0% found this document useful (0 votes)
7 views

Java

This document provides an introduction to Java, highlighting its features such as being platform-independent, object-oriented, and robust. It compares Java with C and C++, detailing differences in language characteristics, data types, and variable types. Additionally, it explains the concept of static variables and blocks, along with examples of Java syntax and programming structure.

Uploaded by

johnnykumar1253
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java

This document provides an introduction to Java, highlighting its features such as being platform-independent, object-oriented, and robust. It compares Java with C and C++, detailing differences in language characteristics, data types, and variable types. Additionally, it explains the concept of static variables and blocks, along with examples of Java syntax and programming structure.

Uploaded by

johnnykumar1253
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

INTRODUCTION TO JAVA

CAREER DEVELOPMENT CENTER


CHENNAI INSTITUTE OF TECHNOLOGY
INTRODUCTION TO JAVA

JAVA:

• Java is a high level, robust, object-oriented and a secure and stable programming
language but it is not a pure object-oriented language because it supports primitive
data types like int, char etc.
• Java is a platform-independent language because it has runtime environment i.e JRE
and API. Here platform means a hardware or software environment in which
anapplication runs.
• Java codes are compiled into byte code or machine-independent code. This byte
code is run on JVM (Java Virtual Machine).
• The syntax of Java is almost the same as C/C++. But java does not support low-level
programming functions like pointers. The codes in Java is always written in the form
of Classes and objects.

Features of Java

1. Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand.

2. Object Oriented
In java, everything is an object which has some data and behaviour. Java can be
easily extended as it is based on Object Model.

3. Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on
compile time error checking and runtime checking.

4. Platform Independent
Unlike other programming languages such as C, C++ etc which are compiled into
platform specific machines. Java is guaranteed to be write-once, run-anywhere
language.

5. Secure
Java is always the first choice. With java secure features it enable us to develop virus
free, temper free system. Java program always runs in Java runtime environment
with almost null interaction with system OS, hence it is more secure.

6. Multithreading
Java multithreading feature makes it possible to write program that can do many
tasks simultaneously. Benefit of multithreading is that it utilizes same memory and
other resources to execute multiple threads at the same time.

1|CHENNAI INSTITUTE OF TECHNOLOGY


INTRODUCTION TO JAVA

7. Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer
architecture, hence a Java program is easy to interpret on any machine.

8. Portable
Java Byte code can be carried to any platform. No implementation dependent
features.

9. High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like
C or C++. But, Java enables high performance with the use of just-in-time compiler.

10. Distributed
Java is also a distributed language. Programs can be designed to run on computer
networks. Java has a special class library for communicating using TCP/IP protocols.

Example: HelloWorld Program


class Hello
{
public static void main(String[] args)
{
System.out.println ("Hello World program");
}
}

• class : class keyword is used to declare classes in Java


• public : It is an access specifier. Public means this function is visible to all.
• static : static is again a keyword used to make a function static. To execute a static
function you do not have to create an Object of the class. The main() method here is
called by JVM, without creating any object for class.
• void : It is the return type, meaning this function will not return anything.
• main : main() method is the most important method in a Java program. This is the
method which is executed, hence all the logic must be inside the main() method. If a
java class is not having a main() method, it causes compilation error.
• String[] args : This represents an array whose type is String and name is args. We
will discuss more about array in Java Array section.

2|CHENNAI INSTITUTE OF TECHNOLOGY


INTRODUCTION TO JAVA

• System.out.println : This is used to print anything on the console like printf in C


language.

DIFFERENCE BETWEEN C AND JAVA

C is a middle-level language. Java is a high-level language.


C is a structural and procedure-oriented Java is an object-oriented programming
programming language. language
It follows the top-down approach to design the It follows the bottom-up approach to design the
application. application.
It is a compiled language. It is an interpreted language.
It is platform dependent. It is platform-independent.
There are 32 keywords in C. Java has 50 keywords.
It does not follow OOPs concepts. It follows OOPs concepts.
It is not secure. It is fully secured language.
It translates the code into machine language so It translates the code into a bytecode that is
that the machine can understand the code. executed by the JVM.
It supports the concept of the pointer. It does not support the concepts of pointers
because of security.
Exception handling is not present in C language. Exception handling is present in Java.
It does not support inheritance that is useful for It supports inheritance that provides code
code reusability. reusability.
There is no concept of threading. It supports the concept of threading.
It supports both call by value and call by It supports only call by value.
reference.
It supports the goto statement. It does not support the goto statement.
Preprocessors are supported in C. Preprocessors are not supported in Java.

DIFFERENCE BETWEEN C++ AND JAVA


C++ is platform-dependent. Java is platform-independent.
C++ is mainly used for system Java is mainly used for application programming. It is
programming. widely used in Windows-based, web-based, enterprise,
and mobile applications.
C++ supports the goto statement. Java doesn't support the goto statement.
C++ supports multiple inheritance. Java doesn't support multiple inheritance through class. It
can be achieved by using interfaces in java.
C++ supports operator overloading. Java doesn't support operator overloading.
C++ supports pointers. You can write a Java supports pointer internally. However, you can't write
pointer program in C++. the pointer program in java. It means java has restricted
pointer support in java.
C++ supports both call by value and call by Java supports call by value only. There is no call by
reference. reference in java.
C++ supports structures and unions. Java doesn't support structures and unions.
C++ doesn't have built-in support for Java has built-in thread support.
threads.
C++ doesn't support documentation Java supports documentation comment (/** ... */) to
comments. create documentation for java source code.
3|CHENNAI INSTITUTE OF TECHNOLOGY
INTRODUCTION TO JAVA

C++ supports virtual keyword Java has no virtual keyword. We can override all non-
static methods by default.
C++ doesn't support >>> operator. Java supports unsigned right shift >>> operator that fills
zero at the top for the negative numbers.
C++ is nearer to hardware. Java is not so interactive with hardware.
C++ is an object-oriented language. Java is also an object-oriented language.
C++ support default arguments Java doesn't support default arguments like C++.

VARIABLE
When we want to store any information, we store it in an address of the computer. Instead
of remembering the complex address where we have stored our information, we name that
address. The naming of an address is known as variable. Variable is the name of memory
location.

Declaration
datatype variableName;

datatype refers to type of variable which can any like: int, float etc.
and variableName can be any like: empId, amount, price etc.

Java Programming language defines mainly three kind of variables.


1. Instance Variables
2. Static Variables (Class Variables)
3. Local Variables

Instance variables in Java


➢ Instance variables are variables that are declare inside a class but outside any
method, constructor or block.
➢ Instance variable are also variable of object commonly known as field or property.
➢ They are referred as object variable.
➢ Each object has its own copy of each variable and thus, it doesn't affect the
instance variable if one object changes the value of the variable.

Example : Instance Variable


class Student
{
String name;
int age;
}

name and age are instance variable of Student class.


4|CHENNAI INSTITUTE OF TECHNOLOGY
INTRODUCTION TO JAVA

Static variables in Java


Static are class variables declared with static keyword. Static variables are initialized only
once. Static variables are also used in declaring constant along with final keyword.

Example : Static Variable


class Student
{
String name;
int age;
static int instituteCode=1101;
}
instituteCode is a static variable. Each object of Student class will share
instituteCode property.

Property of Static Variable


➢ static variable are also known as class variable.
➢ static means to remain constant.
➢ In Java, it means that it will be constant for all the instances created for that class.
➢ static variable need not be called from object.
➢ It is called by classname.static_variable_name

Example
package studytonight;
class Student
{
int a;
static int id = 35;
void change()
{
System.out.println(id);
}
}

public class Example


{
public static void main(String[] args)
{
Student o1 = new Student();
Student o2 = new Student();
5|CHENNAI INSTITUTE OF TECHNOLOGY
INTRODUCTION TO JAVA

o1.change();
Student.id = 1;
o2.change();
o1.change();
}
}
Output
35
1
1

Local variables in Java


Local variables are declared in method, constructor or block. Local variables are initialized
when method, constructor or block start and will be destroyed once its end. Local variable
reside in stack. Access modifiers are not used for local variable.
Example:
void Add(int x, int y)
{
int sum;
sum = x+y;
return sum
}

sum is a local variable.

Scope of A Variable
Scope of a variable decides its accessibility throughout the program. As we have seen
variables are different types so they have their own scope.

Local variable: Scope of local variable is limited to the block in which it is declared. For
example, a variables declared inside a function will be accessible only within this function.

Instance variable: scope of instance variable depends on the access-modifiers (public,


private, default).
• If variable is declared as private then it is accessible within class only.
• If variable is declared as public then it is accessible for all and throughout the
application.
• If variable is declared as default the it is accessible within the same package.

6|CHENNAI INSTITUTE OF TECHNOLOGY


INTRODUCTION TO JAVA

Example
public class Hello World
{
public static void main(String[] args)
{
int a = 10;
for(int i = 0; i<5; i++)
{
System.out.println(i);
}
System.out.println("a = "+a);
System.out.println("i = "+i); // error
}
}

error: cannot find symbol i

DATA TYPES

Java language has a rich implementation of data types. Data types specify size and the type
of values that can be stored in an identifier.

In java, data types are classified into two categories:

➢ Primitive Data type


➢ Non-Primitive Data type

Primitive Data type


A primitive data type can be of eight types:

Primitive Data types


char boolean byte short int long float double

Once a primitive data type has been declared its type can never change, although in most
cases its value can change. These eight primitive types can be put into four groups

Integer
This group includes byte, short, int, long

byte : It is 1 byte(8-bits) integer data type. Value range from -128 to 127. Default value
zero. example: byte b=10;

7|CHENNAI INSTITUTE OF TECHNOLOGY


INTRODUCTION TO JAVA

short : It is 2 bytes(16-bits) integer data type. Value range from -32768 to 32767. Default
value zero. example: short s=11;

int : It is 4 bytes(32-bits) integer data type. Value range from -2147483648 to


2147483647. Default value zero. example: int i=10;

long : It is 8 bytes(64-bits) integer data type. Value range from -9,223,372,036,854,775,808


to 9,223,372,036,854,775,807. Default value zero. example: long l=100012;

Example:
public class Demo
{
public static void main(String[] args)
{
// byte type
byte b = 20;
System.out.println("b= "+b);
// short type
short s = 20;
System.out.println("s= "+s);
// int type
int i = 20;
System.out.println("i= "+i);
// long type
long l = 20;
System.out.println("l= "+l);
}
}
b= 20
s= 20
i= 20
l= 20

Floating-Point Number

This group includes float, double

float : It is 4 bytes(32-bits) float data type. Default value 0.0f. example: float ff=10.3f;

double : It is 8 bytes(64-bits) float data type. Default value 0.0d. example: double
db=11.123;

8|CHENNAI INSTITUTE OF TECHNOLOGY


INTRODUCTION TO JAVA

Example:
public class Demo
{
public static void main(String[] args)
{
// float type
float f = 20.25f;
System.out.println("f= "+f);
// double type
double d = 20.25;
System.out.println("d= "+d);
}}

f= 20.25
d= 20.25

Characters
This group represent char, which represent symbols in a character set, like letters and
numbers.

char : It is 2 bytes(16-bits) unsigned unicode character. Range 0 to 65,535. example: char


c='a';

Example:
public class Demo {
public static void main(String[] args)
{
char ch = 'S';
System.out.println(ch);
char ch2 = '&';
System.out.println(ch2);
char ch3 = '$';
System.out.println(ch3);
}
}
S
&
$

Boolean
This group represent boolean, which is a special type for representing true/false values.
They are defined constant of the language. example: boolean b=true;

9|CHENNAI INSTITUTE OF TECHNOLOGY


INTRODUCTION TO JAVA

Example:
public class Demo
{
public static void main(String[] args)
{
boolean t = true;
System.out.println(t);
boolean f = false;
System.out.println(f);
}
}

true
false

Identifiers in Java
All Java components require names. Name used for classes, methods, interfaces and
variables are called Identifier. Identifier must follow some rules.

Rules:
• All identifiers must start with either a letter( a to z or A to Z ) or currency
character($) or an underscore.
• After the first character, an identifier can have any combination of characters.
• Java keywords cannot be used as an identifier.
• Identifiers in Java are case sensitive, foo and Foo are two different identifiers.
• Some valid identifiers are: int a, class Car, float amount etc.

STATIC

• The static keyword is used for the management of memory mainly.


• The static keyword can be used with Variables, Methods, Block and nested class.
• A static block in a program is a set of statements which are executed by the JVM
(Java Virtual Machine) before the main method.
• At the time of class loading, if we want to perform any task we can define that task
inside the static block, this task will be executed at the time of class loading.
• In a class, any number of a static block can be defined, and this static blocks will be
executed from top to bottom.

Static Block

• Static block executes before the main method while executing program.
• Statements written inside the static block will execute first.
10 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Example
class StaticDemo1
{
static
{
System.out.println("Welcome to Java Programming");
System.out.println("This is static block");
}
public static void main(String as[])
{
System.out.println("This is main() method");
}
}

Example 2: Multiple Static Block


class StaticDemo1
{
static
{
System.out.println("Welcome to Java Programming");
System.out.println("This is static block I");
}
public static void main(String as[])
{
System.out.println("This is main() method");
}
static
{
System.out.println("This is static block II");
}
static
{
System.out.println("This is static block III");
}
}

Initializer Block

• The initializer Block is used to initialize instance data members.


• The initializer block is executed whenever an object is created.
• The Initializer block is copied into Java compiler and then to every constructor.
11 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

• The initialization block is executed before the code in the constructor.

Example
class InitializerDemo1
{
{
System.out.println("Welcome to Java Programming");
System.out.println("This is Initializer block");
}
public InitializerDemo1()
{
System.out.println("Default Constructor invoked");
}
public static void main(String args[])
{
InitializerDemo1 obj = new InitializerDemo1();
System.out.println("This is main() method");
}
}

TYPE CASTING

Casting is a process of changing one type value to another type. In Java, we can cast one
type of value to another type. It is known as type casting.

Example :
int x = 10;
byte y = (byte)x;

In Java, type casting is classified into two types,

• Widening Casting(Implicit)
• Narrowing Casting(Explicitly done)

Widening or Automatic type conversion

Automatic Type casting take place when,

• The two types are compatible


• The target type is larger than the source type

12 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Example:
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
Int value 100
Long value 100
Float value 100.0

Narrowing or Explicit type conversion


When you are assigning a larger type value to a variable of smaller type, then you need to
perform explicit type casting. If we don't perform casting then compiler reports compile
time error.

Example :
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
Double value 100.04
Long value 100
Int value 100

13 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Example – Explicit Type Casting


class CastingDemo1
{
public static void main(String[] args)
{
double d = 120.04;
long l = (long)d;
int i = (int)l;
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}

Conversion of int and double into byte


class Demo2
{
public static void main(String args[])
{
byte b;
int i = 355;
double d = 423.150;
b = (byte) i;
System.out.println("Conversion of int to byte: i = " + i + " b = " + b);
b = (byte) d;
System.out.println("Conversion of double to byte: d = " + d + " b= " + b);
}
}

14 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

DECISION MAKING STATEMENTS


conditional statements are used to perform different actions based on various conditions.
The conditional statement evaluates a condition before the execution of instructions.

There are four types of if statement in Java:

• if statement
• if-else statement
• if-else-if ladder
• nested if statement

if Statement
The if statement is a single conditional based statement that executes only if the provided
condition is true.

if(testcondition)
{
Statements(s);
}

if-else Statement
The if-else statement is used for testing condition. If the condition is true, if block executes
otherwise else block executes.
It is useful in the scenario when we want to perform some operation based on
the false result.
The else block execute only when condition is false.

if(condition)
{
//code for true
}
else
{
//code for false
}

if-else-if ladder Statement


In Java, the if-else-if ladder statement is used for testing conditions. It is used for testing
one condition from multiple statements.
When we have multiple conditions to execute then it is recommend to use if-else-if ladder.

15 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Syntax:
if(condition1)
{
//code for if condition1 is true
}
else if(condition2)
{
//code for if condition2 is true
}
else if(condition3)
{
//code for if condition3 is true
}
...
else
{
//code for all the false conditions
}

Example:
public class IfElseIfDemo1 {
public static void main(String[] args) {
int marks=75;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}
else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
16 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

System.out.println("Invalid!");
}
}
}

Nested if statement
In Java, the Nested if statement is a if inside another if. In this, one if block is created inside
another if block when the outer block is true then only the inner block is executed.

if(condition)
{
//statement
if(condition)
{
//statement
}
}

public class NestedIfDemo1 {


public static void main(String[] args)
{
int age=25;
int weight=70;
if(age>=18)
{
if(weight>50)
{
System.out.println("You are eligible");
}
}
}
}

17 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Switch Statement
The switch statement is used for executing one statement from multiple conditions. it is
similar to an if-else-if ladder.
• Switch statement consists of conditional based cases and a default case.
• In a switch statement, the expression can be of byte, short, char and int type.

Syntax
switch(expression)
{
case value1:
//code for execution;
break; //optional
case value2:
// code for execution
break; //optional
......
......
......
......
Case value n:
// code for execution
break; //optional

default:
code for execution when none of the case is true;
}

Example:

public class SwitchDemo1{


public static void main(String[] args)
{
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Today is Monday";
break;
case 2:
dayName = "Today is Tuesday";
break;
18 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

case 3:
dayName = "Today is Wednesday";
break;
case 4:
dayName = "Today is Thursday";
break;
case 5:
dayName = "Today is Friday";
break;
case 6:
dayName = "Today is Saturday";
break;
case 7:
dayName = "Today is Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println(dayName);
}
}

LOOPING STATEMENT

Loop is designed to execute particular code block till the specified condition is true or all
the elements of a collection(array, list etc) are completely traversed.

Java provides mainly three loop based on the loop structure.


• for loop
• while loop
• do while loop

For Loop
The for loop is used for executing a part of the program repeatedly. When the number of
execution is fixed then it is suggested to use for loop. For loop can be categories into two
type.
1. for loop
2. for-each loop

19 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

For Loop Syntax:


for(initialization;condition;increment/decrement)
{
//statement
}

Initialization
It is the initial part, where we set initial value for the loop. It is executed only once at the
starting of loop. It is optional, if we don’t want to set initial value.

Condition
It is used to test a condition each time while executing. The execution continues until the
condition is false. It is optional and if we don’t specify, loop will be inifinite.

Statement
It is loop body and executed every time until the condition is false.

Increment/Decrement
It is used for set increment or decrement value for the loop.

Example
public class ForDemo1
{
public static void main(String[] args)
{
int n, i;
n=2;
for(i=1;i<=10;i++)
{
System.out.println(n+"*"+i+"="+n*i);
}
}
}

Nested for loop


public class ForDemo2
{
public static void main(String[] args)
{
for(inti=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print("* ");
}
System.out.println();
20 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

}
}
}

for-each Loop
In Java, for each loop is used for traversing array or collection elements. In this loop, there
is no need for increment or decrement operator.

Syntax
for(Type var:array)
{
//code for execution
}
public class ForEachDemo1
{
public static void main(String[] args)
{
inta[]={20,21,22,23,24};
for(int i:a)
{
System.out.println(i);
}
}
}

While Statement

While loop is also used to execute code repeatedly. A control statement. It is used for
iterating a part of the program several times. When the number of iteration is not fixed
then while loop is used.

Syntax
while(condition)
{
//code for execution
}
Example
public class WhileDemo1
{
public static void main(String[] args)
{
inti=1;
while(i<=10)
{

21 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

System.out.println(i);
i++;
}
}
}

Do-While Statement
Do-While loop is used to execute statements again and again. This loop executes at least
once because the loop is executed before the condition is checked. It means loop condition
evaluates after executing of loop body.

The main difference between while and do-while loop is, in do while loop condition
evaluates after executing the loop.

Syntax
do
{
//code for execution
}
while(condition);

Example
public class DoWhileDemo1
{
public static void main(String[] args)
{
inti=1;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}

Break Statement
• In Java, break is a statement that is used to break current execution flow of the
program.
• We can use break statement inside loop, switch case etc.
• If break is used inside loop then it will terminate the loop.
• If break is used inside the innermost loop then break will terminate the innermost
loop only and execution will start from the outer loop.
• If break is used in switch case then it will terminate the execution after the matched
case.

22 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Syntax
jump-statement;
break;

Example

public class BreakDemo1 {


public static void main(String[] args) {
for(inti=1;i<=10;i++){
if(i==8){
break;
}
System.out.println(i);
}
}
}

Continue Statement
In Java, the continue statement is used to skip the current iteration of the loop. It jumps
to the next iteration of the loop immediately.

Syntax
jump-statement;
continue;

Example
public class ContinueDemo1
{
public static void main(String[] args)
{
for(inti=1;i<=10;i++)
{
if(i==5)
{
continue;
}
System.out.println(i);
}
}
}

23 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

OPERATORS

• Operator is a symbol which tells to the compiler to perform some operation.


• Java provides a rich set of operators do deal with various types of operations.

Java operators can be divided into following categories:

• Arithmetic operators
• Relation operators
• Logical operators
• Bitwise operators
• Assignment operators
• Conditional operators
• Misc operators

Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations like: addition, subtraction
etc and helpful to solve mathematical expressions.

Example
class Arithmetic_operators1{
public static void main(String as[])
{
int a, b, c;
a=10;
b=2;
c=a+b;
System.out.println("Addtion: "+c);
c=a-b;
System.out.println("Substraction: "+c);
c=a*b;
System.out.println("Multiplication: "+c);
c=a/b;
System.out.println("Division: "+c);
b=3;
c=a%b;
System.out.println("Remainder: "+c);
a=++a;
System.out.println("Increment Operator: "+a);
a=--a;
System.out.println("decrement Operator: "+a);
}
}

24 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Relation operators
Relational operators are used to test comparison between operands or values.

Example
class Relational_operators1{
public static void main(String as[])

{
int a, b;
a=40;
b=30;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}

Logical operators
Logical Operators are used to check conditional expression.

Example
class Logical_operators1{
public static void main(String as[])
{
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}

Bitwise operators
Bitwise operators are used to perform operations bit by bit.

Example
class Bitwise_operators1{
public static void main(String as[])
{
int a = 50;
int b = 25;
int c = 0;
c = a & b;

25 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

System.out.println("a & b = " + c );


c = a | b;
System.out.println("a | b = " + c );
c = a ^ b;
System.out.println("a ^ b = " + c );
c = ~a;
System.out.println("~a = " + c );
c = a << 2;
System.out.println("a << 2 = " + c );
c = a >> 2;
System.out.println("a >>2 = " + c );

c = a >>> 2;
System.out.println("a >>> 2 = " + c );
}
}

Assignment Operators
Assignment operators are used to assign a value to a variable. It can also be used combine
with arithmetic operators to perform arithmetic operations and then assign the result to
the variable.

Example
class Assignment_operators1{
public static void main(String as[])
{
int a = 30;
int b = 10;
int c = 0;
c = a + b;
System.out.println("c = a + b = " + c );
c += a ;
System.out.println("c += a = " + c );
c -= a ;
System.out.println("c -= a = " + c );
c *= a ;
System.out.println("c *= a = " + c );
a = 20;
c = 25;
c /= a ;
System.out.println("c /= a = " + c );
a = 20;
c = 25;
c %= a ;
System.out.println("c %= a = " + c );
c <<= 2 ;

26 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

System.out.println("c <<= 2 = " + c );


c >>= 2 ;
System.out.println("c >>= 2 = " + c );
c >>= 2 ;
System.out.println("c >>= 2 = " + c );
c &= a ;
System.out.println("c &= a = " + c );
c ^= a ;
System.out.println("c ^= a = " + c );
c |= a ;
System.out.println("c |= a = " + c );
}
}

Conditional operator
It is also known as ternary operator because it works with three operands. It is short
alternate of if-else statement. It can be used to evaluate Boolean expression and return
either true or false value

Example
class Conditional_operators1{
public static void main(String as[])
{
int a, b;
a = 20;
b = (a == 1) ? 30: 40;
System.out.println( "Value of b is : " + b );
b = (a == 20) ? 30: 40;
System.out.println( "Value of b is : " + b );
}
}

instanceOf operator
It is a java keyword and used to test whether the given reference belongs to provided
type or not. Type can be a class or interface. It returns either true or false.

Example
class instanceof_operators1{
public static void main(String as[])
{
String a = "Welcome To Java";
boolean b = a instanceof String;
System.out.println( b );
}
}
27 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

INTRODUCTION TO CLASS

➢ A class is declared by use of the keyword class.


➢ A General form of class declaration is
Class classname
{
type instance-variable1;
type instance-variable2;
//-----
type instance-variableN;

type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
//
type methodnameN(parameter-list)
{
// body of method
}

➢ The data or variable defined within a class are called instance variables.
➢ The code is contained within method.
➢ The variables and methods defined within a class are called members of the class.
➢ The instance variables are acted upon and accessed by the methods defined for that
class.
➢ The variables defined within a class are called instance variables because each
instance of the class contains its own copy of these variables.
➢ The data for one object is separate and unique from the data for another object.

A Simple Class
Class Add
{
int a;
int b;
int sum;
}
28 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

➢ A class defines a new type of data is called Add, using this name for object creation.
➢ A class declaration only creates a template it does not create an actual object.
➢ To create Add object by using the following statements
Add a1 = new Add(); // create a Add object called a1
➢ Every Add object will contain its own copies of the instance variables a,b and sum.
➢ To access these variables, use the dot(.) operator. The dot operator links the name of
the object with the name of an instance variables.
a1.a = 10;
a1.b = 20;
➢ The statement tells the compiler to assign the copy of a and b contained within the
a1 object the values of 10 and 20.

Example:
class Example
{
int a;
int b;
int c;
}
class Examplemain
{
public static void main(String [] args)
{
Example E = new Example();
int sum=0;
E.a=12;
E.b=23;
E.c = 34;
sum = E.a+E.b+E.c;
System.out.println("Sum Value="+sum);
}
}

Output:
Sum Value=69

Each object has its own copies of the instance variables. So to create two objects for
Example class, each has its own copy of a, b and c.

29 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Example:
class Example
{
int a;
int b;
int c;
}
class Examplemain
{
public static void main(String [] args)
{
Example E1 = new Example();
Example E2 = new Example();
int sum=0;

E1.a=12;
E1.b=23;
E1.c = 34;

E2.a=10;
E2.b=20;
E2.c =30;

sum = E1.a+E1.b+E1.c;
System.out.println("Sum Value="+sum);

sum = E2.a+E2.b+E2.c;
System.out.println("Sum Value="+sum);

}
}

Output:
Sum Value=69
Sum Value=60

Declaring Objects:

➢ Object is an instance of a class while class is a blueprint of an object. An object


represents the class and consists of properties and behavior.

30 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

➢ Properties refer to the fields declared with in class and behavior represents to the
methods available in the class.
➢ In real world, we can understand object as a cell phone that has its properties like:
name, cost, color etc and behavior like calling, chatting etc.
➢ So we can say that object is a real world entity. Some real world objects are: ball, fan,
car etc.
➢ There is a syntax to create an object in the Java
className variable_name = new className();
➢ className is the name of class that can be anything like: Student that we declared
in the above example.
➢ variable_name is name of reference variable that is used to hold the reference of
created object.
➢ The new is a keyword which is used to allocate memory for the object.
Student std = new Student();
➢ std is an object that represents the class Student during runtime.
➢ The new keyword creates an actual physical copy of the object and assigns it to the
std variable.
➢ It will have physical existence and get memory in heap area.
➢ The new operator dynamically allocates memory for an object.

Example
public class Student
{
String name;
int rollno;
int age;
void Disp()
{
System.out.println("Name: "+name);
System.out.println("Roll Number: "+rollno);
System.out.println("Age: "+age);
}
public static void main(String[] args)
{
Student s1 = new Student();
/ / Accessing and property value
s1.name = "Ramesh";
s1.rollno = 253;
s1.age = 25;
// Calling method
s1.Disp();
}
}

31 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Example 2
public class Student{
String name;
int rollno;
int age;

void Disp()
{
System.out.println("Name: "+name);
System.out.println("Roll Number: "+rollno);
System.out.println("Age: "+age);
}
public static void main(String[] args)
{
Student s1 = new Student();
// Calling method
s1.Disp();
}
}
Output:
Name: null
Roll Number: 0
Age: 0

Methods in Java

➢ Method in Java is similar to a function defined in other programming languages.


➢ Method describes behavior of an object.
➢ A method is a collection of statements that are grouped together to perform an
operation.
➢ For example, if we have a class Human, then this class should have methods like
eating(), walking(), talking() etc, which describes the behavior of the object.
➢ Declaring method is similar to function.
➢ The syntax to declare the method in Java.

return-type methodName(parameter-list)
{
//body of method
}

➢ return-type refers to the type of value returned by the method.


➢ methodName is a valid meaningful name that represent name of a method.
➢ parameter-list represents list of parameters accepted by this method.
32 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

➢ Method may have an optional return statement that is used to return value to the
caller function.

Example
import java.util.*;
public class Student{
String name;
int rollno;
int age;

void Get()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter The Student Name");
name = sc.nextLine();
System.out.println("Enter The Roll Number");
rollno = sc.nextInt();
System.out.println("Enter The Age");
age = sc.nextInt();
}
void Disp()
{
System.out.println("Name: "+name);
System.out.println("Roll Number: "+rollno);
System.out.println("Age: "+age);
}
public static void main(String[] args)
{
Student s1 = new Student();
// Calling method
s1.Get();
s1.Disp();
}
}

Output:
Enter The Student Name
Ravikumar
Enter The Roll Number
12
Enter The Age
21
Name: Ravikumar
Roll Number: 12
Age: 21

33 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Returning a Value:

import java.util.*;
class Arithmetic
{
int a,b;
void Get()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter The First Number");
a = sc.nextInt();
System.out.println("Enter The Second Number");
b = sc.nextInt();
}
int Add()
{
return a+b;
}
void Disp()
{
System.out.println("A Value="+a);
System.out.println("B Value="+b);
}
public static void main(String [] args)
{
Arithmetic ar = new Arithmetic();
ar.Get();
ar.Disp();
System.out.println("Sum Value="+ar.Add());
}
}

Output
Enter The First Number
23
Enter The Second Number
12
A Value=23
B Value=12
Sum Value=35

Adding a Method that takes Parameters


➢ Parameters allow a method to be generalized.
➢ A parameterized method can operate on a variety of data and/or be used in a
number of different situations.

34 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Example

import java.util.*;
class Arithmetic
{
int a,b;
void Get(int x,int y)
{
a=x;
b=y;
}
int Add()
{
return a+b;
}
void Disp()
{
System.out.println("A Value="+a);
System.out.println("B Value="+b);
}
public static void main(String [] args)
{
Arithmetic ar = new Arithmetic();
ar.Get(12,23);
ar.Disp();
System.out.println("Sum Value="+ar.Add());
}
}

Output
A Value=12
B Value=23
Sum Value=35

Return Object from Method


➢ In some scenario there can be need to return object of a class to the caller function.
➢ In this case, we must specify class name in the method definition.

class Demo{
int a;
double b;
int c;
Demo(int m, double d, int a)
{
a = m;
b = d;

35 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

c = a;
}
}
class MethodDemo{
static Demo get(int x, int y)
{
return new Demo(x * y, (double)x / y, (x + y));
}
public static void main(String[] args)
{
Demo ans = get(25, 5);
System.out.println("Multiplication = " + ans.a);
System.out.println("Division = " + ans.b);
System.out.println("Addition = " + ans.c);
}
}
Output:
Multiplication = 0
Division = 5.0
Addition = 125

Parameter Vs. Argument in a Method


➢ Parameter is variable defined by a method that receives value when the
method is called.
➢ Parameter are always local to the method they dont have scope outside
the method. While argument is a value that is passed to a method when
it is called.

There are two ways to pass an argument to a method

1. call-by-value : In this approach copy of an argument value is pass to a method.


Changes made to the argument value inside the method will have no effect on the
arguments.
2. call-by-reference : In this reference of an argument is pass to a method. Any
changes made inside the method will affect the argument value.
36 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

NOTE: However there is no concept of call-by-reference in Java. Java supports


only call by value.

public class Test


{
public void callByValue(int x)
{
x=100;
}
public static void main(String[] args)
{
int x=50;
Test t = new Test();
t.callByValue(x); //function call
System.out.println(x);
}
}

In the above example, value passed to the method does not change even after modified
in the method. It shows that changes made to the value was local and argument was
passed as call-by-value.

37 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

CONSTRUCTOR
➢ A constructor is a special method that is used to initialize an object.
➢ Every class has a constructor either implicitly or explicitly.
➢ A constructor has same name as the class name in which it is declared.
➢ Constructor must have no explicit return type.
➢ Constructor in Java cannot be abstract, static, final or synchronized.

Types of Constructor
➢ Default Constructor
➢ Parameterized Constructor

Default Constructor
➢ A constructor is said to be default constructor if it does not have any parameter.
➢ Default constructor can be either user defined or provided by JVM.

Example Program
class DefEx
{
DefEx() // Default Constructor
{
int a=10;
int b=5;
int s;
s=a+b;
System.out.println("Sum Value= "+s);
}
public static void main(String args[])
{
DefEx obj=new DefEx(); // constructor calling
}
}

Output:
Sum Value = 15

Parameterized Constructor:
➢ A Constructor is called Parameterized Constructor when it accepts a specific
number of parameters. To initialize data members of a class with distinct values.

Example:
public class Example
{
String name;
int age;
Example(String s, int a) // parameterized constructor
{

38 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

name = s;
age = a;
}
void disp()
{
System.out.println(“Name =”+name);
System.out.println(“Age =”+age);
}
public static void main(String [] args)
{
Example e = new Example(“Kumar”,23); // constructor calling
e.disp();
}
}

POLYMORPHISM
➢ Polymorphism is a concept of object oriented programming that deal with multiple
forms.
➢ There are two types of polymorphism in Java
o Static/Compile Time Polymorphism
o Runtime/Dynamic Polymorphism

1. Static/compile time polymorphism


➢ This polymorphism is resolved during the compiler time and is achieved
through the method overloading. (Compile-time Polymorphism)
➢ Static Polymorphism in Java decides which method to execute during
compile time.

Example – Static/Compile Time Polymorphism


- Method overloading
- Constructor overloading

Method Overloading
➢ Method overloading can be done by changing number of arguments or by
changing the data type of arguments.
➢ If two or more method have same name and same parameter list but differs in
return type cannot be overloaded.
➢ Overloaded method can have different access modifiers and it does not have any
significance in method overloading.
➢ There are two different types of method overloading in java

39 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Example:
1. Method Overloading By Changing Data Type of Arguments

class Calculate
{
void sum (int a, int b)
{
System.out.println("sum is"+(a+b)) ;
}
void sum (float a, float b)
{
System.out.println("sum is"+(a+b));
}
public static void main (String[] args)
{
Calculate cal = new Calculate();
cal.sum (8,5); //sum(int a, int b) is method is called.
cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
}
}

Output:
Sum is = 13
Sum is = 8.4
Note
sum() method is overloaded two times. The first takes two integer arguments, the
second takes two float arguments.

2. Method Overloading By Changing Number Of Arguments


class Demo
{
void multiply(int l, int b)
{
System.out.println("Result is"+(l*b)) ;
}
void multiply(int l, int b,int h)
{
System.out.println("Result is"+(l*b*h));
}
public static void main(String[] args)
{
Demo ar = new Demo();
ar.multiply(8,5); //multiply(int l, int b) is method is called
ar.multiply(4,6,2); //multiply(int l, int b,int h) is called
}
}

40 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Output:
Result is = 40
Result is = 48
Note:
The multiply() method is overloaded twice. The first method takes two
arguments and the second method takes three arguments.

Constructor Overloading
➢ A constructor can also be overloaded. Overloaded constructors are differentiated on
the basis of their type of parameters or number of parameters.
➢ Constructor overloading is not much different than method overloading.
➢ Constructor overloading you have multiple constructor with different signature but
only difference is that constructor doesn't have return type.

Example
class Box{
double width;
double depth;
double height;
double volume() {
return width*depth*height;
}
Box(){
width=-1;
depth=-1;
height=-1;
}
Box(double width,double depth,double height){
this.width=width;
this.depth=depth;
this.height=height;
}
Box(double len){
width=depth=height=len;
}
Box(Box ob){ //object
width=ob.width;
depth=ob.depth;
height=ob.height;
}
}
public class Main {
public static void main(String[] args) {
Box b1=new Box();
Box b2=new Box(10,20,30);
Box b3=new Box(7);

41 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Box b4=new Box(b2);


double vol;
vol=b1.volume();
System.out.println("Volume is "+vol);
vol=b2.volume();
System.out.println("Volume is "+vol);
vol=b3.volume();
System.out.println("Volume is "+vol);
vol=b4.volume();
System.out.println("Volume is "+vol);
}
}

Access Modifiers in Java


➢ Access modifiers are keywords in Java that are used to set accessibility.
➢ An access modifier restricts the access of a class, constructor, data member and
method in another class.
➢ Java language has four access modifier to control access level for classes and its
members.
• Default: Default has scope only inside the same package
• Public: Public has scope that is visible everywhere
• Protected: Protected has scope within the package and all sub classes
• Private: Private has scope only within the classes

Java also supports many non-access modifiers, such as static, abstract, synchronized,
native, volatile, transient etc.

Default Access Modifier


➢ If we don’t specify any access modifier then it is treated as default modifier.
➢ It is used to set accessibility within the package.
➢ It means we cannot access its method or class from outside the package.
➢ It is also known as package accessibility modifier.

Example:
Demo.java
package package1;
public class Demo
{
int a = 10;
// default access modifier
void show()
{
System.out.println(a);
}
}
42 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Test.java
import package1.Demo;
public class Test {
public static void main(String[] args) {
Demo demo = new Demo();
demo.show(); // compile error
}
}

Output : Compile Time Error

Public Access Modifier


➢ public access modifier is used to set public accessibility to a variable, method or a
class.
➢ Any variable or method which is declared as public can be accessible from
anywhere in the application.

Example
Demo.java
package package1;
public class Demo {
int a = 10;
// public access modifier
public void show() {
System.out.println(a);
}
}

Test.java
package package2;
import package1.Demo;
public class Test {
public static void main(String[] args) {
Demo demo = new Demo();
demo.show();
}
}

Output : 10

Protected Access Modifier


➢ Protected modifier protects the variable, method from accessible from outside the
class.
➢ It is accessible within class, and in the child class (inheritance) whether child
is located in the same package or some other package.

43 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Example:
Demo.java
package package1;
public class Demo {
int a = 10;
// public access modifier
protected void show() {
System.out.println(a);
}
}

Test.java
package package2;
import package1.Demo;
public class Test extends Demo{
public static void main(String[] args) {
Test test = new Test();
test.show();
}
}
Output: 10

Private Access Modifier


➢ Private modifier is most restricted modifier which allows accessibility within same
class only. We can set this modifier to any variable, method or even constructor as
well.

Example:
Demo.java
class Demo {
int a = 10;
private void show() {
System.out.println(a);
}
}

Test.java
public class Test {
public static void main(String[] args) {
Demo demo = new Demo();
demo.show(); // compile error
}
}
Output: The method show() from the type Demo is not visible

44 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

INHERITANCE:
➢ Inheritance is one of the key features of Object Oriented Programming.
➢ Inheritance provided mechanism that allowed a class to inherit property of
another class.
➢ When a Class extends another class it inherits all non-private members including
fields and methods.
➢ Inheritance defines is-a relationship between a Super class and its Sub class.
extends and implements keywords are used to describe inheritance in Java.

Example:
class Vehicle
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class
}
• Vehicle is super class of Car.
• Car is sub class of Vehicle.
• Car IS-A Vehicle.

Need For Inheritance


➢ It promotes the code reusability i.e the same methods and variables which are
defined in a parent/super/base class can be used in the child/sub/derived class.
➢ It promotes polymorphism by allowing method overriding.

Disadvantages of Inheritance
➢ Main disadvantage of using inheritance is that the two classes (parent and child
class) gets tightly coupled.
➢ This means that if we change code of parent class, it will affect to all the child classes
which is inheriting/deriving the parent class, and hence, it cannot be independent
of each other.

Example:
class Parent
{
public void p1()
{
System.out.println("Parent method");
}
}
public class Child extends Parent {
public void c1()
{
System.out.println("Child method");
}
45 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

public static void main(String[] args)


{
Child cobj = new Child();
cobj.c1(); //method of Child class
cobj.p1(); //method of Parent class
}
}

Types of Inheritance
Java mainly supports only three types of inheritance that are listed below.
1. Single Inheritance
2. Multilevel Inheritance
3. Heirarchical Inheritance

NOTE: Multiple inheritance is not supported in java

Single Inheritance
➢ When a class extends to another class then it forms single inheritance. In the below
example, we have two classes in which class A extends to class B that forms single
inheritance.

Example
class A
{
int a = 10;
}

class B extends A
{
int b = 20;
void show()
{
System.out.println(“ A Value = “+a);
System.out.println(“ B Value=”+b);
}
}

class SingleEx
{
public static void main(String[] args)
{
B b = new B();
b.show();
}
}

46 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Multilevel Inheritance
➢ When a class extends to another class that also extends some other class forms a
multilevel inheritance.
➢ A class C extends to class B that also extends to class A and all the data members an
methods of class A and B are now accessible in class C.

Example:

class A
{
int a = 10;
}
class B extends A
{
int b = 20;
}
class C extends B
{
int c = 30;
void show()
{
System.out.println(“ A Value=”+a);
System.out.println(“B Value=”=b);
System.out.println(“C Value=”+c);
}
}
class MultiEx
{
public static void main(String[] args)
{
C c = new C();
c.show();
}
}

Hierarchical Inheritance
➢ When a class is extended by two or more classes, it forms hierarchical inheritance.
For example, class B extends to class A and class C also extends to class A in that
case both B and C share properties of class A.

Example
class A
{
public void methodA()
{

47 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

System.out.println("method of Class A");


}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B b = new B();
C c = new C();
D d = new D();
//All classes can access the method of class A
b.methodA();
c.methodA();
d.methodA();
}
}

Super Keyword
➢ In Java, super keyword is used to refer to immediate parent class of a child class.
➢ In other words super keyword is used by a subclass whenever it need to refer to its
immediate super class.

48 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Example 1: Child Class Referring Parent Class Property Using super Keyword
class Parent
{
int a;
}
class Child extends Parent {
int a;
public void Disp()
{
super.a =10;//refers to parent class member
a = 20;
System.out.println(super.a+" and "+a);
}
public static void main(String[] args)
{
Child obj = new Child();
obj.Disp();
}
}

Example 2: Child Class Referring Parent Class Method Using super Keyword
class Parent
{
int a;
public void Disp()
{
a=10;
System.out.println("Parent Class a value="+a);
}
}
class Child extends Parent {
int a;
public void Disp()
{
super.Disp(); //calling Parent class details() method
a=20;
System.out.println("B Class a Value="+a);
}
public static void main(String[] args)
{
Child obj = new Child();
obj.Disp();
}
}

49 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Example 3: Using super keyword To Call Parent Class Constructor


class Parent
{
String name;
public Parent(String n)
{
name = n;
}
}
public class Child extends Parent {
String name;
public Child(String s1, String s2)
{
super(s1); //passing argument to parent class constructor
this.name = s2;
}
public void details()
{
System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
Child cobj = new Child("Parent","Child");
cobj.details();
}
}

Method Overriding (Run Time Polymorphism)


➢ Method overriding is a process of overriding base class method by derived class
method with more specific definition.
➢ Method overriding performs only if two classes have is-a relationship. It mean class
must have inheritance. In other words, It is performed between two classes using
inheritance relation.
➢ In overriding, method of both class must have same name and equal number
of parameters.
➢ Method overriding is also referred to as runtime polymorphism because calling
method is decided by JVM during runtime.

Rules for Method Overriding


1. Method name must be same for both parent and child classes.
2. Access modifier of child method must not restrictive than parent class method.
3. Private, final and static methods cannot be overridden.
4. There must be an IS-A relationship between classes (inheritance).

50 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Example:
class Animal
{
public void eat()
{
System.out.println("Eat all eatables");
}
}
class Dog extends Animal
{
public void eat() //eat() method overridden by Dog class.
{
System.out.println("Dog like to eat meat");
}
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
}
}

Java does not allows method overriding if child class has more restricted access
modifier than parent class.

Example:
class Animal
{
public void eat()
{
System.out.println("Eat all eatables");
}
}
class Dog extends Animal
{
protected void eat() //error
{
System.out.println("Dog like to eat meat");
}
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
}
}

51 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Dynamic Method Dispatch (Run Time Polymorphism)


➢ Dynamic method dispatch is a mechanism by which a call to an overridden method
is resolved at runtime.
➢ This is how java implements runtime polymorphism.
➢ When an overridden method is called by a reference, java determines which version
of that method to execute based on the type of object it refer to.

Example:
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}
class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
// obtain a reference of type A
A ref;
// ref refers to an A obje ct
ref = a;

52 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

// calling A's version of m1()


ref.m1();
// now ref refers to a B object
ref = b;
// calling B's version of m1()
ref.m1();
// now ref refers to a C object
ref = c;
// calling C's version of m1()
ref.m1();
}
}

Output
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method

Difference Between Static Binding and Dynamic Binding

Static binding means when the type of object which is invoking the method is determined
at compile time by the compiler.

Dynamic binding means when the type of object which is invoking the method is
determined at run time by the compiler.

53 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

“this” Keyword

➢ In Java, “this” is a keyword which is used to refer current object of a class. we can
refer any member of the class. It means we can access any instance variable and
method by using this keyword.
➢ The main purpose of using this keyword is to solve the confusion when we have
same variable name for instance and local variables.
➢ We can use this keyword for the following purpose.

• this keyword is used to refer to current object.

• this is always a reference to the object on which method was invoked.

• this can be used to invoke current class constructor.

• this can be passed as an argument to another method.

Example:
In this example, we have three instance variables and a constructor that have three
parameters with same name as instance variables. Now, we will use this to assign values
of parameters to instance variables.
class Demo
{
double width, height, depth;
Demo (double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
public static void main(String[] args) {
Demo d = new Demo(10,20,30);
System.out.println("width = "+d.width);
System.out.println("height = "+d.height);
System.out.println("depth = "+d.depth);
}
}

Output:
width = 10.0
height = 20.0
depth = 30.0

54 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Calling Constructor using this keyword

class Demo
{
Demo ()
{
// Calling constructor
this("Welcome To Java World");
}
Demo(String str){
System.out.println(str);
}
public static void main(String[] args) {
Demo d = new Demo();
}
}

Output:
Welcome To Java World

Accessing Method using this keyword


➢ “this” keyword that allows to access method. We can access method using object
reference too but if we want to use implicit object provided by Java then use this
keyword.

Example
class Demo
{
public void getName()
{
System.out.println("Welcome To Java");
}
public void display()
{
this.getName();
}
public static void main(String[] args) {
Demo d = new Demo();
d.display();
}
}

55 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Output:
Welcome To Java

Instance Variable Hiding

➢ Instance variable hiding refers to a state when instance variables of the same name
are present in super class and subclass. Now if we try to access using subclass object
then instance variable of subclass hides instance variable of super class irrespective
of its return types.
➢ In Java, if there is a local variable in a method with the same name as the instance
variable, then the local variable hides the instance variable. If we want to reflect the
change made over to the instance variable, this can be achieved with the help of this
reference.

Example
class Demo
{
double width, height, depth;
Demo (double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}
public static void main(String[] args) {
Demo d = new Demo(10,20,30);
System.out.println("width = "+d.width);
System.out.println("height = "+d.height);
System.out.println("depth = "+d.depth);
}
}

Output:
width = 10.0
height = 20.0
depth = 30

56 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

GARBAGE COLLECTION

➢ Java garbage collection is the process of releasing unused memory occupied by


unused objects. This process is done by the JVM automatically because it is essential
for memory management.
➢ When a Java programs run on the JVM, objects are created on the heap, which is a
portion of memory dedicated to the program. Eventually, some objects will no
longer be needed.
➢ When there is no reference to an object, then that object is assumed to be no longer
needed and the memory occupied by the object are released. This technique is
called Garbage Collection.
➢ The garbage collection is a part of the JVM and is an automatic process done by JVM.
We do not need to explicitly mark objects to be deleted. However, we can request to
the JVM for garbage collection of an object but ultimately it depends on the JVM to
call garbage collector.
➢ Unlike C++ there is no explicit way to destroy object.

Advantages of Garbage Collection


1. Programmer doesn't need to worry about dereferencing an object.
2. It is done automatically by JVM.
3. Increases memory efficiency and decreases the chances for memory leak.

finalize() Method
➢ Sometime an object will need to perform some specific task before it is destroyed
such as closing an open connection or releasing any resources held. To handle such
situation finalize() method is used.
➢ The finalize() method is called by garbage collection thread before collecting
object. Its the last chance for any object to perform cleanup utility.

Signature of finalize() method

protected void finalize()


{
//finalize-code
}

57 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

PACKAGE:

➢ Package is a collection of related classes. Java uses package to group Related classes,
interfaces and sub-packages in any Java project.
➢ Package as a folder or a directory that is used to store similar files.
➢ In Java, packages are used to avoid name conflicts and to control access of class,
interface and enumeration etc.
➢ Using package it becomes easier to locate the related classes and it also provides a
good structure for projects with hundreds of classes and other files.

Types of Java Package


Package can be built-in and user-defined, Java provides rich set of built-in packages in form
of API that stores related classes and sub-packages.

• Built-in Package: math, util, lang, i/o etc are the example of built-in
packages.
• User-defined-package: Java package created by user to categorize their
project's classes and interface are known as user-defined packages.

How to Create a Package


Creating a package in java is quite easy, simply include a package command followed by
name of the package as the first statement in java source file.

package mypack;
public class employee
{
String empId;
String name;
}

The above statement will create a package with name mypack in the project directory.

Java uses file system directories to store packages. For example the .java file for any class
you define to be part of mypack package must be stored in a directory called mypack.

➢ Package statement must be first statement in the program even before the import
statement.
➢ A package is always defined as a separate folder having the same name as the
package name.
➢ Store all the classes in that package folder.
➢ All classes of the package which we wish to access outside the package must be
declared public.
➢ All classes within the package must have the package statement as its first line.
➢ All classes of the package must be compiled before use.

58 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Example
//save as FirstProgram.java
package learnjava;
public class FirstProgram{
public static void main(String args[]) {
System.out.println("Welcome to package example");
}
}

How to compile Java programs inside packages?


javac -d . FirstProgram.java

How to run Java package program?


java learnjava.FirstProgram

How to import Java Package


To import java package into a class, we need to use java import keyword which is used to
access package and its classes into the java program.

There are 3 different ways to refer to any class that is present in a different package:
1. Without import the package
2. Import package with specified class
3. Import package with all classes Accessing package without import keyword

59 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Example
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B {
public static void main(String args[]) {
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}

Import the Specific Class


Example:
//save by Demo.java
package pack;
public class Demo {
public void msg() {
System.out.println("Hello");
}
}

//save by Test.java
package mypack;
import pack.Demo;
class Test {
public static void main(String args[]) {
Demo obj = new Demo();
obj.msg();
}
}

60 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Import all classes of the package

//save by First.java
package learnjava;
public class First{
public void msg() {
System.out.println("Hello");
}
}

//save by Second.java
package Java;
import learnjava.*;
class Second {
public static void main(String args[]) {
First obj = new First();
obj.msg();
}
}

Java Abstract class and methods


Abstract Class

A class which is declared using abstract keyword known as abstract class. An abstract
class may or may not have abstract methods. We cannot create object of abstract class.

It is used to achieve abstraction but it does not provide 100% abstraction because it can
have concrete methods.
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It is used for abstraction.

Syntax:
abstract class class_name { }

Abstract method
Method that are declared without any body within an abstract class are called abstract
method. The method body will be defined by its subclass. Abstract method can never be
final and static. Any class that extends an abstract class must implement all the abstract
methods.

61 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Syntax:
abstract return_type function_name (); //No definition

1. Abstract classes are not Interfaces. They are different, we will study this when we will
study Interfaces.
2. An abstract class may or may not have an abstract method. But if any class has even a
single abstract method, then it must be declared abstract.
3. Abstract classes can have Constructors, Member variables and Normal methods.
4. Abstract classes are never instantiated.
5. When you extend Abstract class with abstract method, you must define the abstract
method in the child class, or make the child class abstract.

Example
abstract class A
{
abstract void callme();
}
class B extends A
{
void callme()
{
System.out.println("Calling...");
}
public static void main(String[] args)
{
B b = new B();
b.callme();
}
}

Abstract class with non-abstract method


Abstract classes can also have non abstract methods along with abstract methods. But
remember while extending the class, provide definition for the abstract method.

Example
abstract class A
{
abstract void callme();
public void show()
{
System.out.println("this is non-abstract method");
}

62 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

class B extends A
{
void callme()
{
System.out.println("Calling...");
}
public static void main(String[] args)
{
B b = new B();
b.callme();
b.show();
}
}

Abstraction using Abstract class


Abstraction is an important feature of OOPS. It means hiding complexity and show
functionality only to the user. Abstract class is used to provide abstraction. Although it does
not provide 100% abstraction because it can also have concrete method.

Example
abstract class Vehicle
{
public abstract void engine();
}
public class Car extends Vehicle {
public void engine()
{
System.out.println("Car engine");
// car engine implementation
}
public static void main(String[] args)
{
Vehicle v = new Car();
v.engine();
}
}

63 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

INTERFACE
➢ Interface is a concept which is used to achieve abstraction in Java.
➢ This is the only way by which we can achieve full abstraction. Interfaces are
syntactically similar to classes, but you cannot create instance of an Interface and
their methods are declared without any body.
➢ It can have When you create an interface it defines what a class can do without
saying anything about how the class will do it.
➢ It can have only abstract methods and static fields. However, from Java 8, interface
can have default and static methods and from Java 9, it can have private
methods as well.
➢ When an interface inherits another interface extends keyword is used whereas
class use implements keyword to inherit an interface.

Advantages of Interface
➢ It Support multiple inheritance
➢ It helps to achieve abstraction
➢ It can be used to achieve loose coupling.

Syntax:
interface interface_name {
// fields
// abstract/private/default methods
}

Interface Key Points


• Methods inside interface must not be static, final, native.
• All variables declared inside interface are implicitly public, static and final.
• All methods declared inside interfaces are implicitly public and abstract, even if you
don't use public or abstract keyword.
• Interface can extend one or more other interface.
• Interface cannot implement a class.
• Interface can be nested inside another interface.

Example

interface I1
{
void Disp();
}

class IntExample implements I1


{
public void Disp()

64 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

{
System .out. print in (“Interface Example”);
}
public static void main (String[] arg)
{
IntExample ex = new IntExample();
Ex.Disp();
}
}

Interfaces supports Multiple Inheritance


classes in Java doesn't support multiple inheritance, but a class can implement more than
one interfaces.

Example
interface Moveable
{
boolean isMoveable();
}
interface Rollable
{
boolean isRollable
}
class Tyre implements Moveable, Rollable
{
int width;
boolean isMoveable()
{
return true;
}
boolean isRollable()
{
return true;
}
public static void main(String args[])
{
Tyre tr = new Tyre();
System.out.println(tr.isMoveable());
System.out.println(tr.isRollable());
}
}
65 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Interface extends other Interface


➢ Interface can inherit to another interface by using extends keyword.
➢ Interface just inherit, does not provide implementation. Implementation can be
provided by a class only.

interface NewsPaper
{
news();
}

interface Magazine extends NewsPaper


{
colorful();
}

Difference between an interface and an abstract class?

Interface
Abstract class
Interface is a Java Object containing method
Abstract class is a class which contain one or declaration but no implementation. The
more abstract methods, which has to be classes which implement the Interfaces
implemented by its sub classes. must provide the method definition for all
the methods.
Abstract class is a Class prefix with an abstract Interface is a pure abstract class which
keyword followed by Class definition. starts with interface keyword.
Abstract class can also contain concrete Whereas, Interface contains all abstract
methods. methods and final variable declarations.
Abstract classes are useful in a situation that
Some general methods should be implemented Interfaces are useful in a situation that all
and specialization behavior should be properties should be implemented.
implemented by child classes.

Static methods in Interface

interface Abc{
// static method
static void msg(){
System.out.println("This is static method");
}
// Abstract method
void greet(String msg);
}
66 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

public class Demo implements Abc{


public void greet(String msg){ // implementing abstract method
System.out.println(msg);
}
public static void main(String[] args) {
Demo d = new Demo();
Abc.msg(); // calling static method
d.greet("Say Hi"); // calling abstract method
}
}

Private methods In Interface


interface Abc{
// Default method
default void msg(){
greet();
}
// Private method
private void greet() {
System.out.println("This is private method");
}
}
public class Demo implements Abc{
public static void main(String[] args) {
Demo d = new Demo();
d.msg(); // calling default method
}
}

Nested Class

➢ A class defined within another class is known as Nested class. The scope of the
nested class is bounded by the scope of its enclosing class.

Syntax:
class Outer{
//class Outer members
class Inner{
//class Inner members
}
} //closing of class Outer

67 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Advantages of Nested Class


1. It is a way of logically grouping classes that are only used in one place.
2. It increases encapsulation.
3. It can lead to more readable and maintainable code.

Static Nested Class


➢ If the nested class i.e the class defined within another class, has static modifier
applied in it, then it is called as static nested class.
➢ Static nested classes can access only static members of its outer class i.e it cannot
refer to non-static members of its enclosing class directly.

Non-static Nested class


➢ Non-static Nested class is the most important type of nested class.
➢ It is also known as Inner class.
➢ It has access to all variables and methods of Outer class including its private data
members and methods and may refer to them directly.
➢ But the reverse is not true, that is, Outer class cannot directly access members of
Inner class. Inner class can be declared private, public, protected, or with default
access whereas an Outer class can have only public or default access.
➢ A non-static Nested class that is created outside a method is called Member inner
class.
➢ A non-static Nested class that is created inside a method is called local inner class.
➢ If you want to invoke the methods of local inner class, you must instantiate this class
inside the method.
➢ We cannot use private, public or protected access modifiers with local inner class.
Only abstract and final modifiers are allowed.

Example
class Outer
{
public void display()
{
Inner in=new Inner();
in.show();
}
class Inner
{
public void show()
{
System.out.println("Inside inner");
}
}
}

68 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

class Test
{
public static void main(String[] args)
{
Outer ot = new Outer();
ot.display();
}
}

Example of Inner class inside a method(local inner class)


class Outer
{
int count;
public void display()
{
for(int i=0;i<5;i++)
{
//Inner class defined inside for loop
class inner
{
public void show()
{
System.out.println("Inside inner "+(count++));
}
}
Inner in=new Inner();
in.show();
}
}
}
class Test
{
public static void main(String[] args)
{
Outer ot = new Outer();
ot.display();
}
}

Example of Inner class instantiated outside Outer class


class Outer
{
int count;
public void display()
{
Inner in = new Inner();
69 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

in.show();
}
class Inner
{
public void show()
{
System.out.println("Inside inner "+(++count));
}
}
}
class Test
{
public static void main(String[] args)
{
Outer ot = new Outer();
Outer.Inner in = ot.new Inner();
in.show();
}
}

Annonymous class
A class without any name is called Annonymous class.
interface Animal
{
void type();
}
public class ATest {
public static void main(String args[])
{
//Annonymous class created
Animal an = new Animal() {
public void type()
{
System.out.println("Annonymous animal");
}
an.type();
}
}

70 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Difference Between Concrete Class, Abstract Class, Final Class, Interface.

Concrete Class
• A class that has all its methods implemented, no method is present without body is
known as concrete class.
• In other words, a class that contains only non-abstract method will be called
concrete class.

Abstract Class
• A class which is declared as abstract using abstract keyword is known as abstract
class. abstract contains abstract methods and used to achieve abstraction, an
important feature of OOP programming. Abstract class can not be instantiated.

Interface
• Interface is a blueprint of an class and used to achieve abstraction in Java.
• Interface contains abstract methods and default, private methods.
• We cannot create object of the interface. Interface can be used to implement
multiple inheritance in Java.

Final class
Final class is a class, which is declared using final keyword. Final class are used to prevent
inheritance, since we cannot inherit final class. We can create its object and can create
static and non-static methods as well.
Concrete Class Abstract Class Final Class Interface
Constructor Yes Yes Yes No
Non-static (method) Yes Yes Yes Yes
Non-static (variable) Yes Yes Yes No
Access Modifier (by default) Default Default Default Public
Object Declaration Yes Yes Yes Yes
Instantiation Yes No Yes No
Relation Both (IS-A & HAS-A) IS-A HAS-A IS-A
Final Declarations May or May not be May or May not be May or May not be Only Final
Abstract Declarations No May or May not be No Fully Abstract
Inheritance Keyword Extends Extends No Inheritance Implements
Overloading Yes Yes Yes Yes
Overriding No No No No
Super keyword Yes Yes Yes No
This keyword Yes Yes Yes Yes
Byte Code .class .class .class .class
Anonymous Class No Yes No Yes
Keywords used for declaration No keyword Abstract keyword Final keyword Interface keyword
Inheritance Single Single No Inheritance Multiple
Static Variables Yes Yes Yes Yes

71 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

COLLECTIONS
The collection framework in java is made up of classes and interfaces that stores and
processes data in an efficient manner.
• The Sun Microsystems has introduced collection framework in Java 2.0
• The hierarchy of the whole collection framework is given below :

List
• List is an interface that is available in the java.util package.
• List is used to store a collection of elements and allows duplicates.
• The term ‘List is ordered’ means that the order is retained in which we add
elements, and will get the same sequence while retrieving elements.
• List interface has three concrete subclasses:
▪ ArrayList
▪ LinkedList
▪ Vector

Remember the following three important methods of List


• Boolean add(Object o) ; //Append the specified elements to the end of the list
▪ Return type is Boolean
▪ Input type is Object
• Object get(int i); //Return the elements as Object of the specified position in the list
▪ Return type is Object
▪ Input type is int [index of Arraylist ]
• int size(); // Return number of elements in the list
▪ Return type is int [no of elements exist.]
▪ Input type is nothing

ArrayList
The ArrayList extends the AbstractList and implements the List interface. It is usually
slower than the other arrays, but is useful where you need to manipulate a lot in programs.
• Uses Dynamic array for storing the elements
• Duplicate elements are allowed
• Maintains insertion order
• Methods are not synchronised
• Random access as it works on index basis
• Manipulation is slow because lot of shifting needs to be done. This means that if the
ArrayList has 1000 elements and we remove the 50th element, then the 51st
element tries to acquire that 50th position and likewise all elements. So, moving
every element consumes a lot of time.

Vector
The vector class ‘implements a growable array of objects. Similar to an array, it contains
components that can be accessed using an integer index’. The vector may expand or
contract as per the requirements.
• All methods are synchronised
• It is slower than an Arraylist

72 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

• Vector is thread-safe as it has synchronised methods


• It has capacity concept. The default capacity is 10
• It doubles when it reaches its threshold
• Size methods returns the number of elements present
• Capacity method returns the capacity which doubles after reaching the default
capacity, which is 10
• Vector can be iterated by simple for loop, Iterator, ListIterator and Enumeration

Example
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListTest {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add("aaa");
al.add("bbb");
al.add("ccc");
// see return type of add below
System.out.println(al.add("ddd"));
al.size();
System.out.println(al.size);
//to check if Arraylist is empty
al.isEmpty();
System.out.println("iteration of Arraylist by for loop");
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
System.out.println("iteration of Arraylist by Iterator");
Iterator itr = al.iterator();
while (itr.hasNext()) {
Object o = itr.next(); //this is removed in
String s = (String) o;
System.out.println(s);
}
System.out.println("iteration of Arraylist by List Iterator");
ListIterator ltr = al.listIterator();
while (ltr.hasNext()) {
Object o = ltr.next();
String s = (String) o;
System.out.println(s);
//Object op = ltr.previous();
/*String prevStr = (String) op;
System.out.println(prevStr);*/
}
}
}

73 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Example : Vector
public class VectorTest {
public static void main(String[] args) {
Vector v = new Vector();
System.out.println(v.size());
System.out.println(v.capacity());
//we can change its default behaviour
Vector v1 = new Vector(2);
System.out.println(v1.size());
System.out.println(v1.capacity());
//now try adding elements
v1.add("apple");
v1.add("mango");
v1.add("grapes");
System.out.println(v1.size());
// observe capacity
System.out.println(v1.capacity());
//Iterate by using Enumeration
Enumeration enumeration=v1.elements();
while (enumeration.hasMoreElements()) {
String element =(String)enumeration.nextElement();
System.out.println(element);
}
}
}

Every List interface implementing class has two constructors:


• Default constructor
• Constructor which takes java.util.collection

Example of ArrayList
ArrayList al=new ArrayList (); //with default constructor
ArrayList al1=new ArrayList (al); //constructor with ArrayList
ArrayList al2=new ArrayList (v); //constructor with vector
ArrayList al3=new ArrayList (c); //with java.util.collection

Example of Vector
Vector v=new Vector (); //with default constructor
v.add(); //to add elements
Vector v1=new Vector (al); //with java.util.collection
Vector v2=new Vector(v); // with vector

74 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Difference between Iterator and Enumeration:


Iterator Enumeration
• Iterator can be used to access the • Enumeration can be used for accessing
elements of six subclasses of collection elements of vector only.
interface:
1. ArrayList
2. Vector
3. LinkedList
4. LinkedHashSet
5. Treeset and HashSet
• Using the Iterator methods hasNext() • Using enumeration method has More
and next(), you can access the Elements() and nextElements(), you can
elements of collection. access the elements of vector one by one.
• Using the Iterator you can remove the • Enumeration is read only i.e. you can just
elements of collection. the read the data from vector but you
Example : cannot remove the element from vector
Iterator it=al.iterator(); using Enumeration.
while(it.hasNext()) {
String str=it.next().toString();
if(str.equals("jbk")) {
it.remove();
}
}

Difference between Iterator and ListIterator:


1. ListIterator is the sub interface of Iterator and therefore has more features in
ListIterator than Iterator.
2. ListIterator can access elements in forward and reverse directions.
3. Adding elements by using add method.
4. Replacement of existing elements with new element by using the set method.
5. Access index of element.

Iterator ListIterator
• Using Iterator we can access the elements • Using ListIterator we can access the elements in the
of collection only in forward direction forward direction using hasNext() and next()
using the hasNext() & next() methods. methods and in reverse direction using
hasPrevious()and previous() methods.
• You cannot add elements to collection. • You can add the elements collection.
• You cannot replace the existing elements • You can replace the existing elements with a new
with new elements. element by using void set(E e).
• Using Iterator you cannot access the • Using ListIterator you can access indexes of
indexes of elements of collection. elements of collection using nextIndex() and
previousIndex() methods.
• Using Iterator you can remove the • Using ListIterator you can also remove the
elements of a collection. elements of collection.

75 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

Difference between Array and ArrayList:


Array ArrayList
• The size of an Array is fixed, i.e. when you • The size of an ArrayList is grow-able, i.e.
create an array with same size you cannot once the ArrayList is created you can add
change dynamically. any number of elements without restriction.
• When you create an small Array you can't add • You won't get these problems with an
more elements and when you create a large ArrayList.
sized array, the memory will be wasted when
we don't put that.
• When you have an array with a size 100 and • When you access elements of ArrayList
has 10 elements only, then you need to repeat using iterator you won't face this time
the loop 100 times to access 10 elements wastage problem.
which is an unnecessary and time consuming
process.
• Array stores only similar types of • ArrayList store different types of elements
elements.You can store primitive and objects You can store only objects in an ArrayList
in Array Student s1= new Student();
e.g: int a[]=new int[5]; e.g. al.add(s1);
Students[] stu=new Student[5]; al.add("sri");

Note: Both Array and ArrayList store the elements internally using indexing representation
and these elements can be accessed randomly
• You can access the elements of an Array using index representation
For example: a [1]
• You cannot access the elements of an ArrayList using index representation
For example: al [0] is not allowed but al.get(0) is allowed

Comparison between ArrayList, Vector and LinkedList:


Topic ArrayList Vector LinkedList
Legacy or collection Collection framework Legacy class but Collection framework
Framework class added in java 2 revised in java 2 class added in java 2
Synchronised Not Synchronised Synchronised Not Synchronised
Storage Index Representation Index Representation Node Representation
Representation
Accessing Elements Iterator. List Iterator Enumeration. Iterator. List Iterator
Iterator List Iterator
Access Type Random Access Random Access ----

Set
• A set is used to store the collection of elements without duplicates.
• It is an unordered collection which means that order is not maintained while storing
elements and while retrieving them, we may not get the same order that we had put
them in.
• A set cannot be iterated by using ListIterator but by Iterator.
• There are four classes which implement Set interface:
▪ HashSet
76 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

▪ LinkedHashSet
▪ TreeSet
▪ SortedSet - It uses hash table to store elements. Duplicates are not allowed.

Example: Consider the following program of HashSet


import java.util.HashSet;
import java.util.Iterator;
public class HashSetTest {
public static void main(String[] args) {
HashSet hs = new HashSet();
hs.add("aaaa");
hs.add("bbbb");
// aaaa will not be allowed as the set doesn't allow duplicates
hs.add("aaaa");
hs.add("cccc");
// see size
System.out.println(hs.size());
// we can print values for testing
System.out.println(hs);
// By using iterator
Iterator itr = hs.iterator();
while (itr.hasNext())
System.out.println(itr.next());
}
}

Comparison between HashSet, LinkedHashSet and TreeSet:


Topic HashSet LinkedHashSet TreeSet
Duplicate Not Allowed Not Allowed Not Allowed
Ordering Unordered Maintains insertion order Maintains sorting order
Null Allow Allow Do not allow
Accessing Elements Iterator Iterator Iterator
Thread Safety No No No

Queue
• The Queue is an interface of a subtype of the Collection interface
• It represents an ordered list of objects just like a List, but its intended use is slightly
different.
• A queue is designed to have elements inserted at the end of the queue, and elements
removed from the beginning of the queue. Just like a queue in a supermarket or any
shop.
• Following are the concrete subclasses of the Queue interface:
▪ ArrayDeque
▪ PriorityQueue
▪ PriorityblockingQueue
▪ LinkedBlockingQueue

77 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

• Each Queue method exists in two forms:


▪ One throws an exception if the operation fails
▪ The other returns a special value if the operation fails (either null or false,
depending on the operation)

Dequeue
• Dequeue is a sub-interface of Queue interface
• A double-ended-queue is a linear collection of elements that supports the insertion
and removal of elements at both end points
• It defines methods to access the elements at both ends of the Deque instance
• Methods for insertion, removal and retrieval of Deque elements are summarised in
the following table:
Type of First Element (Beginning of the Last Element (End of the
Operation Deque instance) Deque instance)
Insert addFirst(e) addLast(e)
offerFirst(e) offerLast(e)
Remove removeFirst(e) removeLast(e)
pollFirst(e) pollLast(e)
Examine getFirst(e) getLast(e)
peekFirst(e) peekLast(e)

Map
• A map is used to store the key-value pair
• It doesn't allow duplicate keys but duplicate values are allowed
• It has the following concrete subclasses:
▪ HashMap
▪ WeakHashMap
▪ HashTable
▪ IdentityHashMap
▪ TreeMap
▪ LinkedHashMap

HashMap:
• A HashMap is class which implements the Map interface
• It stores values based on key
• It is unordered, which means that the key must be unique
• It may have null key-null value
• For adding elements in HashMap we use the put method
• Return type of put method is Object
• It returns the previous value associated with key or null if there was no mapping for
key

Example:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
78 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

import java.util.Set;
public class HashMapTest {
public static void main(String[] args) {
// Creation of HashMap
HashMap hm = new HashMap();
// Adding elements with key
hm.put("101", "java");
hm.put("102", ".Net");
// Will print null
Object o = hm.put("103", "C++");
System.out.println(o);
// Will print previous value as it is duplicate value
Object o1 = hm.put("103", "C");
System.out.println(o1);
//1. Retrieving elements from HashMap by using iterator
System.out.println("======By using Iterator======");
Set s = hm.keySet(); // set s contains all keys
Iterator itr = s.iterator();
while (itr.hasNext()) {
String key = (String) itr.next();
System.out.println("Key :"+key);
System. out. println(" Value :"+ hm.get(key));
}
//2. Retrieving elements from HashMap by using Map.Entry
System.out.println("====== By using Map.Entry ======");
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator it = set.iterator();
// Display elements
while(it.hasNext()) {
Map.Entry me = (Map.Entry) it.next();
System.out.print(me.getKey()+ ": ");
System.out.println(me.getValue());
}
}
}

LinkedHashMap:
• A LinkedHashMap is a ‘hastable and linked list implementation of the map
interface with a predictable iteration order.
• It is the same as HashMap except it maintains an insertion order i.e. ordered
Consider the same above programs using LinkedHashMap. Observe the output.
Change one line in the above example.

79 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

In the above program


/Instead of
HashMap hm=new HashMap ();
//Use below
// Creation of LinkedHashMap
LinkedHashMap hm = new LinkedHashMap()

TreeMap:
• The TreeMap is a class which implements NavigableMap interface which is the sub-
interface of SortedMap.
• It stores values based on key
• It is ordered but in an Ascending manner
• Keys should be unique
• It cannot have null key at run time but can have null values because the interpreter
will not understand how to sort null with other values
• Consider the program of storing elements using TreeMap

Example:
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapTest {
public static void main(String[] args) {
// Creation of TreeMap
TreeMap tm = new TreeMap();
// adding elements with key
tm.put("103", "java");
tm.put("102", ".Net");
Object o = tm.put("101", "C++");
// below will print null
System.out.println (o);
Object o1 = tm.put("101", "C");
System.out.println (o1);
// retrieving elements from TreeMap
Set s = tm.keySet();
// set s contains all keys
Iterator itr = s.iterator();
while (itr.hasNext()) {
String key = (String) itr.next();
System.out.println("Key :" + key);
System.out.println("Value :" + tm.get(key));
}
// Try putting null value
// will not throw compile time error
// but gives runtime error uncomment below
// tm.put(null, null);

80 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

}
}
Hashtable:
▪Hashtable is a class which implements Map interface and extends Dictionary class.
▪It stores values based on key
▪It is unordered and the key should be unique
▪It cannot have null keys or null values. It gives runtime error if we try to add any
null keys or values but will not show an error at compile time.
▪ It has synchronised methods and slower than hashmap
▪ Consider the program of storing elements using Hashtable
Example
import java.util.Hashtable;
public class HashTableTest {
public static void main(String[] args){ Hashtable ht = new Hashtable(); ht.put("ind",
"India");
ht.put("bhu", "Bhutan");
ht.put("ind", "India");
//the below will print size of ht by
//ignoring the duplicate key
System.out.println("size of hashTable> "+ht.size()); // 2
//OK - compile time
//NOT OK AT RUNTIME
//ht.put(null, "India");
//OK - compile time
//NOT OK AT RUNTIME
//ht.put(null, null);
//OK - compile time
//NOT OK AT RUNTIME
//ht.put("ind", null);
System.out.println(ht.size()); // 2
}
}
Comparison between HashMap, LinkedHashMap, TreeMap and HashTable:
Topic HashMap LinkedHashMap TreeMap HashTable
Duplicate Key Not Not Allowed Not Allowed Not
Allowed Allowed
Ordering Unordered Maintains insertion Maintains in Accessing order Unordered
order
Null (Key Value) Allow Allow key Not allowed but value is Not
Iterator Allowed
Accessing Iterator Iterator Iterator Iterator
Elements
Thread Safety No No No Yes

81 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y
INTRODUCTION TO JAVA

82 | C H E N N A I I N S T I T U T E O F T E C H N O L O G Y

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy