Java
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.
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.
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.
Example
package studytonight;
class Student
{
int a;
static int id = 35;
void change()
{
System.out.println(id);
}
}
o1.change();
Student.id = 1;
o2.change();
o1.change();
}
}
Output
35
1
1
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.
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
}
}
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.
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;
short : It is 2 bytes(16-bits) integer data type. Value range from -32768 to 32767. Default
value zero. example: short s=11;
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
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;
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.
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;
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
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");
}
}
Initializer Block
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;
• Widening Casting(Implicit)
• Narrowing Casting(Explicitly done)
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
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
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
• 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
}
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
}
}
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:
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.
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
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);
}
}
}
}
}
}
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
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
• 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
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
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
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:
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
return-type methodName(parameter-list)
{
//body of method
}
➢ 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
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
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
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
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.
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
Java also supports many non-access modifiers, such as static, abstract, synchronized,
native, volatile, transient etc.
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
}
}
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
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
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.
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
Types of Inheritance
Java mainly supports only three types of inheritance that are listed below.
1. Single Inheritance
2. Multilevel Inheritance
3. Heirarchical Inheritance
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
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
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
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
Output
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method
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.
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
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
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 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
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.
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.
• 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.
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");
}
}
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();
}
}
//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
//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();
}
}
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();
}
}
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();
}
}
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
}
Example
interface I1
{
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();
}
}
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 NewsPaper
{
news();
}
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.
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
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
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();
}
}
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
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
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
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);
}
}
}
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
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
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
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.
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
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
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