JavaCBook
JavaCBook
What is Java
Java is a platform independent language, Which means Java program can be developed on any
Operating system, and compiled into a bytecode that byte code can be run on any platform without
recompile the java program.
There are Three billion devices are using java, for example mobile phones,java powers set-top
boxes, printers, Web cams, games, car navigation systems, medical devices, etc…
Features of Java
Simple
Object oriented
Distributed
Multithreaded
Dynamic
Architecture neutral
Portable
High performance
Robust
Secure
Standalone applications:Standalone applications(Desktop applications) are run in our local system, This
applications contains main method
This applications we need to install in every system, For example Adobe reader, media player, etc…
This applications can be devolped by using AWT(Abstract Window Toolkit), swing, SWT(Standard
Widget Toolkit), etc…
Web applications:Web applications are server and client side programming, This applications are run on
server which will process clinet(browser) requests
For example webmail, This applications can be developed by using servlets, JSP(Java Server Pages),
Struts, Spring, JSF(JavaServer Faces), etc…
Enterprise Applications:This applications are deployed on a variety of platforms, They are data-centric,
user-friendly, and must meet stringent requirements for security, administration, and maintenance. In
short, they are highly complex systems
For example Banking applications, This applications can be developed by usng EJB(Enterprise Java
Beans), etc…
Mobile Applications:This applications are run on mobiles, for example whatsapp, MyJio, etc…, This
applications are developed by using java, andriod, IOS, etc…
Java Editions
Java SE contains core packages like java.lang, java.util, java.io, java.net, java.math, etc…
This will contain core concepts like OOPS, Exceptions, Collections, Threads, Inner classes, Reflection,
I/O Streams, AWT, Swing, etc…
History of Java
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
Java was originally designed for interactive television, but it was too advanced for the digital cable
television industry at the time. The language was initially called Oak after an oak tree that stood
outside Gosling‟s office. Later the project went by the name Green and was finally renamed Java, from
Java coffee,said to be consumed in large quantities by the language‟s creators.[citation needed]
Gosling designed Java with a C/C++-style syntax that system and application programmers would find
familiar.
Sun Microsystems released the first public implementation as Java 1.0 in 1995. It promised “Write
Once, Run Anywhere” (WORA), providing no-cost run-times on popular platforms. Fairly secure and
featuring configurable security, it allowed network- and file-access restrictions. Major web browsers
soon incorporated the ability to run Java applets within web pages, and Java quickly became popular.
The Java 1.0 compiler was re-written in Java by Arthur van Hoff to comply strictly with the Java 1.0
language specification. With the advent of Java 2 (released initially as J2SE 1.2 in December 1998 –
1999), new versions had multiple configurations built for different types of platforms. J2EE included
technologies and APIs for enterprise applications typically run in server environments, while J2ME
featured APIs optimized for mobile applications. The desktop version was renamed J2SE. In 2006, for
marketing purposes, Sun renamed new J2 versions as Java EE, Java ME, and Java SE, respectively.
On November 13, 2006, Sun released much of Java as free and open source software, (FOSS), under
the terms of the GNU General Public License (GPL). On May 8, 2007, Sun finished the process, making
all of Java‟s core code available under free software/open-source distribution terms, aside from a small
portion of code to which Sun did not hold the copyright.
Versions
Java Runtime Environment contains JVM, class libraries, and other supporting files. JRE is targeted for
execution of Java files.
JIT(Just In Time)
JIT compiler is part of JVM which increases the speed of execution of a java program.
JVM Architechture:
Class loader sub system: Class loader sub system will loads the class file in to the JVM.
Method area: Method area stores the class code like static varaibles and method code
PC(Program Counter) registers: This will conatain memory address of instructions of the methods,
For every method separate PC register will create.
Naming conventions specify the rules to be followed by java programmers while writing the names of
class, package, variables and methods etc.
Naming conventions make programs more understandable by making them easier to read.
Package
Examples:
java.util
java.net
java.io
Keyword
Examples:
void
static
Class:
Class name starts with capital letter and every inner word starts with upper capital letter(upper case ).
Examples:
String
StringBuffer
OutputStreamReader
Interface
Interface name starts with upper case letter and every inner word starts with upper case letter.
Examples:
Collection
Runnable
SortedSet
Method
Methods name starts with lower case letter and every inner word starts with upper case letter.
Examples:
println()
readLine()
variables in java
Variable is used to store a value. It‟s nothing but name of the memory location.
1 int x = 5;
Variable declaration
1 int i;
Variable initialization
1 int i = 5;
Types of variables
Instance Variables
public class A{
1
int i = 5;
2
}
A variable which is declared with static keyword is called Static variable.
Ex:
1 public class A{
2 static int i = 5;
3 }
Static variables called as class variables, Because They are associated with the class, rather
than with any object.Static variables are loads at the time of class loading.
Class variables are used to refer a common property , for example College name of the students
Static variables will have only one copy in memory and that is shared by all objects. If we make
any changes on it by using an object that will also effects the other objects.
We can access static variables by using class name (className.variableName)
We can access static variables in static and non-static methods.
Static variables are stored in method area.
Local Variables
1 public class A{
2 public void display(){
3 int i = 5;
4 }
5 }
Local variables are not accessible out side of the method
Local variables should be initialized before using them, Otherwise compiler will throw The local
variable may not have been initialized exception
Data types in java
We need a variable to store some data, Every variable has a data type in java.
Different data types can be used to store different types of values.
Every data type has a range and default value.
In Java for every data type JVM allocates some memory.
1. Primitive
2. Non-Primitive
-2,147,483,648 to 2,147,483,647
-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
1.7976931348623157 x 10308 to
byte :
Default Value: 0
The byte data type can be useful for saving memory in large arrays, where the memory savings
actually matters.
Ex.
1 byte b = 29;
short :
Default Value: 0
The short data type can be useful for saving memory in large arrays, where the memory savings
actually matters.
Ex.
1 short sh = 74;
int :
Default Value: 0
Ex.
1 int i =10;
long :
Default Value: 0L
Ex.
1 long v = 130L;
In the above statement, if L is not there then JVM allots 2 bytes of memory to v, Because 2 bytes is
sufficient to store the value 130.
float :
Ex.
1 float pi = 3.142F;
In the above statement, if F is not written at the end then JVM would have allotted 8 bytes assuming
the value to be double
double :
Ex.
1 double d = 1999.268628265
boolean :
Size: 1 bit.
The boolean data type has only two possible values true and false.
char :
Size: 2 bytes(16 bits).
This data type represents single character which is enclosed with in the single quotes
Ex.
String :
String represents a group of characters which is enclosed with in the double quotes.
Ex.
Derived data types are those whose variables allow us to store multiple values of same type. But they
never allows to store multiple values of different types. In general derived data type can be achieve
using array.
Ex.
User defined data types are those which are developed by programmers, Because in java every class is
a data type.
Operators in java
Operators are standard symbols that are used to perform some specific operations involving one or
more operands and finally produces a result.
Assignment Operator:
Arithmetic Operators:
+ Additive operator (also used for String concatenation)
– Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Unary Operators:
Unary plus operator; indicates positive value (numbers are positive without this,
+ however)
== Equal to
!= Not equal to
Logical Operators:
&& Logical-AND
|| Logical-OR
^ Bitwise exclusive OR
| Bitwise inclusive OR
Ternary Operator:
Arithmetic Operators
Arithmetic Operators are used to perform fundamental arithmetic operations like addition, subtraction,
multiplication and division.
List of arithmetic operators:
+ concatenation)
– Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Addition operator(+):
The addition operator produces the sum of numeric operands or string concatenation.
Ex:
Subtraction operator(-):
The subtraction operator subtracts the two operands, producing their difference
Ex:
Division operator(/):
The division operator produces the quotient of its operands where the left operand is the dividend and
the right operand is the divisor.
Ex:
Remainder operator(%):
The remainder operator returns the remainder left over when one operand is divided by a second
operand.
Ex:
Unary Operators
Unary Operators: The unary operators are act on only one operand.
The unary minus operator is used to negate a value, That means minus operator converts positive to
negative, Negative to poistive
Pre increment(++variable)
Post increment(variable++)
Pre increment(++variable):
Ex:
public class PreIncrementEx2 {
public static void main(String[] args) {
1
int i = 10, j = 5;
2
/*
3
* i value is incremented first, and then the result is
4
* used in the ++i + j expression
5
*/
6
int k = ++i + j;
7
System.out.println("k value: "+k);
8
System.out.println("i value: "+i);
9
}
}
Output :
k value: 16
i value: 11
Ex:
1 public class PostIncrementEx2 {
2 public static void main(String[] args) {
3 int i = 10;
4 //First i value is assign to k then i value will be increased
5 int k = i++;
6 System.out.println(k);
7 System.out.println(i);
8 }
9 }
Output:
10
11
Ex:
Ex:
1 public class PreDecrement {
2 public static void main(String[] args) {
3 int i = 10, j = 5;
4 /*
5 * i value is decrement first, and then the result is
6 * used in the --i + j expression
7 */
8 int k = --i + j;
9 System.out.println("k value: "+k);
10 System.out.println("i value: "+i);
11 }
12 }
Output :
k value: 14
i value: 9
These operators are used for the purpose of comparing, For example to know which one is bigger or
whether two quantities are equal or not.
== Equal to
!= Not equal to
Ex:
Logical Operators
Logical operators are used to construct compound conditions, A compound condition is a combination
of several simple conditions
&& Logical-AND
|| Logical-OR
Logical-AND Operator(&&):
The Logical-AND operator returns true when all the conditions are true, Otherwise it returns false.
Ex:
The above example if both conditions(i == 10 and j == 5) are true, then i == 10 && j == 5 returns
true.
The Logical-AND operator(&&) doesn‟t check second condition if first condition is false. It checks
second condition only if first condition is true.
Logical-OR Operator(||):
The Logical-OR operator(||) returns true if either one or both conditions are true, otherwise it returns
false.
Ex:
The above example if either one or both conditions(i == 10 or j == 6) are true, then i == 10 || j == 6
returns true.
The Logical-OR || operator doesn‟t check second condition if first condition is true. It checks second
condition only if first condition is false.
^ Bitwise exclusive OR
| Bitwise inclusive OR
System.out.print() statement keeps the cusrsor in the same line after printing the output.
System.out.println() statement moves cusrsor to the next line after printing the output.
Keywords in java
Keyword Description
Abstract abstract keyword is used to declare an abstract class and abstract method.
assert keyword is used in an assert statement
expression1 is a boolean.If expression1 returns False then the an error will be thrown
It is actually a primitive type. It has only two possible values: true and false. And the
We use this in loops. While executing a loop at any point of time if we want to stop
Break execute the loop, we will use break keyword to jump out of the loop
Byte byte is a primitive data type which holds an 8 bit signed integer
case is used as part of switch statement to switch between the statements while
char represents a primitive datatype which can hold a character within single-quote.
continue keyword is used whenever we want to skip the remaining statements in the
do is a keyword used in do-while loop. In do-while loop first statements get executed
else is a keyword used in if-else condition. The statements in else block will be
extends is a keyword used for both classes and interfaces to extend the abilities of
another class or interface. A class can extend only class, and an interface can extend
import is a keyword used to specify the package or a class to be used in the current
Import class
Instanceof of type of specified class. If yes it returns True or else it returns False
Int int is a primitive data type which can hold 32 bit signed integer
Long long is a primitive data type which can hold 64 bit signed integer
native is a keyword used to declare method to specify that the method implemented
return is a keyword declared at the end of the method and it is used return a value
Short short is a primitive data type which can hold 16-bit signed two‟s complement integer
strictfp keyword is used to restrict the precision and rounding of floating point
super is a keyword used in a sub-class to refer it‟s super-class state or behavior also
Super constructors
Throws throws is a keyword used to specify which exceptions are expecting to be thrown by
the code within the method
try is a keyword to define a try-block which contains a set of statements which can
Void void is a keyword used for a method to define that it returns nothing
while is a keyword used in while-loop. It tests a boolean expression and executes the
While defined statements under the loop if the expression returns True
Find the average value from all odd indexed elements from given array
/*
Find out the average value from all odd indexed elements
from a given array
*/
1
class FindAvgValueFromOdd {
2
public static void main(String[] args) {
3
int[] arr = { 5, 24, 3, 65, 27, 34, 40, 52 };
4
int sum = 0;
5
for (int i = 1; i < arr.length; i = i + 2) {
6
sum += arr[i];
7
}
8
double avg = (double) sum / (arr.length / 2);
9
System.out.println("Average value from all odd indexed elements" + avg);
10
}
11
}
12
Control statements
Control statements are the statements which alter the flow of execution and provide the better control
to the programmer on the flow of execution
The following control statements are available in Java.
If-else statement
switch statement
for loop
for-each loop
while loop
do-while statement
break statement
continue statement
break
Syntax :
while(condition){
if(condition){
break;
}
}
Ex:
int i =0;
if(i== 5){
break;
}
System.out.println(i);
}
continue
continue is used to skip the current iteration and it continues rest of iterations.
while(condition){
if(condition){
continue;
}
}
Ex:
int i =0;
while(i > 10){
if(i== 5){
continue;
}
System.out.println(i);
}
for-each Loop
for(var : collection){
//group of statements
}
if-else
if statement:
1 if(condition){
2 //if code
3 }
The above case if the specified condition is true then if code get executed .
3 int i = 5;
4 if (i > 0) {
6 }
7 }
8 }
Output:
5 is a poistive number
if-else statement:
If we want to check two conditions such case we will use if-else statement
syntax:
1 if(condition){
2 //if code;
3 }
4 else{
5 // else code;
6 }
Above case if the specified condition is true then if code get executed, otherwise else code get
executed.
In the above example the if code and else code represents either single statement or group of
statements, If it is single statement Flower brackets({}) are optional.
syntax:
1 if(condition)
2 statement1;
3 else
4 statement2;
3 int num=4;
4 if(num%2==0)
6 else
8 }
9 }
5 } else {
7 }
8 }
if-else-if ladder:
If we want to check more then two conditions such case we will use if-else-if ladder statement
syntax:
1 if(condition1){
2 statement1;
3 }
4 else if(condition2){
5 statement2;
6 }
7 else if(condition3){
8 statement3;
9 }
10 -
11 -
12 else{
13 statement;
14 }
If-condition1 is true then statement1 get executed , otherwise it will check condition2 if it is true then
statement2 get executed, otherwise it will check condition3 if it is true then statement3 get executed
like that it will check all conditions if any condition is true then appropriate statement get execute, if
all the conditions fails then finally else statement get executed.
int i = 5, j = 10;
if (i > j) {
} else if (i < j) {
} else {
Switch Statement
Syntax :
1 switch(argument){
3 break; //optional
5 break; //optional
7 break; //optional
8 .......
9 .......
10 .......
12 }
Switch statement allows only byte, char, short, int , String and enum as an argument
switch doesn‟t allow float, double and long as an argument
When a break statement is encountered, the control moves out of the switch statement. If no break
statement is given, all the case statements are executed until a break is encountered or the switch
statement ends.
2 int i = 2;
3 switch (i) {
4 case 1: System.out.println("1");
5 break;
6 case 2: System.out.println("2");
7 break;
8 case 3: System.out.println("3");
9 break;
10 case 4: System.out.println("4");
11 break;
12 case 5: System.out.println("5");
13 break;
15 }
16 }
Output: 2
Output :
2
3
4
5
No match found
for loop
For loop is used to execute a block of code repeatedly until the condition is true
1. for loop
2. nested for loop
3. for-each loop
2 //group of statements
3 }
Ex:
3 }
1 initialization;
3 //group of statements
4 }
Ex:
1 int i =0;
3 System.out.println(i);
4 }
Conditional part is optional in for loop, If are not providing any condition complier will provide true
value.
3) Syntax :
1 for(initialization ; ; increment/decrement){
2 //group of statements
3 }
Ex:
2 System.out.println(i);
3 }
2 //group of statements
3 }
Ex:
1 for(int i = 0 ; i < 10 ; ){
2 System.out.println(i);
3 }
2 //group of statements
3 }
Ex:
1 int i = 0;
2 for( ; ; ){
3 System.out.println(++i);
4 }
4 System.out.println(i);
5 }
6 }
7 }
Output:
0
1
2
3
4
5
6
7
8
9
while loop
while loop is used to execute group of statements repeatedly as long as the condition is true.
Syntax :
1 while(condition){
2 //group of statements
3 }
Ex:
1 int i = 0;
3 System.out.println(++i);
4 }
do-while loop
do-while loop is used to execute group of statements repeatedly as long as the condition is true, but
the difference between while loop and do-while loop is while loop every time will check the condition
where as do-while loop first time it won‟t check the condition.
Syntax :
1 do{
2 //group of statements
3 } while(condition);
Ex:
int i = 0;
do{
System.out.println(++i)
What is OOPS?
OOPS (Object Oriented Programming System) is an approach designing the programs using classes and
objects.
Features of OOPS
Encapsulation
Inheritance
Polymorphism
Abstraction
Class
class is a blueprint for creating objects, class refers common properties and functions of Objects
A class can produce any number of objects of its own type.
Class contains
instance variables
class variables(static variables)
instance methods
class methods (static methods)
constructors
instance blocks
static blocks
nested classes
nested intefaces
Example:
2 String name;
3 String gender;
4 float height;
5 float weight;
Object
An object can be anything which is existing physically in the real world, For example book, pen,
person, car
An object contains state and behavior
For example a dog object contains states like color, name, breed as well as behaviors like
wagging the tail, barking, eating.
Object maintains its state in instance variables and implements its behavior with the methods.
Suppose to a build a house we need a planning which contains the architecture (blue print) of the
house. The blue print is a class in this scenario. After building the house according to that particular
plan, the house will be physically existed. So the outcome „house‟ is the Object.
Creating Object:
Generally we can create an object to a class by using “new” operator. [There are several ways to
create an object. We will discuss the remaining ways in the coming topics]
In the above statement, “raju” is a reference of Person object. By using this reference we can reuse
Person object.
Below image explains the same scenario diagrammatically
1. First JVM determines the amount of memory needed for the new object, Then JVM allocates the
memory on the heap
2. All instance variables get initialized
3. JVM will invoke appropriate constructor, based on the arguments specified in the new statement
4. Before the constructor executes, super class constructor and instance blocks gets executed
5. The body of the constructor gets executed
6. The new operator returns a reference to the new object
Methods
3 return result;
4 }
Types Of Methods
Instance Methods
Static Methods
Instance Methods
2 sb.append("york");
A method which is declared with static keyword is known as static method(class method)
we can call a static method by using the Class-Name
syntax: ClassName.methodName()
Ex:
1 String.valueOf(5);
We can overload the static methods, but we can‟t override static methods
Static methods can access static variables and other static methods directly
Static methods cannot access instance variables and instance methods directly,But we can
access by creating an object
Static methods doesn‟t allowthis keyword
Syntax: methodName(parameters-list)
Ex:Println(String str)
Constructor
Constructor is similar to a method but it will not return any value even void also(If method not return
any value then return type is void) .
We cannot call the constructor explicitly, Constructor implicitly called by JVM at the time of object
creation[Ex. Person p = new Person()]
Constructor rules:
Types of constructors:
2 Person() {
5 }
2 Person(String str) {
4 }
5 }
In case if we did not provide any constructor(default or parameterized constructor), then Java compiler
will provide a default constructor.
We can call from one constructor to another constructor of the same class by using “this” keyword. In
case if we are calling a parameterized constructor from a constructor, we should pass the parameters.
Advantages of constructors:
Private constuctor
When ever we declare private constructor in a class , that class can’t be extended as well we
can’t create object outside of that class.
Ex:
package com.core;
1
public class Test
2
{
3
private Test()
4
{
5
}
6
}
Encapsulation in java
A Java Bean class is the best example for a well implemented encapsulation in Java. Check the below
example code.
Output:
p
i value 10
u
j value 20
b
Inside printMsg1 method
l
Inside printMsg2 method
i
c
In the above example, A class is called “super class”, and B class is called“sub class”. Super
class variables and methods reusing in sub class without rewriting it in sub class.
v
o
When ever super class object is created then memory allocated to only super class
i
members,so we can access only super class members.
d
Ex:
s
1 A a = new A(); e
t
2 System.out.println(a.i); N
a
3 a.printMsg1();
m
e
When ever sub class object is created then memory allocated to both super class and sub (
class members, so we can access super and sub class members. S
t
Ex: r
i
1 B b = new B(); n
g
2 System.out.println(b.i);
3 System.out.println(b.j); n
a
4 b.printMsg1(); m
e
5 b.printMsg2();
)
{
Super class reference can refer both super class and sub class object, but it can access only
super class members.
Ex:
1 A a = new B(); t
h
2 System.out.println(a.i); i
s
3 a.printMsg1(); .
n
a
Sub class reference can refer only sub class object, but it can access both super class and
sub class members. m
e
Ex:
=
1 B b = new B();
n
2 System.out.println(b.i); a
m
3 System.out.println(b.j);
e
4 b.printMsg1(); ;
5 b.printMsg2(); }
p
Sub class reference can‟t refer super class object. u
b
Ex: l
i
1 B b = new A();//will not compile c
v
Types of inheritance o
i
There are five types of inheritance d
s
e
t
G
e
n
1 class A { d
e
2 ----------
r
3 } (
S
4 class B extends A { t
r
5 ----------
i
6 } n
g
g
e
n
d
e
r
)
t
1 class A {
h
2 ---------- i
s
3 } .
g
4 class B extends A {
e
5 ---------- n
d
6 } e
r
7 class C extends B {
=
8 ----------
9 } g
e
n
d
e
r
;
p
u
b
l
i
1 class A { c
2 ----------
S
3 } t
r
4 class B extends A { i
n
5 ----------
g
6 }
g
7 class C extends A { e
t
8 ---------- N
a
9 }
m
e
(
)
{
r
e
t
u
1 class A { r
n
2 ----------
n
3 } a
m
4 class B{
e
5 ---------- ;
6 } }
g
e
class A { t
1 G
---------- e
2 n
} d
3
e
class B extends A{
r
4
---------- (
5 )
}
6 {
class C extends A {
7 r
----------
e
8
t
}
9 u
class D extends B,C { r
10 n
----------
11 g
}
e
n
Java doesn‟t support for hybrid inheritance. d
e
What is multiple inheritance in Java? r
;
If a class extends more then one class is known as multiple inheritance.
}
Assume that we have three classes like Parent1, Parent2 and Child, If the Child class
extends Parent1, Parent2 which contains same method, And we are trying to invoke the
common method from child class, In such case JVM gets confuse which method needs to
invoke, This is called diamond problem.
1 class Parent1{
2 void printMessage(){
3 System.out.println("Parent1 method");
4 }
5 }
6 class Parent2{
7 void printMessage(){
8 System.out.println("Parent2 method");
9 }
10 }
Types of Relationships
1. ―IS-A‖ Relationship
2. ―HAS-A‖ Relationship
IS-A Relationship:
IS-A Relationship can achieve through inheritance by using the “extends” keyword.
HAS-A Relationship:
HAS-A relationship can achieve through association, Association is nothing but establishing
the relationship between two separate classes through their objects.The relationship can be
one to one, One to many, many to one and many to many.
Aggregation
5 this.name = name;
6 }
8 return name;
9 }
11 return gender;
12 }
14 this.gender = gender;
15 }
16 }
5 this.person = person;
6 }
8 this.jobName = jobName;
9 }
11 return jobName;
12 }
14 return person;
15 }
16 }
5 person.setName("Ram");
6 person.setGender("Male");
8 job.setJobName("Software");
9 job.setPerson(person);
10 }
11 }
In the above Main class we have created object to Person then we are passing to the Job object by
means of setter methods. so here Person object exists with out Job object also.
Composition
In composition the contained object cannot exists without the existence of container object, then the
relationship is called as Composition.
Address.java
1 package com.test;
7 return addrId;
8 }
10 this.addrclass= addrId;
11 }
13 return street;
14 }
16 this.street = street;
17 }
19 return city;
20 }
22 this.city = city;
23 }
24 }
Employee.java
1 package com.test;
8 return empName;
9 }
11 this.empName = empName;
12 }
14 return empId;
15 }
17 this.empclass= empId;
18 }
20 return salary;
21 }
23 this.salary = salary;
24 }
26 return addr;
27 }
28 }
In the above case Employee object contains Address object, but with out Employee object there is
no Address object this is called Composition.
Polymorphism
What is Polymorphism?
Types of polymorphism
Static polymorphism
Dynamic polymorphism
Static polymorphism:
Method overloading
If a class contains two or more methods having same name with different parameters(different method
signature) is known as method overloading
In method overloading the return type may or may not be same
1 Public class A{
3 System.out.println("inside show()");
4 }
7 }
10 }
11 }
Method Overriding
Declaring same method in sub class which is already exists in super class is known as method
overriding, Here the sub class method will override super class method
In method overriding the super class method is called overridden method and the sub class method
is called overriding method
Overriding Rules:
overridden and overriding methods should exist in super and sub class
overridden and Overriding methods name and parameters should be same and return type can
be same or covariant return type.
Private methods can not be overridden
Static methods can not be overridden
Final methods can not be overridden
Overriding method can not throw super class exception of overridden method exception.
For example overridden method throws IOException, In such case overriding method should
not throw Exception, Because Exception is super class of IOException
Overriding method scope can not reduced of overridden method scope
For example overridden method scope is protected, In such case overriding method scope can
not be private or default
Overriding method scope can be same or increase of overridden method scope
For example overridden method scope is protected, In such case overriding method scope can
be protected or public
Example -1:
3 System.out.Println(x);
4 }
6 System.out.Println(str);
7 }
8 }
System.out.Println(“inside test()”);
System.out.Println(str);
Child.java
1 class TestOverriding{
4 childObj.display(“Hello”);
5 childObj.show(10);
6 childObj.toString();
7 }
8 }
In the above example, we are overriding display() method in the Child class. The
display()method in the Child class(subclass) is called “overriding method”
While executing childObj.display(“Hello”), JVM calls the display()from the Child class(sub classs)
In case of childObj.show(10), initially JVM checks whether the method is existed or not in the
Child class(sub class)
In our case show(int x) is not there. Then the JVM checks whether the Parent class(super class)
has the method show(int x), Yes it is there, so it will execute that method
In case of childObj.toString(), this method is not provided in both the Child and Parent classes
then the JVM checks the Object class(which is the super class of all the classes in Java) and
continue to execute it
Example -2:
1 class TestOverriding2{
4 parentRef.show(10);
6 }
7 }
In the above example, Parent class(super class) reference is holding the Child class(sub class) object.
In case of parentRef.show(10), at compile time the Java Compiler will checks forshow(int x)
method whether it is existing in Parent class. Yes the method is existing in Parent class
In case of parentRef.test(), at compile time the Java Compiler will check whether test() method
is existed in the Parent class. In our case it is not existed in the Parent class so the compiler
throws an exception
Overriding method return type should be sub return type of overriden method return type, is known as
covariant return type
Example -3:
1 package com.test;
2 class Parent{
3 }
1 package com.test;
2 class Child extends Parent{
3 }
1 package com.test;
2 class A{
6 }
7 }
1 Ppackage com.test;
2 class B extends A{
6 }
7 }
Overloading vs Overriding
the same class with same method If two or methods which are exists in super and sub
name along with different parameters classes with same method name along same
Return type may or may not be same. overriding supports co-variant return type.
scope.
public
specifiers may or may not be same. private -> default -> protected -> public
Overloaded methods can throws any Exception, Because Exception is super class of
exception. IOException
Typecasting in java
When ever we assign a value to a variable using assignment operator, Java compiler checks whether
the variables are of the same data type on both sides of equal operator. If the data types are not the
same then we will get an exception, to over come this situation we should convert the data types to
same on the both sides. To convert the data type, we will use the cast operator.
Converting from one data type to another data type is called type casting.
There are two types of casting in Java:
implicit casting
explicit casting
implicit casting
1 char c = „x‟;
2 int i = c; // it is acceptable
explicit casting
Example:
int i = 66;
1
char c = i; //not acceptable
2
char c = (char) i; // acceptable
Abstraction
Abstraction is the process of hiding the unwanted implementation details and exposing only
required features.
Abstraction can achieved by using interfaces and abstract classes in java.
An interface provides complete(100%) abstraction where as the abstract class provides partial(0
to 100%) abstraction.
Abstract class
Ex:
1 abstract class Vehicle {
2 }
Ex:
1
public void getMessage(){
2
}
3
Abstract class may or may not contains concrete methods, that means abstract class can
contains all abstract methods.
Abstract class may or may not contains abstract methods, that means abstract class contains all
concrete methods.
We can not create object to abstract class.
An abstract class can extends another abstract class or a class.
All abstract methods of abstract class should be implemented in the sub classes.
If any abstract method is not implemented, then the sub classes should be declared as abstract.
Even if a single method is declared as abstract in a class, the class itself can be declared as
abstract.
An abstract class can have constructors and instance variables.
Should not use final and abstract modifiers together in java.
Ex:
}
Interface
Ex:
1 interface Collection{
2 }
Ex:
Ex:
1 public interface A {
2 int i = 10;
3 void show();
4 }
7 System.out.println("inside B");
8 }
9 }
10
String
String represents a group of characters which is enclosed with in the double quotes.
Ex:
String is a class as well as data type since all the classes are data types in Java.
String default value is null.
String is an immutable object. immutability means unchangeable.
Once String object is created then the content of the object can‟t be modified.
String Constructors :
String() :
Creating string object with empty content.
Ex:
String(byte[] bytes):
Creating string object with byte array argument.
Ex:
1 byte[] arr={104,101,108,108,111};
String(char[] value):
Creating string object with char array argument.
Ex:
1 char[] arr={'h','e','l','l','o'};
2 String str=new String(arr);
1 char[] arr={'h','e','l','l','o'};
String(String original):
The newly created string is a copy of the argument string.
Ex:
String(StringBuffer buffer):
Create new String object with string buffer argument.
Ex:
String(StringBuilder builder):
Create new String object with string builder argument.
Ex:
String Methods:
char charAt(int intex): Returns the char value at the specified index of the string.
Ex:
1 char c=str.charAt(2);
int compareTo(String anotherString): This method is useful to compare two strings and we can
know which string is bigger or smaller
Ex:
1 int i=str.compareTo(“ok”);
String concat(String str): Concatenates the specified string to the end of this string.
Ex:
1 str.concat(“john”);
boolean contains(CharSequence s): Returns true if and only if this string contains the specified
sequence of char values.
Ex:
1 Boolean value=str.contains(“llo”);
1 int count=str.length();
boolean equals(String s): Return true if both strings content are same otherwise returns false.
Ex:
1 bolean value=str.equals(“hello”);
1 String str1=str.trim();
1 char[] arr=str.toCharArray();
String[] split(String delimiter): Splits this string around matches of the given delimiter.
Ex:
String toLowerCase(): Converts all of the characters in this string to lower case.
Ex:
1 String s=str.toLowerCase();
String toUpperCase(): Converts all of the characters in this string to upper case.
Ex:
1 String s=str.toUpperCase();
boolean startsWith(String prefix): Returns true if this string starts with specified prefix, other
returns false.
Ex:
1 boolean value=str.startsWith(“h”);
boolean endsWith(String suffix): Returns true if this string ends with specified suffix, other returns
false.
Ex:
1 boolean value=str.endsWith(“o”);
String replace(char oldChar, char newChar): Returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.
Ex:
String subString(int index): Returns a new string that is a substring of this string, from the index.
Ex:
1 String s=str.subString(2);
String substring(int startIndex, int endIndex): Returns a new string that is substring of this
string, from start index to end index .
Ex:
1 String s=str.subString(1,4);
boolean isEmpty(): Returns true if the length of string is 0., otherwise returns false.
Ex:
1 boolean value=str.isEmpty();
int indexOf(char ch): Returns the index within this string of the first occurrence of the specified
character.
Ex:
int lastIndexOf(char ch): Returns the index within this string of the first occurrence of the specified
substring.
Ex:
1 int i=10;
2 String str=String.valueOf(i);
Creating String object
String literal object is created in String Constant Pool, Before creating the object JVM will check
in String Constant Pool(String literal Pool) is there any object is exists with same content or not. If
any object exist with the same content then JVM will create a new reference for existing object.
otherwise it creates a new object in String constant pool.
Example:
In the above Literal example by executing String str1 = ”Hello”, JVM creates a new String object
in string constant pool, Because first time string constant pool doesn‟t contain any object with
“Hello” content.
While executing the statement String str2 = “Hello”, Instead of creating a new object JVM will
create a new reference(str2) for existing object. Because already string constant pool contains
an object with “Hello” content.
The following image shows how JVM creates objects in case of literal.
In case new operator, JVM always create a new object in the heap without checking is there any object
exist with same content or not.
Ex.
In the above case JVM creates three String objects two objects in heap, another one is in String
constant pool.
While executing String str1 = new String(“Hello”), JVM creates two String objects one is in Heap
another one is in string constant pool.
While executing String str2 = new String(―Hello”), JVM creates only one String object in
Heap, Because already string constant pool contains an object with “Hello” content.
String immutability
Immutability:
String is an immutable object, immutability means once String object is created, then the content of
the object can‟t be modified.
If we make any changes on String object instead of modifying the original object JVM will create a new
object.
2 str.concat(” Raj”);
3 System.out.Println(str);
Output: Hello
In the above scenario we are trying to modify the content of str object, but instead of modifying the
original object(str) content , JVM will create a new object in Heap.
Below diagram illustrates the behaviour of JVM while executing the statement. String str=”Hello”;
In the above scenario we are trying to modify the content of str object, but instead of modifying the
original object(str) content , JVM will create a new object in Heap.
Below diagram illustrates the behaviour of JVM while executing the statement. String str=”Hello”;
From the above diagram, str is holding the object which has the content “Hello”
Below diagram illustrates the behaviour of JVM while executing the statement str.concat(” Raj”);
While executing the statement str.concat(‖ Raj‖), we are trying to modify content of the str
Instead of modifying the str object, JVM creates a new object with “Hello Raj” content.
Here we can understand that once an object is created, then the content of the original object
cant be modified.
Ex:
3 System.out.Println(str);
In the above example str1, str2, str3 are pointing to the same object containing “hello”
1 str3 = “Welcome”;
In the above line we have changed str3 value from “hello” to “welcome”.
If String is not immutable then the changes will effect remaining references(str1,str2).
To overcome this problem String has been made immutable.
In the above example by executing String str1 = ”hello”, String str2 = ”hello” and String str3 = ”hello”,
all the references are pointing to the same object. Refer the below diagram.
Suppose if String is not immutable and for executing str3 = “Welcome”, the same will be effected
to str1 and str2which are pointing to the same object. Refer the below diagram
String concatenation
Concate operator (+) can concat String along with primtive values. concate operator(+) internally uses
StringBuffer to concate the values.
str = str+"york";
}
Output:
concat() method concatenates the specified string to the end of current string, concat() method can
concat only String objects.
1
public class StringTest2 {
2
public static void main(String[] args) {
3
String str = new String ("New");
4
str = str.concat("york");
5
System.out.println("String concatenation with concat method: "+str);
6
}
7
}
8
String Comparison
== operator
equals()
compareTo(String str)
By using == operator:
== operator checks the references(memory addresses) of two objects, but not content.
Example:
8 System.out.println(str == str1);
9 System.out.println(str1 == str2);
10 System.out.println(str1 == str3);
System.out.println(str3 == str4);
output:
false
true
false
false
str and str1 holding different objects, So both str and str1 memory addresses are different.
Then str==str1statement returns “false”.
str1 and str2 are holding same object based on String Constant Pool concept. So
both str and str1 memory addresses are same, Then str1==str2 statements returns “true”.
both str1 and str3 holding different objects in such case memory addresses are different ,
So str==str3statement returns “false”.
str3 and str4 holding different objects in suchcase memory addresses are different ,
So str3==str4 statement returns “false”.
Example:
8 System.out.println(str.equals(str1));
9 System.out.println(str.equals(str2));
10 System.out.println(str.equals(str3));
11 System.out.println(str3.equals(str4));
12 }
13 }
output:
false
true
true
true
str.equals(str1)statement returns “false” because contents in the both objects are different
str.equals(str2) statement returns “true”
str.equals(str3) statement returns “true”
str3.equals(str4) statement returns “true”
str, str2, str3 and str4 object‟s contents are the same, So for the above three statements the
result is “true”
This method is useful to compare two strings and we can know which string is bigger or smaller. And
the syntax is string1.compareTo(string2)
System.out.println(str.compareTo(str1));
System.out.println(str.compareTo(str2));
System.out.println(str.compareTo(str3));
output:
-2
0
17
In the above program, str.compareTo(str1)) statement returns “-2”. Because “ramya” comes
after ”ram” in the dictionary
str.compareTo(str2)) statement returns ”0”. Because for both str and str2 the contents are
equal
str.compareTo(str3)) statement returns ”17”. Because “ram” comes after “apple” in dictionary
intern() mehod
intern() method always returns the object from String constant pool, If the object is not avaialble then
JVM will create a new object in String constant pool.
1 {
3 {
4 String s1 = "Hello";
5 String s2 = "Hello";
7 System.out.println(s1 == s2);
8 System.out.println(s1 == s3);
9 System.out.println(s1 == s3.intern());
10 }
output:
true
false
true
StringBuffer
StringBuffer is a mutable object, which means the content of the object can be modified.
StringBuffer is a synchronized
If we perform any operation on a mutable class object, directly the original object gets
effected.StringBuffer objects does the same, by making changes using any of StringBuffer operations
then the original StringBuffer object will be effected.
Constructors:
StringBuffer():
StringBuffer(String str):
Constructs a string buffer initialized to the contents of the specified string.
EX:
StringBuffer(int capacity):
Constructs a string buffer with no characters in it and the specified initial capacity.
EX:
Methods in StringBuffer:
2 sb.append(“ john”);
3 sb.append(sb1);
int capacity():
Returns the current capacity.
EX:
2 char c = sb.charAt(2);
2 sb.delete(2 , 4);
StringBuffer reverse():
Causes this character sequence to be replaced by the reverse of the sequence.
EX:
2 sb.reverse();
2 sb.setCharAt( 2 , „k‟);
2 sb.setLength(4);
String toString():
Returns a string representing the data in this sequence.
EX:
void trimToSize():
Attempts to reduce storage used for the character sequence.
EX:
2 sb.trimToSize();
2 sb. ensureCapacity(32);
int length():
Example :
sBuffer1.append("york");
StringBuilder
StringBuilder is very similar like StringBuffer. Everything including all the operations are the
same, Only difference is StringBuilder is not synchronized.
Since StringBuilder is not thread-safe, it is faster than StringBuffer.
Constructors in StringBuilder:
StringBuilder():
StringBuilder(String str):
Constructs a string buffer initialized to the contents of the specified string.
EX:
StringBuilder(int capacity):
Constructs a string buffer with no characters in it and the specified initial capacity.
EX:
Methods in StringBuilder:
2 sb.append(“ john”);
3 sb.append(sb1);
int capacity():
Returns the current capacity.
EX:
2 char c = sb.charAt(2);
2 sb.delete(2 , 4);
StringBuilder reverse():
Causes this character sequence to be replaced by the reverse of the sequence.
EX:
2 sb.reverse();
2 sb.setCharAt( 2 , „k‟);
2 sb.setLength(4);
String toString():
Returns a string representing the data in this sequence.
EX:
void trimToSize():
Attempts to reduce storage used for the character sequence.
EX:
2 sb.trimToSize();
int length():
StringTokenizer
StringTokenizer
Constructors:
StringTokenizer(String str):
Creates a string tokenizer for the specified string.
Methods:
int countTokens():
Calculates the number of times that this tokenizer‟s nextToken method can be called before it
generates an exception.
boolean hasMoreElements():
Returns the same value as the hasMoreTokens method.
boolean hasMoreTokens():
Tests if there are more tokens available from this tokenizer‟s string.
Object nextElement():
Returns the same value as the nextToken method, except that its declared return value is Object
rather than String.
String nextToken():
Returns the next token from this string tokenizer.
Example:
import java.util.StringTokenizer;
while (st.hasMoreTokens()) {
String word=st.nextToken();
System.out.println(word);
output:
Hi
welcome
to
java
Call by value
While passing primitive values to methods, the original values are not be passed just the copy of the
value will be passed. If any changes happened to them inside method that will not effect original value
Example:
output:
While passing any object to method, Instead of passing reference it will pass memory address(memory
address is an integer value) of the object so if any changes happened on the object content in method,
then the original object content will be effected.
But in case of String the original value will not be effected, Because String is an immutable object
this.empId = empId;
this.empName = empName;
return empId;
this.empId = empId;
return empName;
this.empName = empName;
employeeManuplate(emp);
e.setEmpName("RamaKrishna");
System.out.println("id inside method==" + e.getEmpId());
output:
Static keyword
static variable :
static methods :
2 return "myName";
3 }
static block :
package com.core;
public class Test
static{
i = 10;
} }
Inner classes:
1 class OuterClass {
2 ...
4 ...
5 }
6 }
Instance block
Example:
1 package com.core;
3 {
4 {
5 int i = 10;
7 }
8 public Test()
9 {
10 System.out.println("inside constructor");
11 }
12 }
13
1 package com.core;
4 {
6 {
8 }
9 }
output :
final keyword
Variable level
Method level
Object level
Class level
Variable Level
When we use final keyword at variable level, we can‟t modify the value of the variable (modifying is
possible by using the Reflection).
Ex:
Method level
when we use final keyword at method level, that method can‟t be overridden.
Ex:
1 public final void getName(){
2 System.out.println("displaying name");
3 }
Object level
When we use final keyword at object level, that object reference can‟t be assigned to other object.
Ex 1:
Ex 2:
In the above case we have declared List reference as final and it is holding ArrayList object. If we try to
assign final List reference to LinkedList object it will through a compile time exception.
Because final reference can‟t be assigned to any object.
In the above Example 2, final str is already holding hello object and we are trying to modify str so we
will get an exception here.
Class level
Ex:
package com.core;
System.out.println("displaying name");
}
Inner class
1 class OuterClass {
2 ...
3 class NestedClass {
4 ...
5 }
6 }
Using inner classes we can develop more readable and maintainable code.
Using inner classes we are logically grouping classes that are only used in one place.
1) Member class
3) Local class
4) Anonymous class
Member class
3 class Inner{
6 }
7 }
8 }
13 innerObj.show();
14
A class that is defined as a static member of another class is known as static inner class. It is also
called as top level inner class.
}
14
public class Main {
1
public static void main(String[] args) {
1
Outer outer = new Outer();
outer.getMessage();
innerObj.show();
Local class
Anonymous class
A class which declared inside of a class without any name is known as anonymous inner class.It is
always is used to write a sub class to an interface or a class.
void show();
//Anonymous class
Test test = new Test(){
};
test.show();
Exceptions
An Exception is an abnormal condition which interrupts the normal flow of the program.
CheckedException
UncheckedException
Checked vs unchecked exceptions
Checked Exception :
Ex:
IOException
ClassNotFoundException
SQLException
FileNotFoundException
Ex:
NumberFormatException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
NullPointerException
ClassCastException
Error :
Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception handling.
Let‟s take a scenario:
1 statement 1;
2 statement 2;
3 statement 3;
4 statement 4;
6 statement 6;
7 statement 7;
8 statement 8;
9 statement 9;
10 statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of
the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest
of the statement will be executed. That is why we use exception handling in java.
Generally exceptions can handle by using try, catch and finally block.
try :
The try block contains set of statements which can cause the exception.
For every try block we should have atleast one catch or finally block
One try block can have multiple catch blocks or one finally block
catch :
While providing multiple catch blocks first we should catch sub-class exception then we
should catch the super-class exception otherwise we will get Unreachable Catch block
Exception at compile time
We shouldn‟t provide a catch block without defining a try block
finally :
finally block is used to close the resources like database connections, files, and JMS connections
finally block will be executed irrespective of whether there is an exception occurred in the try
block or not
Possibilities of try-catch:
try{
catch(Exception e){
finally{
1 try{
3 }
4 catch(Exception e1){
6 }
7 catch(Exception e2){
9 }
1 try{
3 }
4 catch(Exception e1){
6 }
7 try{
9 }
10 catch(Exception e2){
11
12 }
2 try{
4 try{
6 }
7 catch(Exception e){
8 }
9 }
10 catch(Exception e){
11 }
12
2
try{
3
}
4
catch(Exception e){
5
try{
6
}
7
catch(Exception e){
8
}
9
}
10
11
try{
try{
}
catch(Exception e){
catch(Exception e){
try{
catch(Exception e){
try {
int i = 4 / 2;
System.out.println(i);
int j = 5 / 0;
System.out.println(j);
ae.printStackTrace();
finally{
Output:
2
java.lang.ArithmeticException: / by zero
at ExceptionEx.main(ExceptionEx.java:6)
inside finally block
Outside of Exception Handling
In the above program, we are dividing 5 with 0. In this case we will get ArithematicalException.
We are handing this exception using try-catch-finally blocks. Even though we are getting exception,
remaining code had been executed without any interruption.
import java.io.FileInputStream;
1 import java.io.FileNotFoundException;
2 import java.io.IOException;
6 try {
8 int character;
10 System.out.print(character);
11 }
12 } catch (FileNotFoundException e) {
13
14 e.printStackTrace();
15 } catch (IOException e) {
16
17 e.printStackTrace();
18 }
19
20 finally {
}
}
In the above example our code throws FileNotFoudException and IOException. While providing catch
blocks, first we are catching FileNotFoudException because it is sub-class exception of IOException.
class should contain default and one parametrized constructor with String.
//Default constructor
public MyCheckedException() {
super(msg);
Ex:
try {
test.numberCheck(-1);
} catch (MyCheckedException e) {
if(number < 0)
return true;
}
Output:
class should contain default and one parametrized constructor with String.
//Default constructor
MyOwnUncheckedException(){
MyOwnUncheckedException(String msg) {
super(msg);
Ex:
try {
test.numberCheck(-1);
} catch (MyOwnUncheckedException e) {
return true;
throw:
Example:
1
public class ThrowTest {
2
public boolean numberCheck(int number) {
3
if(number < 0)
4
throw new ArithmeticException("No negatives allowed!!");
5
return true;
6
}
7
public static void main(String[] args) {
8
ThrowTest test = new ThrowTest();
9
try {
10
test.numberCheck(-1);
11
} catch (ArithmeticException e) {
12
System.out.println("Exception says: "+e.getMessage());
13
}
14
}
15
}
16
throws:
throws is a keyword which is used to throw an exception. If programmer doesn‟t want to handle
any exception caused by a method, then programmer can throw the exception by
using throws keyword so that the exception will be handled by the method caller or the JVM.
throws keyword is used at method level.
If a method contains statements causing any exceptions then the method should specify all the
possible exceptions to the caller of that method.
Example:
1 import java.io.FileInputStream;
2 import java.io.IOException;
7 int character;
9 System.out.print(character);
10 }
11 }
12 }
This main() method is called by JVM. So JVM itself is responsible to handle this exception.
Writing try block inside another try block is known as nested try block.
Ex:
try {
try {
array[10] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
try {
int x= 10/0;
} catch (ArithmeticException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
at com.exception.NestedTryTest.main(NestedTryTest.java:10)
java.lang.ArithmeticException: / by zero
at com.exception.NestedTryTest.main(NestedTryTest.java:17)
finally Block
The statements inside the finally block always gets executed, regardless whether an exception is
occurred or not in a try block.
Even though there is a return statement in the try or catch block, the code inside the finally
block gets executed before completion of the method execution
finally block is used to close the resources like database connections, files, and JMS connections
finally block statements always gets executed regardless of whatever happens in the try block.
So it is suggestible to keep all the cleanup code in the finally block
Example:
package com.test;
public class FinallyTest {
//first case
try {
result = 252/0;
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("result: "+result);
//second case
try {
result = 252/2;
} catch (Exception e) {
e.printStackTrace();
}finally {
System.out.println("result: "+result);
System.out.println("Leaving Now!!");
Output:
In the first case of the above example, ArithmeticException had been occurred while
dividing by zero. Since it is ArithmeticException, its own catch block [catch (ArithmeticException e)] got
executed and printed the message in console. Then the control has executed the print statement
written within the finally block
In the second case, even though there is no any exception occurred in the try block, finally
block had been executed
Collection:
Arrays also used to store the group of objects. But arrays size are fixed, That means the size of the
arrays can not be changed once they are created. This causes lot of problems while handling group of
objects. To overcome this problems java has introduced Collection framework
What is Collection?
Array Collection
Arrays are fixed size, You can not change the size of the
Performance point of view arrays is highly recommended Performance point of view collection is
Arrays can hold only homogeneous type of elements and heterogeneous type of elements
Arrays can be used to store both primitive values and collection can be used to store only
There is no underlying data structure for arrays for every collection class
Collection Hierarchy :
Collection:
As in the above diagram the root of the collection hierarchy is Collection interface. A collection
represents a group of objects known as its elements.Collection interface has the below stated methods.
List:
ArrayList
LinkedList
Vector
HashSet
LinkedHashSet
TreeSet
CopyOnWriteArraySet
EnumSet
SortedSet:
TreeSet
NavigableSet:
TreeSet
Queue:
LinkedList
PriorityQueue
ArrayDeque
List, Set, SortedSet, NavigableSet and Queue is used to store a group of individual objects.
If we want to store a group of objects as a key-value pair then we should go for Map
Map:
HashMap
Hashtable
TreeMap
IdentityHashMap
LinkedHashMap
ConcurrentHashMap
EnumMap
WeakHashMap
Properties
SortedMap:
TreeMap
NavigableMap:
TreeMap
Collection API:
Collection interface contains the most common methods which can be applied for any collection object
List contains the following methods.
Methods :
void clear():
Removes all of the elements from this collection .
boolean isEmpty():
Returns true if this collection contains no elements.
Iterator iterator():
Returns an iterator over the elements in this collection.
int size():
Returns the number of elements in this collection.
Object[] toArray():
Returns an array containing all of the elements in this collection.
Iterators in java
1. Iterator
2. ListIterator
3. Enumeration
4. for-each
Iterator
Iterator is an interface. By using iterator we can retrieve the elements one by one from the collection.
Methods in Iterator:
boolean hasNext() :
Returns true if the iteration has more elements.
elementNext():
This method returns the next element in the iterator.
void remove():
Removes from the underlying collection the last element returned by this iterator.
ListIterator
ListIterator is an interface.
By using ListIterator we can retrieve the elements from the list , both forward and reverse direction.
Methods in ListIterator:
void add(E e):
Inserts the specified element into the list
boolean hasNext() :
Returns true if this list iterator has more elements when traversing the list in the forward direction.
boolean hasPrevious():
Returns true if this list iterator has more elements when traversing the list in the reverse direction.
element next():
Returns the next element in the list and advances the cursor position.
int nextIndex():
Returns the index of the element that would be returned by a subsequent call to next().
element previous():
Returns the previous element in the list and moves the cursor position backwards.
int previousIndex():
Returns the index of the element that would be returned by a subsequent call to previous().
void remove():
Removes from the list the last element that was returned by next() or previous()
Enumeration
Enumeration is an interface.
By using enumeration interface we retrieve the elements from the collection one by one like itertor.But
enumeration normally we are using to iterate over legacy collection(Vector).
Methods:
boolean hasMoreElements():
Tests if this enumeration contains more elements.
element nextElement():
Returns the next element of this enumeration if this enumeration object has at least one more element
to provide.
For-each Loop
for-each loop is like for loop which repeatedly executes a group of statements for each element of the
collection.
Format:
1 for(variable : collection-object)
2 {
3 Group of statements
4 }
Generics
From JDK 5 compiler will forces the programmer to store specific type of objects in generic collection.
Syntax
Examples :
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
list.add(2);
list.add(8);
list.add("Apple");
Iterator it=list.iterator();
while (it.hasNext()) {
System.out.println(num);
Output:
2
8
Exception in thread “main” java.lang.ClassCastException: java.lang.String cannot be cast to
java.lang.Integer at com.core.GenericsEx.main(GenericsEx.java:18)
In the above program we have added string and integer objects to the list , but while iterating we are
typecasting to integer. string can‟t be typecasted to integer. So we are getting ClassCastException
here.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
list.add(2);
list.add(8);
list.add(4);
list.add(1);
while (iterator.hasNext()) {
System.out.println(num);
Output:
2
8
4
1
ArrayList in java
Constructors :
ArrayList(Collection<? extends E> c): Constructs a list containing the elements of the specified
collection, in the order they are returned by the collection‟s iterator.
ArrayList(int initialCapacity): Constructs an empty list with the specified initial capacity.
Ex.
Methods:
Method Description
boolean add(E e) Appends the specified element to the end of this list.
boolean addAll(int index, Collection<? Inserts all of the elements in the specified collection
extends E> c): into this list, starting at the specified position.
capacity argument.
void ensureCapacity(int minCapacity):
proper sequence.
Iterator iterator():
exclusive.
List subList(int fromIndex, int toIndex):
element).
Object[] toArray():
1 import java.util.ArrayList;
6 list.add("ok");
7 list.add("bye");
8 System.out.println(list);
import java.util.ArrayList;
list.add(5);
list.add(4);
1 list.add(8);
list.add(10);
list.add(12);
System.out.println(list.get(i));
Output :
5
4
8
10
12
import java.util.ArrayList;
import java.util.Iterator;
list.add(5);
list.add(4);
list.add(8);
list.add(10);
list.add(12);
while (iterator.hasNext()) {
int i = iterator.next();
System.out.println(i);
Output :
5
4
8
10
12
import java.util.ArrayList;
import java.util.ListIterator;
list.add(5);
list.add(4);
list.add(8);
list.add(10);
list.add(12);
while (listIterator.hasNext()) {
int i = listIterator.next();
System.out.println(i);
while (listIterator.hasPrevious()) {
int i = listIterator.previous();
System.out.println(i);
Output:
import java.util.ArrayList;
public class Main {
list.add(5);
list.add(4);
list.add(8);
list.add(10);
list.add(12);
System.out.println(i);
Output:
5
4
8
10
12
this.name = name;
this.empId = empId;
return name;
}
public void setName(String name) {
this.name = name;
return empId;
this.empId = empId;
Main.java
import java.util.ArrayList;
list.add(employee1);
list.add(employee2);
list.add(employee3);
Output :
173 Krish
174 Ram
175 sachin
Main.java
import java.util.ArrayList;
import java.util.Iterator;
list.add(employee1);
list.add(employee2);
list.add(employee3);
while (iterator.hasNext()) {
System.out.println(employee.getEmpId()+" "+employee.getName()); }
Output:
173 Krish
174 Ram
175 sachin
package com.mypackage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
list.add(5);
list.add(2);
list.add(8);
list.add(4);
Collections.reverse(list);
Collections.sort(list);
while (iterator.hasNext()) {
int i = iterator.next();
System.out.println(i);
Output:
Vector in java
Vector Constructors
2 list.add(“apple”);
Vector(int initialCapacity) : It creates a vector object with empty content with the given initial
capacity.
Ex:
Vector(int initialCapacity, int capacityIncrement): It creates a vector object with empty content
with the given initial capacity and capacity increment.
Ex:
Methods:
Method Description
they are
boolean addAll(Collection<? extends E> c): returned by the specified Collection‟s Iterator
boolean addAll(int index, Collection<? Inserts all of the elements in the specified Collection
Int hashCode(): Returns the hash code value for this Vector.
int indexOf(Object o, int index): from index, or returns -1 if the element is not found.
void removeRange(int fromIndex, int index is between fromIndex, inclusive, and toIndex,
toIndex): exclusive.
List subList(int fromIndex, int toIndex): fromIndex, inclusive, and toIndex, exclusive.
Returns an array containing all of the elements in
Ex:
1 import java.util.Vector;
5 list.add("hello");
6 list.add("ok");
7 list.add("bye");
8 System.out.println(list);
9 }
10 }
Vector Programs
1 import java.util.Enumeration;
2 import java.util.Vector;
7 vector.add("Apple");
8 vector.add("Orange");
9 vector.add("Banana");
10 Enumeration<String> e = vector.elements();
11 while (e.hasMoreElements()) {
13 System.out.println(fruit);
14 }
Output:
3
Apple
Orange
Banana
1 import java.util.Enumeration;
2 import java.util.Vector;
6 vector.add("Apple");
7 vector.add("Orange");
8 vector.add("Banana");
9 System.out.println(vector.size());
10 System.out.println(vector.contains("Orange"));
11 System.out.println(vector.elementAt(1));
12 System.out.println(vector.firstElement());
13 System.out.println(vector.get(0));
14 System.out.println(vector.isEmpty());
15 }
16 }
17
Output :
3
true
Orange
Apple
Apple
false
LinkedList
In case of inserting or deleting elements in between the collection, LinkedList is faster then
ArrayList because it performs these operations without any shifting, By simply updating the
previous and next nodes of the elements
LinkedList supports Iterator and ListIterator.
In single LinkedList the node consists of only two fields one is data field another one is the reference to
next node.
In double LinkedList the node has three fields, first field reference to the previous node , second field
value of the element and third field reference to the next node.
Constructors:
2 arl.add(“Apple”);
3 arl.add(“Orange”);
Methods:
Method: Description
boolean add(E e): Appends the specified element to the end of this list.
boolean addAll(Collection<? end of this list, in the order that they are returned by the
boolean addAll(int index, Inserts all of the elements in the specified collection into this
void addFirst(E e): Inserts the specified element at the beginning of this list.
void addLast(E e): Appends the specified element to the end of this list.
boolean contains(Object o): Returns true if this list contains the specified element.
element element():
Retrieves, but does not remove, the head (first element) of
this list.
element get(int index): Returns the element at the specified position in this list.
ListIterator listIterator(int Returns a list-iterator of the elements in this list (in proper
boolean offerFirst(E e): Inserts the specified element at the front of this list.
boolean offerLast(E e): Inserts the specified element at the end of this list.
Retrieves, but does not remove, the first element of this list,
Retrieves, but does not remove, the last element of this list,
element poll(): Retrieves and removes the head (first element) of this list.
element pollFirst():
Retrieves and removes the first element of this list, or
returns null if this list is empty.
element pop(): Pops an element from the stack represented by this list.
void push(E e): Pushes an element onto the stack represented by this list.
element remove(): Retrieves and removes the head (first element) of this list.
element remove(int index): Removes the element at the specified position in this list.
element removeFirst(): Removes and returns the first element from this list.
removeFirstOccurrence(Object o): list (when traversing the list from head to tail).
element removeLast(): Removes and returns the last element from this list.
removeLastOccurrence(Object o): list (when traversing the list from head to tail).
1 import java.util.Iterator;
2 import java.util.LinkedList;
6 ll.add("Apple");
7 ll.add("Mango");
8 ll.add("Banana");
9 System.out.println(ll.get(0));
10 System.out.println(ll.getFirst());
11 System.out.println(ll.getLast());
12 System.out.println(ll.contains("Mango"));
13 System.out.println(ll.size());
14 System.out.println(ll.subList(1, 2));
Output:
Apple
Apple
Banana
true
3
[Mango]
HashSet
Constructors:
HashSet(Collection<? extends E> c): It creates a new HashSet object with the specified collection.
Ex:
2 list.add(“Apple”);
3 list.add(“Grape”);
HashSet(int initialCapacity): It creates a new HashSet object with the specified initial capacity and
default load factor (0.75).
Ex: HashSet hs=new HashSet (12);
HashSet(int initialCapacity, float loadFactor): Constructs it creates a new HashSet object with the
specified initial capacity and the specified load factor.
Ex:
Methods
Method Description
Ex:
import java.util.HashSet;
hashSet.add("hello");
hashSet.add("ok");
hashSet.add("bye");
System.out.println(hashSet);
HashSet Programs
Below is the program to add elements and iterating the HashSet using for-each-loop
import java.util.HashSet;
hSet.add("Maruthi");
hSet.add("Audi");
hSet.add("BMW");
hSet.add("Maruthi");
Output:
3
Audi
BMW
Maruthi
1 import java.util.HashSet;
2 import java.util.Iterator;
6 hSet.add("Maruthi");
7 hSet.add("Audi");
8 hSet.add("BMW");
9 hSet.add("Maruthi");
10 System.out.println(hSet.size());
11 System.out.println(hSet.contains("Audi"));
12 System.out.println(hSet.isEmpty());
15 while(iterate.hasNext()){
17 System.out.println(car);
18 }
20 for(String s : hSet)
21 {
22 System.out.println(s);
Output:
3
true
false
Audi
BMW
Maruthi
LinkedHashSet
LinkedHashSet is similar like HashSet but only difference is it follows the insertion order
It implements Set interface
LinkedHashSet doesn‟t allow duplicate elements but it allows null values
It supports Iterator
It internally uses LinkedHashMap [The object we have inserted into the LinkedHashSet that will
put in the LinkedHashMap as a key and the value is a dummy object (private static final Object
PRESENT = new Object())]
Default initial capacity 16 and load factor 0.75
Constructors:
LinkedHashSet(): Constructs a new, empty linked hash set with the default initial capacity (16) and
load factor (0.75)
Ex:
LinkedHashSet(Collection<? extends E> c): Constructs a new linked hash set with the same
elements as the specified collection.
Ex:
2 list.add(“Apple”);
3 list.add(“Grape”);
LinkedHashSet(int initialCapacity): Constructs a new, empty linked hash set with the specified
initial capacity and the default load factor (0.75)
Ex:
1 LinkedHashSet hs=new LinkedHashSet (12);
LinkedHashSet(int initialCapacity, float loadFactor): Constructs a new, empty linked hash set
with the specified initial capacity and load factor
Ex:
Methods:
Method Description
boolean add(E e): Adds the specified element to this set if it is not already present
boolean contains(Object
boolean remove(Object
int size(): Returns the number of elements in this set (its cardinality)
Example:
1 import java.util.Iterator;
2 import java.util.LinkedHashSet;
7 lhs.add("Audi");
8 lhs.add("BMW");
9 lhs.add("Maruthi");
10 System.out.println(lhs.size());
11 System.out.println(lhs.contains("Audi"));
12 System.out.println(lhs.isEmpty());
14 while(it.hasNext()){
16 System.out.println(car);
17 }
18 }
Output :
3
true
false
Maruthi
Audi
BMW
TreeSet
Constructors:
TreeSet(): Creates a new, empty tree set, sorted according to the natural ordering of its elements.
TreeSet(Collection c): Creates a new tree set containing the elements in the specified collection,
sorted according to the natural ordering of its elements.
TreeSet(Comparator comparator): Creates a new, empty tree set, sorted according to the specified
comparator.
TreeSet(SortedSet s): Creates a new tree set containing the same elements and using the same
ordering as the specified sorted set.
Methods:
Method Description
boolean addAll(Collection<? extends E> Adds all of the elements in the specified collection to
TreeSet programs
import java.util.TreeSet;
ts.add("Apple");
ts.add("Mango");
ts.add("Banana");
ts.add("Orange");
System.out.println(ts);
System.out.println(ts.size());
System.out.println(ts.contains("Mango"));
System.out.println(ts.first());
System.out.println(ts.subSet("Banana", "Orange"));
Output:
3
[Apple, Banana, Mango, Orange] 4
true
Apple
[Banana, Mango]
super();
this.empclass= empId;
this.empName = empName;
return empId;
this.empclass= empId;
return empName;
this.empName = empName;
return 1;
return -1;
}
return 0;
Employee.java
import java.util.TreeSet;
System.out.println(set);
Output:
5 super();
6 this.empclass= empId;
7 this.empName = empName;
8 }
11 }
13 this.empclass= empId;
14 }
16 return empName;
17 }
19 this.empName = empName;
20 }
Employee.java
Below is our comparator class that was written to sort Employee's IDs
1 import java.util.Comparator;
4 Employee e1=(Employee)obj1;
7 return 1;
8 }
10 return -1;
11 }
12 return 0;
13 }
14 }
15
import java.util.TreeSet;
System.out.println(set);
HashMap
Constructors:
HashMap(): Constructs an empty HashMap with the default initial capacity (16) and the default load
factor (0.75).
Ex:
HashMap(int initialCapacity, float loadFactor) : Constructs an empty HashMap with the specified
initial capacity and load factor.
Ex:
HashMap(Map<? extends K,? extends V> m): Constructs a new HashMap with the same mappings
as the specified Map.
Ex:
Methods:
Method Description
Object clone(): the keys and values themselves are not cloned.
boolean isEmpty():
Returns true if this map contains no key-value
mappings.
void putAll(Map<? extends K,? extends V> Copies all of the mappings from the specified map to
HashMap Programs
Below are the programs to add elements to HasMap and iterating in different ways
1 import java.util.HashMap;
2 import java.util.Set;
3 import java.util.Map.Entry;
7 map.put("Apple", 20);
8 map.put("Mango", 10);
9 map.put("Orange", 13);
10 System.out.println("map===>"+map);
13 System.out.println(entry);
Output:
ArrayList sorting can be done by simply calling the Collections.sort(List list) method
Collections.sort(List list) method by default sort all wrapper class objects and String objects
In case List contains String objects, The List will be sorted alphabetically
import java.util.ArrayList;
1
import java.util.Collections;
2
import java.util.List;
3
public class StringListEx {
4
public static void main(String[] args) {
5
List<String> list = new ArrayList<>();
6
list.add("Krishna");
7
list.add("Ram");
8
list.add("Arjun");
9
list.add("Laxman");
10
list.add("Venkat");
11
System.out.println("Before sorting: " + list);
12
Collections.sort(list);
13
System.out.println("After sorting: " + list);
14
}
Output:
Collections.sort() method can be used for sorting the Integer objects as well.
1 import java.util.ArrayList;
2 import java.util.Collections;
3 import java.util.List;
7 list.add(2);
8 list.add(7);
9 list.add(5);
10 list.add(6);
11 list.add(4);
12 list.add(3);
13 list.add(1);
15 Collections.sort(list);
17 }
Output:
1 import java.util.ArrayList;
2 import java.util.List;
7 duplicateList.add("Krishna");
8 duplicateList.add("Ram");
9 duplicateList.add("Arjun");
10 duplicateList.add("Laxman");
11 duplicateList.add(null);
12 duplicateList.add("Venkat");
13 duplicateList.add("Venkat");
14 duplicateList.add(null);
18 if(!uniqueList.contains(name)) {
19 uniqueList.add(name);
20 }
21 }
Output :
Before removing duplicates: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]
By converting List to Set we can avoid duplicate elements, Since Set doesn‟t contain duplicate
elements
1 import java.util.ArrayList;
2 import java.util.HashSet;
3 import java.util.List;
4 import java.util.Set;
9 list.add("Krishna");
10 list.add("Ram");
11 list.add("Arjun");
12 list.add("Laxman");
13 list.add(null);
14 list.add("Venkat");
15 list.add("Venkat");
16 list.add(null);
Output:
Before removing duplicates: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]
Java 8 streams provide a very simple way to remove duplicate elements from a list. Using the distinct
method.
1 import java.util.ArrayList;
2 import java.util.List;
3 import java.util.stream.Collectors;
8 list.add("Krishna");
9 list.add("Ram");
10 list.add("Arjun");
11 list.add("Laxman");
12 list.add(null);
13 list.add("Venkat");
14 list.add("Venkat");
15 list.add(null);
17 list = list.stream().distinct().collect(Collectors.toList());
19 }
Output:
Before removing duplicates: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]
1 import java.util.ArrayList;
2 import java.util.List;
6 list.add("Krishna");
7 list.add("Ram");
8 list.add("Arjun");
9 list.add("Laxman");
10 list.add(null);
11 list.add("Venkat");
12 list.add("Venkat");
13 list.add(null);
16 if(list.get(i) == null) {
17 list.remove(i);
18 }
19 }
Output:
Before removing null values: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]
Iterating ArrayList
1 import java.util.ArrayList;
2 import java.util.List;
7 list1.add("Krishna");
8 list1.add("Ram");
9 list1.add("Arjun");
10 list1.add("Laxman");
11 list1.add(null);
12 list1.add("Venkat");
13 list1.add("Venkat");
14 list1.add(null);
17 if (null != name) {
18 list2.add(name);
19 }
20 }
Output:
Before removing null values: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]
1 import java.util.ArrayList;
2 import java.util.Collections;
3 import java.util.List;
7 list.add("Krishna");
8 list.add("Ram");
9 list.add("Arjun");
10 list.add("Laxman");
11 list.add(null);
12 list.add("Venkat");
13 list.add("Venkat");
14 list.add(null);
16 list.removeAll(Collections.singleton(null));
18 }
Output:
Before removing null values: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]
import java.util.ArrayList;
import java.util.List;
1
import java.util.Objects;
2
public class RemovingDuplicateEx1 {
3
public static void main(String[] args) {
4
List<String> list = new ArrayList<>();
5
list.add("Krishna");
6
list.add("Ram");
7
list.add("Arjun");
8
list.add("Laxman");
9
list.add(null);
10
list.add("Venkat");
11
list.add("Venkat");
12
list.add(null);
13
System.out.println("Before removing null values: "+list);
14
list.removeIf(Objects::isNull);
15
System.out.println("Before removing duplicates: "+list);
16
}
Output:
Before removing null values: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]
1 import java.util.ArrayList;
2 import java.util.List;
3 import java.util.stream.Collectors;
4 public class RemovingDuplicateEx1 {
7 list.add("Krishna");
8 list.add("Ram");
9 list.add("Arjun");
10 list.add("Laxman");
11 list.add(null);
12 list.add("Venkat");
13 list.add("Venkat");
14 list.add(null);
Output:
Before removing null values: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]
Using set(int index, E element) method we can replace the element at the specified position in this list
with the specified element
1 import java.util.ArrayList;
2 import java.util.List;
6 list.add("Krishna");
7 list.add("Ram");
8 list.add("Arjun");
9 list.add("Laxman");
10 list.add(null);
11 list.add("Venkat");
12 list.add("Venkat");
13 list.add(null);
16 list.set(1, "John");
18 }
Output:
Before updating list`: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]
After updating list`: [Krishna, John, Arjun, Laxman, null, Venkat, Venkat, null]
ArrayList Vector
ArrayList storing capacity will be increased by half of it‟s by double of it‟s original storing
original storing capacity, when the current storing capacity capacity, when the current storing
ArrayList is performance is high, Because threads need not makes the threads to wait for object
to wait for object lock to access ArrayList object lock to enter into vector object
Implementing our own ArrayList class, Which contains add(), get(), remove(), size() methods.
MyArrayList.java
1 import java.util.Arrays;
5 public MyArrayList() {
7 this(10);
8 }
10 if (initialCapacity < 0)
14 }
17 arr[size++] = obj;
18 return true;
19 }
26 }
27 }
29 return size;
30 }
31 public Object get(int index) {
34 }
35 return arr[index];
36 }
40 }
43 if (numMoved > 0)
arr[--size] = null;
return oldValue;
Main.java
5 list.add("Apple");
6 list.add("Mango");
7 list.add("Orange");
8 list.add("Banana");
9 list.add("Pineapple");
10 list.add("Grapes");
11 list.add(10);
12 list.remove(4);
14 System.out.println(list.get(i));
15 }
16 }
17 }
Output:
Apple
Mango
Orange
Banana
Grapes
10
10. In case of inserting or deleting elements in between the collection, LinkedList is faster then
ArrayList because it performs these operations without any shifting, By simply updating the
previous and next nodes of the elements
11. LinkedList supports Iterator and ListIterator.
12. LinkedList can be synchronized by using Collections.synchronizedList(List list) method
13. The iterator() and listIterator() both methods are return fail-fast iterators
14. If the LinkedList is structurally modified at any time while iterating, The iterator will throw
a ConcurrentModificationException except through the Iterator‟s own remove or add
methods
15. LinkedList contains descendingIterator() method which returns an Iterator object containing all
elements of a LinkedList in the reverse order
16. LinkedList contains offer() and poll() methods which make LinkedList to work as a Queue
17. LinkedList contains pop() and push() methods which makes LinkedList as a Stack
18. LinkedList contains add() or addLast() or offer() or offerLast() to add the elements at the end of
the LinkedList
19. LinkedList contains addFirst() or offerFirst() to add the elements at the head of the LinkedList
20. pollLast() and removeLast() methods remove the elements from the tail of the LinkedList
21. poll() or pollFirst() or remove() or removeFirst() methods remove the elements from the head
of the LinkedList
22. The subList(int fromIndex, int toIndex) method of Vector returns a List object between the
specified fromIndex, inclusive, and toIndex, exclusive
23. toArray() method of Vector converts ArrayList to Object array
24. toString() method is overridden in Vector to display the content in array format
25. Vector implements Serializable and Cloneable interfaces
In single LinkedList the node consists of only two fields one is data field another one is the reference to
next node.
In double LinkedList the node has three fields, first field reference to the previous node , second field
value of the element and third field reference to the next node.
Hashtable
Constructors:
Hashtable(): Constructs a new, empty hashtable with a default initial capacity (11) and load factor
(0.75).
Hashtable(int initialCapacity): Constructs a new, empty hashtable with the specified initial capacity
and default load factor (0.75).
Hashtable(int initialCapacity, float loadFactor): Constructs a new, empty hashtable with the
specified initial capacity and the specified load factor.
1 Hashtable <String, String> ht = new Hashtable <String, String>(20, 0.90);
Hashtable(Map t): Constructs a new hashtable with the same mappings as the given Map.
Methods:
Method Description
void putAll(Map<? extends K,? extends V> Copies all of the mappings from the specified map to
Array
Array is an object
Arrays are used to store multiple elements
Arrays are allowed only same type of elements
Arrays are stored elements on index based
Array index starts with 0, The first element of the array is stored at 0 index
Elements are accessed from array by using there indexes
Arrays are fixed size, Which means the size of the array can not be modified once they are created
1 int[] arr;
2 int arr[];
3 int []arr;
The above case int represents integer type elements, Which can be stored into array
Every array is an object in java, So array can be created by using new operator
At the time of instantiation we must specify the size of the array otherwise we will get compile time
error
The size represents number of elements can be stored into the array
The size value must be byte, short, int and char type only
syntax:
int[] arr = new int[size];
Ex:
2 int arr2[] = new int['a']; //Creates an array with size 97 'a' ASCII value is 97
3 byte b =10;
When JVM executes int[] arr1 = new int[5]; line of code JVM allots memory for storing 5 int values
into the array, But actually we have not stored any values, In such case JVM stores integer default
values
Storing elements into the array
1 arr1[0] = 20;
2 arr1[1] = 25;
3 arr1[2] = 30;
4 arr1[3] = 31;
5 arr1[4] = 32;
When JVM executes above line of code, elements are stored into the array the following manner
3 int[] arr = { 1, 4, 5, 8, 7 };
4 System.out.println(arr[0]);
5 System.out.println(arr[1]);
6 System.out.println(arr[2]);
7 System.out.println(arr[3]);
8 System.out.println(arr[4]);
9 }
Output:
1
4
5
8
7
3 int[] arr = { 1, 4, 5, 8, 7 };
5 System.out.println(arr[i]);
6 }
7 }
8 }
Output:
14587