My Java Notes
My Java Notes
1.programming language
2.platform
Note: java is not only programming language it is also a platform. Java programming
language used to develop apptions and services
Types of apptions:
2.distributed apptions
1.standalone apption:
2.distributed apption:
console apptions:
window apptions:
1.Web apptions
2.Enterprise apptions
Web apption: it is a distributed apptions which runs on web browser and web server.
A static web apption is a web apption which resides in server and executes in browser
Static web apptions can be developed by using HTML, java script, VB script…etc
A dynamic web apption is a web apption which resides in server and executes in server
only
dynamic web apptions can be developed by using Servlets, java server pages…etc
Enterprise apption:
Services:
Notepad.exe
Types of services:
1.window services
2. Web services
1.Window service: it is a service and it is used by window apption to run under operating
system
1.javaSE
2.javaEE
3.javaME
4.javaFX
1.javaSE
It is the widely used java platform for developing console apptions, window apption and
static web apptions.
2.javaEE
It is a widely used java platform for developing dynamic web apptions, enterprise
apptions and services.
3.javaME
4.javaFX:
It is java platform designed for rich internet apptions. Rich internet apptions means
which contains more graphics
JDK
JDK stands for Java Development Kit.It physically exists.It contains JRE + development
tools.
JRE
JRE stands for Java Runtime Environment. It is used to provide runtime environment. It
is the implementation of JVM. It physically exists. It contains set of libraries +
other files that JVM uses at runtime. Jre is part of jdk
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides
runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are
platform dependent because configuration of each OS differs. But, Java is platform
independent.
Loads code
Verifies code
Executes code
If the source file contains public class then file neme must match with public class name
If the source file does not contain public class then no naming restriction to file name
If we define a class in side the package then then package statement must be declared at
first line in the source file.
Inside a source file, import statements must be declared between package statement and
class declaration.
Note: If there is no package statement then import statement must be declared at first
line.
.
1.package & subpackage: all small letters. Sub packages are separated with( ) symbol
Ex: 1.java.lang
2.Java.awt.event
2.class and interface:
Usually class names are nouns, should starts with Upper case letter. If ti contains
multiple words every inner word should starts with upper case letterl. No space
between words
Ex: 1.String
2.StringBuffer
3.ArrayIndexOutOfBoundsException
Usually interface names are adjectives should starts with uppercase letter and if it
contains multiple words everyh inner word should starts with uppercase letter.
No space between the words
1.Serializable
2.Runnable
3.Cloneable
3.variable and method: second word onwards first letter of the word is capital. No space
between words
Ex.
1.empNo
2.netIncome
3.compareTo( )
4.toString
To compile:
javac filename.java
To:run:
Java classname
Identifiers
A name in the program is an identifier it may be class name or method name,variable
name or label name.
Ex:
3) There is no length limit for java identifiers but it is not recommended to take more
than 15
length.
6.the names of predefined classes and interfaces can be used as identifiers but it is not
recommended.
Reserved Words
Some identifiers are reserved to associate some functionality or to represent values,
such type of reserved identifiers are called “ReservedWords”.
In java total 53 keywords are there. In this 50 key words and 3 reserved literals
Datatypes:
Datatype defines the type of value that can be stored in a particular variable.
Data types are used to specify the how much memory is allocated for
variables.
There are 8 primitive data types in java and those are named by keywords.
Data type Size Range Default values
Reference datatype:
Arrays,Strings,Classes, Interfaces
Literals:-
Octal literals: allowed digits are 0 to 7 but here literal value should be prefixed with
0(zero)
Hexadecimal literals: the allowed digits are 0 to 9, A- F (Both lower, Upper case) literals
class Demo
int x = 10;
int y = 010;
int z = 0x10;
B. float f = 10.5f;
we can specify explicitly a floating point literal of double type by suffixing with d or D.
double d = 10.5D;
Boolean Literals
The only allowed values for boolean datatype are true, false.
1. boolean b = true;
character literal
A char literal can be represented as a single character with in single quotes.
Ex:
char ch = 'a';
we can represent a char literal by using it’s Unicode value. For the allowed Unicode
values are 0 to
65535.
Ex:
char ch = 97;
System.out.println(ch); O/P: a
String literal
A sequence of character with in double quotes is String literal.
String s = "Java";
Variable:
Ex: int a;
Assignment:
Variable=literal;
Ex a=10;
Initialization:
Datatype variable=literal;
Ex:
Int x=10;
Note: primitive type variable stores data where as reference variable stores hashcode
A language that supports all the principles of Object Oriented programming is known as
object oriented programming language.
1.Encapsulation
2.Abstraction
3.Inheritance
4.Polymorphism
1.Class
2.Object
1.Class:
A class is a collection of variables and methods.
“A class is a way of binding the data and associated methods in a single unit”.
Any JAVA program if we want to develop then that should be developed with respect
class only i.e., without class there is no JAVA program.
Syntax:
class class_name
Datatype variable1;
Datatype variable2;
--------
---method definition
Note: class will not occupy memory where as file occupies memory.
2.Object:
In order to store the data for the data members of the class, we must create an object.
“new” is called dynamic memory allocation operator. Because it allocates the memory at
runtime.
e1 Emp object
eno
data
Hashcode
Reference variable
Types of variables:
Instance variables
Class variables.
Local variables
Instance variables:
If the value of the variable is varied from object to object such
type of variables are called instance variable
The scope of the instance variable is exactly same as the object
because instance variables are created at the time of object
creation and will be destroyed at the time of object
destruction
Instance variables should be declared inside the class and out
side the method and constructors.
Instance variables cannot be accessed from static area directly
we can access by using object or object reference
A variable which is defined as a member of a class is know as an
instance variable
Memory allocated to instance variable ever an object is created
Instance variables are stored in heap area.
Separate copy of instance variable exist for every instance
There are two ways to access instance variables
1.by using object
2.by using object reference
Use object to access instance variable if it is required only one
time
Use object reference to access instance variable if it is required
more than one time
For instance variables it is not required to perform
initialization explicitely , jvm will provide default values
The main advantage of arrays is we can represent a group of values with single name
hence readability of the code will be improved
The main limitation of arrays is they are fixed in size.i.e once we constructed an array
there is no chance of increasing or decreasing bases on our requirement
Array Declaration,Construction &Initialization
Array Declaration:
The following are the ways to declare an array.
int [] a;
int a[];
int [] a;
At the first time of declarations we are not allowed to specify the size. Violation leads to
compile time
int[ ][ ] a;
int a[][];
int [][]a;
int[] a[];
int[] []a;
Construction of Arrays
Single Dimension : Arrays are internally implemented as object hence by using new
operator we can construct an array. Compulsory at the time of construction we
should specify the size otherwise compile time error.
It is legal to have an array with size 0 there is no compile time error or run time error.
If we are specifying array size with some –ve integer we will get run time exception
saying NegativeArraySizeException.
The only allowed Data type to allow the size are byte, short,char,int. if we are using any
other datatype we will get a compile time error.
int[] a = new int[10L]; // compile time error: possible loss of precision found: long
required: int
Initialization of arrays
Once we created an array all it’s elements initialized with default values. If we are
providing any explicit initialization then default values will be overridden with
our provided values.
Example:1
int[] a = new int[3];
System.out.println(a[0]);//Output: 0
System.out.println(a);//O/P: [I@12dacd1
when ever we are trying to access an array with int index which is not in valid range
then we will get runtime exception saying “ArrayIndexOutOfBoundsException”
but there is no compile time error.
If we are trying to access an array index with the following datatype we will get
compile time error.
float, double, long, boolean.
Some times we can declare an array with out name also such
type of arrays are called anonymous arrays.
The main objective of anonymous arrays is just for temporary
usage. We can create an anonymous arrays as follows.
new int[]{10,20,30,40}
Package
package in java is an encapsulation mechanism to group related classes and interfaces
into a single
There is universally accepted convention to name the package i.e to use internet domain
name in
reverse.
a package is a collection of subpackage, classes , interface
2.to provide security to the classes and interfaces so that out side person
Compile:
javac –d . Test.java
-d means destination to place generated class files “.” means current working directory.
If the specified package structure is not already available then this command itself will
If the specified destination is not available then we will get compile time error.
class Test
System.out.println("package name");
The first non-comment statement in any java source file is package statement.
import Statement
the main objective of import statement is it acts as typing shortcut.
This type of import is highly recommended to use because it improves readability of the
code.
The code compiles fine even though we are not using import statements because we
Whenever we are using fully qualified name it is not required to use import statement.
Similarly whenever we are using import statements it is not require to use fully qualified
name.
static imports
The main objective of static imports is to import static members of a particular class
class Test
System.out.println(Math.sqrt(4));
System.out.println(Math.max(10,20));
System.out.println(Math.random());
}}
class Test
System.out.println(sqrt(4));
System.out.println(random());
System.out.println(max(10,20));
}
class modifier
when ever we are writing our own classes compulsory we should provide information about
our class to the JVM like.
The only appble modifier for the top level classes are
public classes
If a class declared as the public then we can access that class from any where.
<default> classes
If a class declared as default then we can access that class only in the current package.
<default>
abstract
abstract is the modifier appble only for classes and methods i.e we can’t use abstract for
variables.
If we don’t know about implementation still we are allowed to declare methods with
abstract
modifier.
abstract method should have only declaration but not implementation hence abstract
method
abstract never talks about implementation, if any modifier talks about implementation it is
abstract final
synchronized
native
static
strictfp
private
If we don’t want instantiation for any class such type of classes we have to declare with
abstract
If a class contain at least one abstract method then the corresponding class should be
declared as
If we are creating any child class for abstract class then compulsory we should provide
implementation for all abstract methods of parent class other wise the child class also
should be
declared as abstract
final
final is the modifier appble for classes, methods and variables.
If a method is not allowed to override in the child class then we should declare that method
as ‘final’.
for any class if we are not allow to create child class, such type of classes we have to declare
with
final method should not be overridden but we should override abstract method to provide
implementation. Hence final & abstract combination is always illegal for both method and
class
Strictfp
Java strictfp keyword ensures that you will get the same result on every platform if
you perform operations in the floating-point variable. The precision may differ
from platform to platform that is why java programming language have
provided the strictfp keyword, so that you get same result on every platform.
abstract and strictfp is a legal combination for the classes(Illegal for the methods)
member modifiers
public members
we can access public members from any where but the corresponding class must be visible.
<default> members
If a member declared as a default we can access that member only in the current package.
private members
If a member declared as private we can access that member only in the current class.
protected members
If a member declared as protected then we can access that member from any where with in
the
We can access protected members from outside package only in child class.
And we should use child class reference only. i.e parent class reference is not allowed to
access protected members from
outside package violation leads to C.E but in the current package we can access protected
members
Final Variables
For the Static and instance variables no need to perform initialization, JVM Will Provide
default
initialization.
For the local variables compulsory we should perform initialization before using.
final int i = 0;
3) Inside constructor
are not using local variable then no need of perform initialization even though it is final.
static Modifier
static is the modifier is appble for methods and variables.
we can’t declare top level classes as static but inner classes can be declares as static( static
nested class).
Instance variables(methods) can’t be accessed from static area directly, But Static members
can be accessed from any where.
overriding is not appble for static methods but seems to be overriding is possible, but it is
method hiding.
native
native is the modifier appble only for methods
The methods which are implemented in non-java are called “native methods” or “foreign
methods”.
Synchronized
It is a keyword appble only for methods and blocks. We can’t declare variables and classes
with
synchronized keyword.
If a method declared as synchronized at a time only one thread is allowed to execute on the
given
object. Hence the main advantage of synchronized keyword is we can overcome data
inconsistency
problem.
Transient is the keyword appble only for variables. i.e we can’t apply transient for
methods and classes.
While performing serialization if u don’t want to save the value of a particular variable, that
At the time of serialization, JVM ignores the value of transient variable and saves it’s default
value.
VolatileModifier
Volatile is the keyword appble only for variables. We can’t declare methods and classes with
volatile modifier.
If the value of a variable keep on changing then we have to declare that variable as volatile.
Interfaces
1) Introduction.
2) Declaring Interface.
3) Interface Methods.
4) Interface variables.
6) Marker/Tag interface.
Interface is similar to class which is collection of public static final variables (constants) and
abstract methods.
The interface is a mechanism to achieve fully abstraction in java. There can be only abstract
methods in the interface. It is used to achieve fully abstraction and multiple
inheritance in Java.
properties of Interface
It is implicitly abstract. So we no need to use the abstract keyword when declaring
an interface.
All the data members of interface are implicitly public static final.
Interface can not contain instance fields. Interface only contains public static final
variables.
public
abstract
strictfp
<default>
When ever we are implementing an interface method compulsory we should declare that
method as
extends vs implements
A class can extends only one class at a time. But an interface can extends any no of interfaces
simultaneously.
5 Which may contain either variable or Which should contains only constants.
constants.
The default access specifier of abstract There default access specifier of interface
6
class methods are default. method are public.
Inside abstract class we can take Inside interface we can not take any
8
constructor. constructor.
There are no any restriction for abstract For the interface method can not declare
11 class method modifier that method as strictfp, protected, static,
means we can use any modifiers. native, private, final, synchronized.
interface Methods
Every Interface method is by default public and abstract whether we r declaring or not.
As the interface method are by default public and abstract, we r not allowed to use the
following
modifiers.
private
protected
static
final
native
strictfp
synchronized.
Interface variables
An interface can contain variables also every interface variable is by default public static
and final
As interface variables already public static and final we r not allowed to declare with the
following
modifiers.
For the interface variables compulsory we should perform initialization at the time of
declarations
only.
Marker Interface
An interface that have no member is known as marker or tagged interface.
By implementing an interface if our objects will get some ability, Such type of interfaces are
called
“marker” or “taginterface”.
Ex:
OO CONCEPTS:
Data Hiding
The data should not go out directly i.e outside person is not allowed to access the data this is
nothing but
“Data Hiding”.
Abstraction
Hiding implementation details is nothing but abstraction. The main advantages of
abstraction are we can achieve security as we r not highlighting internal
implementation.
Enhancement will become easy. With out effecting outside person we can change our
internal
implementation.
Hiding of data is known as data abstraction. In object oriented programming language this
is implemented automatically while writing the code in the form of class and object.
It improves maintainability.
Encapsulation
is a process of wrapping of data and methods in a single unit is called encapsulation.
Encapsulation is achieved in java language by class concept.
If a class follows data hiding and abstraction such type of class is said to be ‘Encapsulated’
class.
Ex:
class Employee
{
private String name;
return name;
this.name=name;
class Demo
e.setName("Harry");
System.out.println(e.getName());
The main advantage of using of encapsulation is to secure the data from other methods, when
we make a data private then these data only use within the class, but these data not
accessible outside the class.
IS – A RelationShip
In Is-A relationship one class is obtaining the features of another class by using inheritance
concept with extends keywords.
class Parent
{}
{}
Class Test
p.methodOne();
p.methodTwo();
c.methodOne();
c.methodTwo();
P1.methodOne();
P1.methodTwo();
Memory allocated to both super class and sub class members when ever object is created to
sub class
1) Whatever the parent has by default available to the child but whatever the child has by
default not available to the parent. Hence on the child reference we can call both parent
and child class methods. But on the parent reference we can call only methods available
2) Parent class reference can be used to hold child class object but by using that reference
we can call only methods available in parent class and child specific methods we can’t
call.
Having more than one Parent class at the same level is called multiple inheritance with respect to
classes
Any class can extends only one class at a time and can’t extends more than one class
simultaneously hence java won’t provide support for multiple inheritance with respect to classes.
In java hierarchy of classes Object is class is the super class of all other classes(user defined or
predefined classes)
If our class doesn’t extends any other class then only our class is the direct child class of
object.
HAS – A RelationShip
In Has-A relationship an object of one class is created as data member in another class the
relationship between these two classes is Has-A.
Ex:
class A
===
}
}
class B
ob.show();
There is no specific keyword, but most of the cases we can implemented by using new
keyword.
Drawback:
HAS – A relationship increases dependency b/w components and creates maintainability
problems.
Method Signature
In java method signature consists of method name and arguments list( including order also)
Two methods with the same signature are not allowed in any java class, violation leads to
compile time error.
Public void calculateSalary(int basic,float da)// compile time error because both methods
are having //same signature
{
It is called as reference variable because it refers an object . it always refers current object
int x=5;
void display()
void show()
}
public static void main(String[] args) {
o.display();
class Employee {
empNo=eno;
empName=name;
Employee getDetails()//when ever method return type is class it indicated that method
will return an object of that class
}
public static void main(String args[])
Employee e3=e1.getDetails();
System.out.println(e3.empName+" "+e3.empNo);
This is key word is explicitly required to access instance variables when ever both instance
variable and local variable names are same.
By default this referece is prefixed when we access instance variables and methods.
Demo()
System.out.println("default constructor..") ;
Demo(String s)
this();
System.out.println("parameterised constructor..") ;
}
Constructors:
Constructor is a special method which has the same name as the class name .
1.default constructors
2.parameterised constructors
public Demo(String s)
System.out.println(s);
new Demo();
new Demo("hello");
note: the java compiler provides one default constructor if the class does not contain any
other constructor
class Emp
int empNo=101;
String empName="suresh";
Super keyword
It is explicitly required to access super class members when ever super class members and
sub class member names are same
class A
int x=5;
class B extends A
int x=10;
void print()
int x=15;
System.out.println(x);
System.out.println(this.x);
System.out.println(super.x);
B ob=new B();
ob.print();
Note: static method does not refer “this” and “super” key word in any way (explicitely or
implicitly)
super() : it is used to call default constructor of a super class. This statement is provided by
java compiler in every constructor
class A
A()
{
Demo
()
Super();
Block:
The group of statements between open and close flower brackes{ } is called block
One class can have any number of blocks. All the blocks are executed from top to bottom
order before constructor , when ever an object is created.
System.out.println("block1");
Demo()
System.out.println("block2");
{
new Demo();
A block is called as initialization block because it is used to initialize the instance variables
of the class
Static block:
One class can have any number of static blocks. All the blocks are executed from top to
bottom order before constructor , when ever a class is loaded
A static block is called as static initialization block because it is used to initialize the static
variables of the class Static blocks are used in real time to load the libraries
Polymorphism:
The ability to take more than one form is called polymorphism
Binding of method call statement with method definition is done at compile time only is
known as compile time polymorphism
OverLoading
Whenever same method name is exiting multiple times in the same class with different number
of parameter or different order of parameters or different types of parameters is known as
method overloading.
class Demo
System.out.println(a+b);
System.out.println(a+b+c);
}
ob.add(10,20);
2.Runtime polymorphism:
Binding of method call statement with method definition is done at runtime is known as
runtime polymorphism
Overriding
If two or more methods with the same name and with the same parameters list then it is
said to be method overriding
What ever the parent has by default available to the child class through inheritance,
If the child class is not satisfied with the parent class implementation then the child is
allowed to overwrite that parent class method to provide it’s own specific
implementation, this concept is nothing but “overriding”.
void show()
void print()
System.out.println("print method");
void show()
void display()
System.out.println("display method");
}
public static void main(String args[])
ob.show();
ob.print();
ob.display();
Overriding method resolution will take care by JVM based on runtime Object. Hence
overriding is
1.if two or more methods with the same 1. if two or more methods with the same
name and different parameters lists name and with the same parameters
then it is said to be method lists then it is said to be method
overloading overriding
4. in method overloading return type can 4. in method overriding return type must
be same be same
Java allows sub class type as a return type while overring a method this is known as co-
variant return type.
In overriding the return types must be same but this rule is appble only until 1.4 version but
from 1.5 version onwards co-variant return types also allowed. i.e the child class method
return type
need not to be same as parent class method return type it’s child class also allowed.
Ex:
Parent : String
Child : Object X
it seems that overriding is happened but it is not overriding this concept is called “method
hiding”.
All the rules of method hiding are exactly similar to overriding, except both methods
declared as
static.
In the case of method hiding method resolution will take care by compiler based on
reference
class P
System.out.println("parent method");
class C extends P
System.out.println("child method");
class Test
P p = new P();
C c = new C();
P p1 = new P();
Execution priority:
class StaticDemo
static
System.exit(0);
Typecasting
1. Implicit casting
A data type of lower size is assigned to a data type of higher size. This is done implicitly by the JVM.
The lower size is widened to higher size. This is also named as automatic type
conversion.
2. Explicit casting
A data type of higher size cannot be assigned to a data type of lower size. This is not done
implicitly by the JVM and requires explicit casting; a casting operation to be performed
by the programmer. The higher size is narrowed to lower size.
double x = 10.5;
int y = (int) x;
A b=(c) d;
Assigning an object or reference variable of subclass type( child class obeject) to super class
type is known as upcasting
A ob2=ob1;
Downcasting
Assigning an object or reference variable of superclass type to subclass type is known as
downcasting
A ob1=new B();
B ob2=(B) ob1;
String handling:
There are four string handling classes are available in java to handle strings
1.java.lang.String
2.java.lang.StringBuffer
3.java.lang.StringBuilder
4.java.util.StringTokenizer
String:-
trying to perform any changes with those changes a new String object will be created this
behavior is
1.String s1=”hello”;
First statement creates one String object in string constant pool. Where as second statement
creates two objects , one in string constant pool and the another one out side the
pool.(on heap)
Where as the String class toString() method always returns the contents of the string object
System.out.println(ob);
The object class toString method can be overridden by the programmer to change the
definition
return "welcome";
System.out.println(ob);
}
Java.lang.String
Constructors:
1.String ();
2.String (String);
Constructor-2 is used for creating a String object by taking another string as a parameter.
3.public String(char[]);
4.public String(char[], int, int);//first int indicates the starting index and second int
represent no of characters from the starting index
The above two constructors are used to convert the character array into a String
5.public String(byte[]);
The above two constructors are used to convert the byte array into a String
public class Demo{
char ch[]={'w','e','l','c','o','m','e'};
byte b[]={65,66,67,68};
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
}
Methods:
it is used to remove the extra spaces at the beginning of the string and at the end of the
string
is used for obtaining the characters from specified position to end character
position.
12. public String subString (int start, int end);
position.
class Demo
int n= s1.length();
char ch=s1.charAt(3);
byte b[]=s1.getBytes();
for(byte c:b)
System.out.println(c);
boolean comp=s1.equals(s2);
if(comp)
else
boolean comp2=s1.equalsIgnoreCase(s3);
if(comp2)
String s5=s1.concat(s4);
System.out.println(s5);
System.out.println(s6);
System.out.println(s6.trim());
char ch1[]=s2.toCharArray();
for(char temp:ch1)
System.out.println(temp);
System.out.println(s6.substring(8));
equals() method of java.lang.Object class compares the hascode of the reference variable
class Demo
System.out.println(s1.equals(s2));
System.out.println(s1==s2);
StringBuffer class:
StringBuffer API:
1. StringBuffer ()
2. StringBuffer (String)
For example:
For example:
String s=”HELLO”;
StringBuffer sb=new StringBuffer (s);
Instance methods:
This method is used for determining the capacity of StringBuffer object. Capacity of
This method is used to append string data at the end of source StringBuffer object.
5. public StringBuffer delete (int start, int end);
This method is used for removing the specified number of characters from one position to
another position.(in between characters will be deleted from starting index to the ending
index)
ex:
ex:
This method is used for replacing the string into StringBuffer object form one specified
This method is used for inserting the string data from one specified position to another
specified position.
Ex:
String StringBuffer
String class overrides the equals() method StringBuffer class does not overrides the
of Object class. equals() method of Object class.
s1.concat(s2);
System.out.println(s1);
StringBuffer sb1=new StringBuffer("Taj");
sb1.append(sb2);
System.out.println(sb1);
}}
StringBuilder
Java StringBuilder class is used to create mutable (modifiable) string. The Java
StringBuilder class is same as StringBuffer class except that it is non-
synchronized. It is available since JDK 1.5.
StringBuilder(): creates an empty string Builder with the initial capacity of 16.
StringBuilder(int length): creates an empty string Builder with the specified capacity
as length.
String tokenizer:
It allows an apption to break a string into tokens(words)
Constructor:
Public StringTokenizer(String);
Methods:
this method returns true if the next token is present other wise it returns false
it returns current token and moves the cursor to the next token
import java.util.StringTokenizer;
while (st.hasMoreTokens())
System.out.println(st.nextToken());
Wrapper classes:
To Wrap primitives into object form. So that we can handle primitives also just like
objects.
To Define several utility functions for the primitives(like converting primitive to the
string form etc.
Each of java’s 8 primitive data types has classes. And those classes are called as
Wrapper classes because they wrap the data into an object.
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
Integer class
public class Demo {
System.out.println(I);
System.out.println(I1);
Note:If the String is unable to convert into the number form then we will get run time
exception saying “NumberFormatException“.
Float class
This class contains 2 constructors which can take double, String as argument.
Character class
This class contain only one constructor which can take char as the argument i.e
character class doesn’t contain a constructor which can take string as the
argument.
Boolean class
This class contains 2 constructors one can take boolean primitive. Other can take string argument. If you
are providing boolean primitive as the argument then. The allowed values are true or false.
Case is not important if the content contains ‘TRUE’ then it is considered as true other wise it considered as
false.
}
valueOf method:
All the wrapper classes except Character class contains the valueOf() method for
converting string to corresponding Wrapper Object.
Integer I = Integer.valueOf("10");//10
Float F = Float.valueOf("10.5");//10.5
Boolean B = Boolean.valueOf("java");//false
//Character ch = Character.valueOf("10");//invalid
All Integral wrapper classes “Byte, Short, Long, Integer” Contains the following
valueOf() method.
public static wrapper valueOf(String s, int radix);
The allowed base of radix is 1 to 36.Because Numerics(10) ,Alphabets(26) finally
10+26 =36
Every Wrapper class including character class contains the following valueOf() method
to convert primitive to wrapper object form.
Integer I = Integer.valueOf(10);
Character ch = Character.valueOf('a');
Boolean B = Boolean.valueOf(true);
xxxValue() method
Every wrapper class Except character and Boolean classes contains the following
xxxValue() methods for converting wrapperObject to primitive.
Integer I = Integer.valueOf(130);
System.out.println(I.byteValue());
System.out.println(I.shortValue());
System.out.println(I.intValue());
System.out.println(I.longValue());
System.out.println(I.floatValue());
System.out.println(I.doubleValue());
Character class contain charValue() method to return char primitive for the given
character wrapper object.
System.out.println(ch1);
}
Boolean class contains booleanValue() method to return boolean primitive for the given
boolean object.
Boolean B = Boolean.valueOf("MNC");
boolean b1 = B.booleanValue();
System.out.println(b1);
Java.lang.Integer:
Constructor:
public Integer(int)
method:
int x=5;
int x=ob.intValue();
Autoboxing:
The process of converting primitive type variable to the corresponding reference type
variable is called autoboxing
int x=5;
Auto Unboxing:
The process of converting reference type variable to the corresponding primitive type
variable is called autounboxing
int x=ob;
class Demo
{
int x=10;
System.out.println(ob);
int y=ob2.intValue();
System.out.println(y);
System.out.println(ob3);
int z=ob;//autounboxing
System.out.println(z);
Exception Handling
Error:
Types of errors:
3.Logical errors
Exception is an unwanted and unexpected event that disturbs normal flow of the program is
called exception.
If we are not handling exception,the program may terminate abnormally without releasing
allocated resources.This is not a graceful termination.Being a good programming
practice compulsory we should handle exceptions for graceful termination of the
program.
Exception handling doesn’t mean repairing an exception just we have to provide alternative
path to continue the program normally.
All the method calls performed by that thread will be sorted in the corresponding run time
stack.
Once the method terminates normally, the corresponding entry from the stack will be
removed.
After completing all method calls the stack will become empty and JVM destroys that stack
before terminating the thread.
Ex:
doStuff();
doMoreStuff();
System.out.println("Exception thread..");
When ever an exception raised by the method ,then that method is responsible for the
preparation of exception object by including the following information.
Name of Exception.
Description.
Location of Exception.
After preparation of Exception Object, The method handovers that object to the JVM.
JVM will check for Exception handling code in that method, if the method doesn’t contain
any exception handling code then JVM terminates that method abnormally and
removes corresponding entry from the stack.
JVM will check for exception handling code in the caller,and if the caller method also doesn’t
contain exception handling code then JVM terminates that caller method abnormally
and removes corresponding entry from the stack.
This process will be continued until main method and if the main method also doesn’t
contain any exception handling code then JVM terminates main method abnormally.
Default exception handler prints the exception information to the console and terminates
the program abnormally.
doStuff();
doMoreStuff();
System.out.println(10/0);
/*
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionDemo.doMoreStuff(ExceptionDemo.java:12)
at ExceptionDemo.doStuff(ExceptionDemo.java:8)
at ExceptionDemo.main(ExceptionDemo.java:5)
*/
Exception Hierarchy
The Java exception hierarchy starts from Throwable class i.e for all java Exceptions and
Errors Throwable is parent class
Exception:Most of the times, Exceptions are caused by due to our program code only and
these are recoverable
Error:Most of the times errors are raised due to lack of system resources and Errors are
non-recoverable.
The exception classes which are derived from java.lang.Exception class are called
checked exceptions
All checked exceptions must be handled by the programmer explicitely by using try catch
block or throws key word other wise compile time error will occurs
The compiler checks for try and catch block or throws keyword for this kind of
exceptions.
java.io.FileInputStream:
constructor:
it opens a file for reading if the file is exist , otherwise FileNotFoundException is thrown.
import java.io.FileInputStream;
2.Unchecked exceptions:
The Exceptions which are unable to checked by the compiler are called ‘unchecked
exceptions’
Runtimeexception and it’s child classes, Error and it’s child classes are considered as
unchecked
The exception classes which are derived from java.lang.RuntimeException class are called
Unchecked exceptions
The java compiler does not check for try catch or thorows keyword for this kind of
exceptions.
java.lang.Integer:
Method()
int x=Integer.parseInt(args[0]);
}
}
A checked exception is said to be partially checked if some of it’s child classes are not checked.
Example:Exception.
//Risky code
}catch (X e){
//handling code
System.out.println("Statement1");
System.out.println(10 / 0);
System.out.println("Statement2");
}
/*
Output:
Statement1
at ExceptionDemo.main(ExceptionDemo.java:6)
*/
System.out.println("Statement1");
try {
System.out.println(10 / 0);
System.out.println("Statement2");
/*
Statement1
Exception block:5
Statement2
*/
When ever exception occurs in java a related exception class object is created by jvm and it
will be thrown to a catch block
The catch block is called as an exception handler and it handles the exception object.
{
public static void main(String[] args)
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
int z=x/y;
System.out.println(z);
The above example a programmer can also handle the exceptions explicitely to change the
default messages of the exceptions
Try
----
Catch(Exceptionclassname objectreference)
--
Try block must be associated with atleast one catch block or finally block
{
public static void main(String[] args)
try
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
int z=x/y;
System.out.println(z);
catch(ArrayIndexOutOfBoundsException ae)
catch(NumberFormatException nfe)
catch(ArithmeticException ae)
}
}
try
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
int z=x/y;
System.out.println(z);
catch(RuntimeException ae)
}
Note: in the above example catch block handles RuntimeException class object and all its
sub classes
statement 1;
statement 2;
statement 3;
catch (X e)
statement 4;
statement 5;
Case2: if there is an exception raised at statement 2 and the corresponding catch block
matched.
Case3: if an exception raised at statement 2 but the corresponding catch block is not
matched
1 Abnormal termination.
try
risky code
catch (ArithmeticException e )
//handler to A.E
catch (NullPointerException e)
catch(IOException e)
catch(Exception e)
In the case of try with multiple catch blocks the order of catch blocks is important. And it
should be from
child to parent other wise Compiler Error. Saying Exception xxx has already been caught
Example:Parent to Child
public class ExceptionDemo {
try{
System.out.println(10 / 0);
ex.printStackTrace();
e.printStackTrace();
Example:Child to Parent
public class ExceptionDemo {
System.out.println(10 / 0);
} catch(ArithmeticException e) {
System.out.println("ArithmeticException block");
} catch(Exception ex) {
System.out.println("Exception block");
import java.io.IOException;
try{
System.out.println("Hello");
ex.printStackTrace();
}
Note:IOException is fully checked exception.
try {
System.out.println("hello");
} catch(Exception e) {
System.out.println("Exception block");
Finally
It is not recommended to place cleanup code inside try statement because there is no
guarantee for
It is not recommended to maintain cleanup code with in the catch block because if there is
no exception the catch blocks won’t be executed.
We required a block to maintain cleanup code which should execute always irrespective of
whether the
exception is raised or not whether it is handled or not , such block is nothing but “finally
block”
catch (X e)
finally
Ex:
try
System.out.println("try");
catch (ArithmeticException e)
System.out.println("catch");
finally
{
System.out.println("finally");
O/P: try
finally
Normal Termination
Ex:
try
System.out.println(10/0);
catch (ArithmeticException e)
System.out.println("catch");
finally
System.out.println("finally");
O/P: catch
Finally
Normal Termination
Ex:
try
System.out.println(10/0);
catch (NullPointerException e)
System.out.println("catch");
finally
System.out.println("finally");
O/P: finally
Abnormal termination
Hence finally block should always execute irrespective of whether the exception is raised or
not raised or
final: It is the modifier appble for classes methods and variables. For final classes we can’t
create
final methods can’t be override in child classes for final variables reassignments is not
possible
finally: It is a block associated with try catch the main objective of finally block is to
maintain
finalize: It is a method should be executed by the “Garbage Collector” just before destroying
an
if(a>0)
System.out.println(a*a*a);
else
try
int x=Integer.parseInt(args[0]);
ob.cube(x);
}
catch(NegetiveNumberException e)
System.out.println(e);
if(a>0)
System.out.println(a*a*a);
else
throw new NegetiveNumberException();
int x=Integer.parseInt(args[0]);
ob.cube(x);
throw keyword
By using throw we can hand – over exception object to the JVM.
case:1
class Test{
Compiletime Error:No exception of type Test can be thrown; an exception type must be a
subclass of Throwable
case:2
Case:3
public class ExceptionDemo {
throw e;
Here Explicitly we created a object to the ArithmeticException class and that object was
thrown by thow to the JVM.
Case 4:
public class ExceptionDemo {
static ArithmeticException e ;
throw e;
Output:
Exception in thread “main” java.lang.NullPointerException
Here we didn’t create Object to the AritmeticException class just we created a reference,
so reference variable is not pointing to any object and we thrown only reference
variable that’s why only it shows NullPointerException.
After throw statement we are not allowed to write any statement directly other wise we will
get compile time error saying that un-reachable statement
Throws keyword:
In our program,If there is any chance of raising checked exception then compulsory we
should handle that checked exception either by using try, catch or we have to
delegate that responsibility to the caller using throws keyword other wise C.E
ex:
class Demo
Thread.sleep(1000);
We can resolve this problem either by using try catch or by using throws keyword as follows
class Demo
try
Thread.sleep(1000);
catch (InterruptedException e)
System.out.println(e);
}
class Demo
Thread.sleep(1000);
Hence the main objective of throws keyword is to delegate the responsibilities of exception
handling to the
In the case of unchecked exceptions it is not required to use the throws keyword
StackTace.
Ex:-
Multithreading
Multitasking Executing several tasks simultaneously is called ‘Multitasking’,
There are 2
types of multitasking.
Ex:
While writing java program in the editor we can run MP3 player. At the same time
we
can download a file from the net. All these tasks are executing simultaneously and
same program is called Thread based Multitasking. This type of multitasking is best
suitable
at programmatic level.
Java provides in built support for thread based multitasking by providing rich
library (Thread,
…etc.
{
public void run()
System.out.println("Child Thread");
class MultiThreadDemo
t.start();
System.out.println("Main Thread");
Case1 :
Thread Shedular:
If multiple threads are there then which thread will get chance first for execution
will be
decided by “Thread Scheduler”. Thread Scheduler is the part of JVM. The behavior
of thread
scheduler is vendor dependent and hence we can’t expect exact O/P for the above
program.
Note: when ever the situation comes to multithreading the guarantee in behavior is
very less we can tell possible output but not exact output
Case2:
In the case of t.start() a new thread will be created and which is responsible for the
execution
of run( ) method. But in the case of t.run() no new thread will be created and run()
method will be executed just like a normal method by the main thread.
Hence in the above program if we are replacing t.start() with t.run() then the O/P is
Case3:
After Creating thread object compulsory we should perform registration with the
thread
scheduler. This will take care by start( ) of Thread class, So that the programmers
has to
concentrate on only job. With out executing Thread class start() method there is no
chance of
start()
Case4:
Then the thread class run method will be executed which has empty
implementation.
Ex:
class ThreadDemo
{
t.start();
O/P:- no output
Note: it is highly recommended to override run method to define the job of a thread
Case5:
Ex:
System.out.println("start() method");
System.out.println("run method");
class ThreadDemo
{
public static void main(String arg[])
t.start();
In this case start() method will be executed just like a normal method.
Once we crated a thread object then it is said to be in new state or born state
If we call start( ) method then the thread will be entered into ready or runnable
state
If threadshedular allocates cpu then the thread will entered into running state
If run( ) method completes its execution then the thread will entered into deadstate
Note:- we can’t stop a running Thread explicitly. But until 1.2 version we can
achieve this by using
deprecated.
After starting a thread we are not allowed to restart the same thread once again,
violation leads to Runtime Error saying “IllegalThreadStateException”.
MyThread t = new MyThread();
t.start();
-----
-----
Within the run method if we call super.start( ) method we get the same runtime
error “IllegalThreadStateException”.
for(int i = 0;i<=10;i++)
System.out.println("Child Thread");
class ThreadDemo
t.start();
for(int i = 0;i<=10;i++)
System.out.println("Main Thread");
Ex:
Case1:
t1.start();
A new thread will be started and executes Thread class run( ) method(Which is
having empty
implementation).
Case2:
t1.run();
No new thread will be created and Thread class run() method will be executed just
like a
Case3:
t2.start();
A new thread will be created and responsible for execution of MyRunnable run( )
method.
Case4:
t2.run();
No new thread will be created and MyRunnable run( ) method will be executed just
like a
Case5:
r.run();
No new thread will be created and MyRunnable run( ) method will be executed just
like a
Case6:
r.start();
every thread in java has some name it may be provided by programmer or a default
name generated by jvm
Thread class defines the following methods to set and get the name of a Thread.
Ex:
class Test
System.out.println(Thread.currentThread().getName());
Thread.currentThread().setName("New Thread");
System.out.println(Thread.currentThread().getName());
Note: we can get current executing thread reference by using the following method
of thread class
Thread Priorities:
Every Thread in java having some priority. The range of valid thread priorities is
(1-10) (1 is least & 10 is Highest). Thread class defines the following
constant for representing some standard priorities.
Thread.MIN_PRIORITY 1
Thread.NORM_PRIORITY 5
Thread.MAX_PRIORITY 10
Thread scheduler use these priorities while allocating C.P.U. The Thread which is
having highest priority
will get chance first for execution. If two threads having the same priority then
which thread will get chance first for execution is decided by Thread
Scheduler, which is vendor dependent i.e we can’t expect exactly.
The default priority for the main thread only the 5, but for all the remaining threads
the priority will be inherit from parent i.e what ever the parent has the same
priority the child thread also will get.
Thread class contains the following methods to set and get priorities of thread.
Ex:
System.out.println("Child Thread");
class ThreadPriorityDemo
{
public static void main(String arg[])
System.out.println(t.getPriority());
t.setPriority(10);//------------'(1)
t.start();
for(int i =0;i<10;i++)
System.out.println("Main Thread");
If we are commenting line 1 then both main and child threads having the same
priority(5) and hence we cant expect exact execution order and exact output
If we are not commenting line 1 then main has the priority 5 and child thread have
the priority(10) and hence child thread will be executed first and then main
thread. In this case the output is child thread 10 times and mainthread 10
times will be executed
Note: Some Operating Systems may not provide support for thread priorities.
1) yield()
2) join()
3) sleep()
yield()
The thread which is called yield() method temporarily pause the execution to give
the chance for remaining threads of same priority.
Then the same thread will get the chance immediately for the execution.
the thread which is yielded, when it will get chance once again for execution is
decided by ThreadSchedular and we can’t expect exactly.
Ex:
Thread.yield();//-----------------------(1)
System.out.println("Child Thread");
}
}
class YieldDemo
t.start();
for(int i =0;i<10;i++)
System.out.println("Main Thread");
If we are commenting line 1 then both threads will be executed simultaneously and
we cant expect exact execution order
If we are not commenting line 1 then the chance of completing main thread first is
high because child thread always calls yield() method.
. As the yield method is native method some Operating system may not provide the
support for this.
join()
If a thread wants to wait until some other thread completion then we should go for
join method.
Ex:
If a thread t1 executes t2.join(), then t1 will be entered into waiting state until t2
completion.
Ex:
System.out.println("Child Thread");
try
Thread.sleep(2000);
catch(InterruptedException e)
e.printStackTrace();
class ThreadJoinDemo
{
public static void main(String arg[])throws InterruptedException
t.start();
t.join();//--------------------(1)
for(int i =0;i<10;i++)
System.out.println("Main Thread");
If we are commenting line 1 then both threads will be executed simultaneously and
we cant expect exact execution order and hence we cant expect exact o/p.
If we are not commenting line 1 then main thread will wait until completing child
thread hence in this case the o/p is expected.
Sleep ( ):
If a thread has to wait some predefined amount of time with out execution then we
should go for sleep() method.
If a thread don’t want to perform any operation for a particular amount of time
(just pausing) then we should go for sleep()
Ex:
class Test
System.out.println("systems");
Thread.sleep(5000);
System.out.println("domain");
Thread.sleep(5000);
System.out.println("banashankari");
interrupting a thread
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling
the interrupt() method on the thread, breaks out the sleeping or waiting
state throwing InterruptedException. If the thread is not in the sleeping or
waiting state, calling the interrupt() method performs normal behaviour and
doesn't interrupt the thread.
when ever we are calling interrupt() the target thread may not be effected
immediately. At the time of calling interrupt if the target thread is not in
sleeping or in waiting state interrupt call will wait until target thread
entered into sleeping or waiting state the interrupt call will impact the target
thread..
Ex:
class MyThread extends Thread
try
for(int i=0;i<100;i++)
System.out.println("lazy thread");
Thread.sleep(5000);
catch(InterruptedException e)
class InterruptDemo
t.start();
t.interrupt();//------------(1)
If we are commenting line 1 then main thread wont interrupt child thread hence
both threads will be executed until completion.
If we are not commenting line 1 then main thread interrupts the child thread rises
InterruptedException.
Synchronization
‘synchronized’ is the keyword appble for the methods and blocks. We can’t apply
this keyword for variables and classes.
If a thread want to execute any synchronized method on the object first it should
require the lock of that object. Once a thread got the lock then it is allowed to
execute any synchronized method on that object.
Once synchronized method completes then automatically the lock will be released
While a thread executing a synchronized method on the object, then the remaining
threads are not allowed to execute any synchronized method on the same
object. But the remaining threads are allowed to execute any non-
synchronized method on the same object.
Every object in java has unique lock but a thread can acquire more than one lock at
a time.
Ex:
class Display
for(int i =0;i<10;i++)
System.out.print("Hai.......!");
try
Thread.sleep(2000);
catch (InterruptedException e)
System.out.println(name);
Display d;
String name;
this.d = d;
this.name = name;
d.wish(name);
class SynchronizedDemo
t1.start();
t2.start();
If we are not declaring wish method as “synchronized” we will get irregular o/p
because both threads will execute simultaneously. If we are declaring wish
method as synchronized we will get regular o/p because at a time only one
thread is allowed to execute wish method.
t1.start();
t2.start();
Even though wish method is synchronized we will get irregular o/p only because
both threads are operating on different objects.
Class level lock: If a thread want to execute any static synchronized method then
compulsory that thread should require class level lock.
While a thread executing any static synchronised method then the remaining
threads are not allowed to execute any static synchronized method of the
same class simultaneously.
But the remaining threads are allowed to execute any non-synchronized static
methods, synchronized – instance method, non – synchronized instance
method simultaneously.
Declare static synchronized in display method and try the above example we will
get regular o/p because there is class level lock.
Synchronized Blocks
It is not recommended to declare entire method as synchronized if very few lines of
code requires the synchronization concept. Such a few lines of code we can
declare in a block rather than declaring entire method as a synchronized
method
Syntax:
synchronized(b)
//critical section.
To get the lock for the current object we can define synchronized block as follows
synchronized(this)
//critical section.
synchronized(Display.class)
we can define synchronized block either for object references or for class
references But not for primitives violation leads to Compile time error.
int i =10;
synchronized(i)
//------
found : int.
required : reference.
‘synchronized statement’.
These methods are available in object class but not in thread class. Because threads
are calling these methods on any object.
We should call these methods only from synchronized area other wise we get
runtime exception saying
IllegalMonitorStateException.
After giving the notification also the thread releases the lock but may not be
immediately.
wait(): It is a method on Object class. It makes the current thread into the "Not
Runnable" state. Wait is called on a object, not a thread. Before calling wait()
method, the object should be synchronized, means the object should be
inside synchronized block. The call to wait() releases the acquired lock.
Ex:
class ThreadA
b.start();
synchronized(b)
b.wait();
System.out.println(b.total);
}
class ThreadB extends Thread
int total = 0;
synchronized(this)
total = total + i;
this.notify();
Dead Lock
If two threads are waiting for each other forever, then the threads are said to be in
“deadlock”.
Ex:
Banker’s Algorithm.
Ex:
class A
Thread.sleep(600);
catch (InterruptedException e)
b.last();
class B
try
Thread.sleep(600);
catch (InterruptedException e)
A a = new A();
B b = new B();
DeadLock()
t.start();
b.bar(a);
a.foo(b);
new DeadLock();
DaemonThread
The threads which hare running in the background to provide support for user
defined threads are called
“Daemon Thread”. Usually daemon thread are running with low priority but based
on our requirement we
We can check whether the given thread is daemon or not by using the following
thread class thread.
the daemon nature of a thread is inheriting from the parent. i.e if the parent is
daemon then the child is also
daemon and if the parent is non – daemon then the child is also non – daemon.
After starting a thread we are not allowed to change the daemon nature violation
leads to runtime exception
saying IllegalThreadStateException.
Ex:
class Test
System.out.println(Thread.currentThread().isDaemon());
System.out.println(t.isDaemon());
t.setDaemon(true);
System.out.println(t.isDaemon());
t.start();
//t.setDaemon(false); - 1
}
We can’t change the daemon nature of main thread because it has started already
before main() method only.
All the daemon threads will be terminated automatically when ever last non –
daemon thread terminates.
Ex:
If we are commenting line 1, then both child and main threads are non – Daemon,
hence they will execute until their completion.
If we are not commenting line 1, then the child thread is daemon and hence it will
terminate automatically
1) Arrays are fixed in size i.e once we created an array there is no chance of
increasing or
Ex:-
s[2] = "raju"; X
o[2] = "raju";
3) For the Arrays there is no underlying Data Structure i.e for every requirement
we have to code explicitly and there is no default ready made support(like
sorting, searching).
To resolve the above problems of arrays, Sun people has introduced ‘collections
concept’
Collections are grow able in nature i.e based on requirement we can increase or
decrease the size.
We can represent all the elements in some sorting order. We can prevent duplicate
object insertion by default.
elements elements.
6) Collection can hold only Objects but 6) Arrays can hold both Objects and
not primitives.
primitives.
This interface can be used for representing a group of objects as single entity.
This interface defines the most common general methods which can be appble for
any collection object. There is no concrete class which implements collection
interface directly.
2) List interface :
This can be used for representing a group of individual objects as a single entity
where insertion order is preserved and duplicate objects allowed. This is
child interface of collection.
duplicate objects are not allowed and insertion operation is not preserved.
hashset and linkedHashSet are the classes which implements Set interface directly.
4) SortedSet interface :
This can be used for representing a group of individual and unique objects.
Where all the objects are inserted in some sorting order. It is the child interface of
Set interface
All the above interfaces(collection, List, Set, SortedSet, Queue) can be used for
representing a group of individual objects.
If u want to represent a group of objects as key value pair than we can’t use above
interfaces.
6) Map:
This can be used for representing a group of objects as key value pairs. Both key
and value are
objects only.
StudentName StudentRollNo
phoneNumber contactdetails
word meaning
IP Address Domain-name
7) SortedMap:
This can be used for representing a group of objects as key value pairs where all the
entries are
1) vector.
2) stack
4) properties
Collection
This can be used for representing a group of individual objects as a single entity.
This interface defines the most common general methods. Which can be
appble for any collection implemented class object.
2) boolean addAll(Collection c)
4) boolean removeAll(Collection c)
5) boolean retainAll(Collection c)
6) void clear()
9) boolean isEmpty()
List interface
This can be used for representing a group of individual objects where insertion
order is preserved and duplicate objects are allowed.
By means of index we can preserve insertion order and we can differentiate
duplicate objects.
3) boolean addAll(Collection c)
Old object. It replaces with the existing objected located at specified index with the
new
ArrayList()
The underlying data Structure for ArrayList() is resizable Array or “Growable
Array”.
When ever ArrayList reaches its max capacity a new ArrayList Object will be
created with new
capacity.
Ex:
import java.util.*;
class ArrayListDemo
a.add("A");
a.add(new Integer(10));
a.add("A");
a.add(null);
System.out.println(a);
a.remove(2);
System.out.println(a);
a.add(2,"M");
a.add("N");
System.out.println(a);
Usually the collection objects can be used for data transport purpose and hence
every collection
LinkedList()
The underlying Data Structure for linked list is doubly linked list.Duplicate objects
are allowed.
LinkedList class usually used for implementing stacks and Queues to provide
support for this
3. Object removeFirst()
4. Object removeLast()
5. Object getFirst()
6. Object getLast()
Constructors
Ex:
import java.util.*;
class LinkedListDemo
x --------------------------------
insertion
shifting
LinkedList l = newLinkedList();
l.add("raju");
l.add(new Integer(10));
l.add(null);
l.add("raju");
l.set(0, "chinna");
l.add(0, "Kiran");
l.addFirst("AAAA");
l.addLast("ZZZZ");
System.out.println(l);
l1.add(10);
l1.add(20);
l1.add(30);
System.out.println("l1--->"+l1);
l2.add(1,5);
l2.add(3,5);
l2.add(5,15);
System.out.println("l2--->"+l2);
System.out.println("l3--->"+l3);
VectorClass
The underlying Data structure for the vector is resizable array or growable array.
Vector ArrayList
Similarly we can find synchronized versions of set and Map objects by using the
collections class
method.
Vector methods
add(Object obj)
addElement(Object obj)
remove(Object obj)
removeElement(Object obj)
remove(int index)
removeElementAt(int index)
clear()
removeAllElements()
Object firstElement();
Object lastElement();
OtherMethods
int size();
int capacity();
Enumaration elements();
constructors
Creates an empty vector object with default initial capacity 10, when ever vector
reaches it’s max capacity a new vector object will be created with.
Ex:
import java.util.*;
class VectorDemo
System.out.println(v.capacity());
v.addElement(i);
System.out.println(v.capacity());
v.addElement("Aa");
System.out.println(v.capacity());
System.out.println(v);
Stack
It is the child class of Vector contains only one constructor.
Object pop();
Object peek();
If the specified object is available it returns its offset from top of the stack
boolean empty();
Ex:
import java.util.*;
class StackDemo
s.push("A");
s.push("B");
s.push("C");
System.out.println(s);
System.out.println(s.search("A"));
System.out.println(s.search("Z"));
From the collection object to retrieve objects we can use the following 3 cursors.
1. Enumeration
2. Iterator
3. ListIterator
Enumeration
This interface has introduced in 1.0 version it contains the following 2 methods.
boolean hasMoreElements();
Object nextElement();
Ex:
import java.util.*;
class EnumaretionDemo
v.addElement(i);
System.out.println(v);
Enumeration e = v.elements();
while (e.hasMoreElements())
Integer i = (Integer)e.nextElement();
if((i%2) == 0)
System.out.println(i);
}
System.out.println(v);
Limitations of Enumeration
2. While iterating the elements by using enumeration we can perform only read
operation and we can’t perform any modify/removal operations.
Iterator
o Introduced in 1.2 version.
o We can use Iterator Object for any collection implemented class i.e it is universal
cursor.
boolean hasNext();
Object next();
void remove();
Ex:
import java.util.*;
class IteratorDemo
al.add(i);
}
System.out.println(al);
while (itr.hasNext())
Integer i = (Integer)itr.next();
if((i%2) == 0)
System.out.println(i);
else
itr.remove();
System.out.println(al);
Note:-
1. Enumeration and Iterator are single directional cursors. They can always move
to words forward direction only.
2. By using Iterator we can perform read and remove operations. And we can’t
perform any replace or addition of new objects
ListIterator
1.It has introduced in 1.2 version and it is child interface of Iterator.
4.While Iterating we can perform replace and add operation in addition to read and
remove this
interface defines the following 9 methods.
1. boolean hasNext();
2. boolean hasPrevious();
3. Object next();
4. Object previous();
5. int nextIndex();
6. int previousIndex();
7. void remove();
8. void set(Object)
import java.util.*;
class ListIteratorDemo
l.add("balakrishna");
l.add("chiru");
l.add("venky");
l.add("nag");
System.out.println(l);
while (ltr.hasNext())
String s = (String)ltr.next();
if(s.equals("nag"))
{
ltr.add("chaitanya");
System.out.println(l);
The most powerful cursor is listIterator. But it’s main limitation is it is appble only
for list
SetInterface
This can be used for representing a group of Individual objects where insertion
order is not preserved and
This interface doesn’t contain any new method and we have to use only collection
Interface methods.
HashSet( class)
The underlying Data Structure for HashSet is Hashtable.
Insertion order is not preserved and it is based on hash code of the Object.
This method simply returns false. If the object is already existing in the set.
Constructors
Here fillratio is 0 or 1.
Ex:
import java.util.*;
class HashSetDemo
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(new Integer(10));
System.out.println(h.add("Z"));
System.out.println(h);
LinkedHashSet (class)
It is the child class of HashSet. It is Exactly similar to HashSet. Except the following
differences.
HashSet LinkedHashSet
Note:- For implementing caching apption the best suitable Data structure is
LinkedHashSet and LinkedHashMap where duplicate objects are not allowed
and insertion order Must be preserved.
SortedSet
This can be used for representing a group of individual objects where duplicate
objects are not
allowed.
Insertion order is not preserved but all the elements are inserted according to
some sorting order
of elements. The sorting order may be default natural sorting order or customized
sorting order.
1. Object first()
2. Object last()
Returns the SortedSet contains the elements which are less than the specified
object obj.
Returns the SortedSet whose elements are greater than or equal to the specified
object obj
Returns the SortedSet whose elements are >= obj1 but < Obj2
6. Comparator comparator();
first() 100
last()160
headSet(140) {100,120,130}
tailSet(140) {140,150,160}
subset(130,150) {130,140}
comparator() null
TreeSet
The underlying Data structure for the TreeSet is Balanced tree.
Duplicate objects are not allowed. If we are trying to insert duplicate object we
won’t get any
compile time error or Run time error, add method simply returns false.
Insertion order is not preserved but all the elements are inserted according to
some sorting order.
Heterogeneous objects are not allowed, violation leads to Run time error saying
class cast
Exception
Constructors
Creates an empty TreeSet Object where the sorting order is default natural sorting
order.
object.
Ex:
import java.util.*;
class TreeSetDemo
t.add("A");
t.add("B");
t.add("Z");
t.add("L");
t.add("A");// ? false.
System.out.println(t);
null Acceptance
For the empty TreeSet as the first element null insertion is possible. But after
inserting null if we are trying to insert any other element we will get
NullPointerException.
If the TreeSet already contains some elements if we are trying to insert null we will
get
NullPointerException.
Ex:
import java.util.*;
class TreeSetDemo
t.add(new StringBuffer("A"));
t.add(new StringBuffer("B"));
t.add(new StringBuffer("T"));
t.add(new StringBuffer("Z"));
System.out.println(t);
An object is said to be comparable(if and only if) the corresponding class has to
implement
comparable interface.
All wrapper classes and String class already implemented comparable interface.
But the String buffer doesn’t implement comparable interface. Hence in the
above program we got class cast exception.
Queue interface
Diagram:
2) Usually Queue follows first in first out order but based on our requirement we can
4) LinkedList based implementation of Queue always follows first in first out order.
2) Object poll() ;
To remove and return head element of the Queue, if Queue is empty then we will get
null.
3) Object remove();
To remove and return head element of the Queue. If Queue is empty then this method
4) Object peek();
To return head element of the Queue without removal, if Queue is empty this method
returns null.
5) Object element();
It returns head element of the Queue and if Queue is empty then it will raise Runtime
2) The priority order can be either default natural sorting order (or) customized sorting
3) If we are depending on default natural sorting order then the objects must be
4) If we are defining our own customized sorting order by Comparator then the objects
6) Insertion order is not preserved but all objects will be inserted according to some
priority.
7) Null is not allowed even as the 1st element for empty PriorityQueue.
Constructors:
Creates an empty PriorityQueue with default initial capacity 11 and default natural
sorting order.
Example 1:
import java.util.*;
class PriorityQueueDemo
//System.out.println(q.peek());//null
//System.out.println(q.element());//NoSuchElementException
for(int i=0;i<=10;i++)
q.offer(i);
System.out.println(q);//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
System.out.println(q.poll());//0
System.out.println(q);//[1, 3, 2, 7, 4, 5, 6, 10, 8, 9]
Note: Some platforms may not provide proper supports for PriorityQueue [windowsXP].
Example 2:
import java.util.*;
class PriorityQueueDemo
q.offer("A");
q.offer("Z");
q.offer("L");
q.offer("B");
System.out.println(q);//[Z, B, L, A]
}
class MyComparator implements Comparator
String s1=(String)obj1;
String s2=obj2.toString();
return s2.compareTo(s1);
Comparable interface:
Comparable interface present in java.lang package and contains only one method
compareTo() method.
Example:
obj1.compareTo(obj2);
Diagram:
Example 3:
class Test
System.out.println("A".compareTo("Z"));//-25
System.out.println("Z".compareTo("K"));//15
System.out.println("A".compareTo("A"));//0
//System.out.println("A".compareTo(new Integer(10)));//Test.java:8:
//System.out.println("A".compareTo(null));//NullPointerException
If we are depending on default natural sorting order then internally JVM will use
If we are not satisfying with default natural sorting order (or) if default natural sorting
order is not available then we can define our own customized sorting by Comparator
object.
Comparator interface present in java.util package this interface defines the following 2
methods.
Diagram:
Requirement: Write a program to insert integer objects into the TreeSet where the sorting
Program:
import java.util.*;
class Test
t.add(10);
t.add(0);
t.add(15);
t.add(5);
t.add(20);
Integer i1=(Integer)obj1;
Integer i2=(Integer)obj2;
if(i1<i2)
return +1;
else if(i1>i2)
return -100;
else return 0;
At line “1” if we are not passing Comparator object then JVM will always calls
At line “1” if we are passing Comparator object then JVM calls compare() method of
Diagram:
Various alternative implementations of compare() method:
Integer i1=(Integer)obj1;
Integer i2=(Integer)obj2;
Requirement: Write a program to insert String objects into the TreeSet where the sorting
order
Program:
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
t.add("Roja");
t.add("ShobaRani");
t.add("RajaKumari");
t.add("GangaBhavani");
t.add("Ramulamma");
GangaBhavani]
String s1=obj1.toString();
String s2=(String)obj2;
//return s2.compareTo(s1);
return -s1.compareTo(s2);
Requirement: Write a program to insert StringBuffer objects into the TreeSet where the
sorting
Program:
import java.util.*;
class TreeSetDemo
t.add(new StringBuffer("A"));
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("K"));
t.add(new StringBuffer("L"));
System.out.println(t);// [A, K, L, Z]
String s1=obj1.toString();
String s2=obj2.toString();
return s1.compareTo(s2);
Note: Whenever we are defining our own customized sorting by Comparator then the
objects
Example: StringBuffer
Requirement: Write a program to insert String and StringBuffer objects into the TreeSet
where
the sorting order is increasing length order. If 2 objects having the same length then
consider
import java.util.*;
class TreeSetDemo
t.add("A");
t.add(new StringBuffer("ABC"));
t.add(new StringBuffer("AA"));
t.add("xx");
t.add("ABCD");
t.add("A");
String s1=obj1.toString();
String s2=obj2.toString();
int l1=s1.length();
int l2=s2.length();
if(l1<l2)
return -1;
else if(l1>l2)
return 1;
else
return s1.compareTo(s2);
Note: If we are depending on default natural sorting order then the objects should be
our own sorting by Comparator then objects “need not be homogeneous and comparable”.
Comparable vs Comparator:
For predefined Comparable classes default natural sorting order is already available if
we are not satisfied with default natural sorting order then we can define our own
For predefined non Comparable classes [like StringBuffer] default natural sorting order
is not available we can define our own sorting order by using Comparator object.
For our own classes [like Customer, Student, and Employee] we can define default
natural sorting order by using Comparable interface. The person who is using our class,
if he is not satisfied with default natural sorting order then he can define his own sorting
Example:
import java.util.*;
String name;
int eid;
this.name=name;
this.eid=eid;
return name+"----"+eid;
int eid1=this.eid;
int eid2=((Employee)o).eid;
if(eid1<eid2)
return -1;
else if(eid>eid2)
return 1;
else return 0;
class CompComp
t1.add(e2);
t1.add(e3);
t1.add(e4);
t1.add(e5);
t2.add(e1);
t2.add(e2);
t2.add(e3);
t2.add(e4);
t2.add(e5);
Employee e1=(Employee)obj1;
Employee e2=(Employee)obj2;
String s1=e1.name;
String s2=e2.name;
return s1.compareTo(s2);
Equals() method.
interface.
Map Interface
If we want represent a group of objects as a key value pairs then we should go for
Map interface.Both key and and value are objects only.
Collection meant for group of individual objects and Map is meant for group of key-
value pairs
HashMap Hashtable
null is allowed for both key and null is not allowed for both
value key and value
Constructors of HashMap
Construcor Description
HashMap hashMap=new
HashMap(int
initialCapacity)
HashMap hashMap=new
HashMap(int
initialCapacity,float
fillratio)
HashMap hashMap=new
HashMap(Map map)
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
HashMap LinkedHashMap
IdentityHashMap
In the case of HashMap to identify duplicate keys JVM
always use .equals() method of string class(compares
the content).
But in the case of IdentityHashMap instead of .equals()
method JVM will use == operator (compares the hash
code or memory reference) to identify duplicate keys.
import java.util.HashMap;
import java.util.IdentityHashMap;
WeakHashMap
In the case of HashMap an object is not eligible for garbage
collector even though it doesn’t contain any external
references if it is associated with HashMap.
In the case of WeakHashMap an object is eligible for garbage
collector if it doesn’t contain any external references
even though it is associate with WeakHashMap.
That is HashMap dominates the garbage collector where as
garbage collector dominates the WeakHashMap.
import java.util.HashMap;
import java.util.WeakHashMap;
//WeakHashMap implementation.
WeakHashMap weakHashMap=new WeakHashMap();
Demo d1=new Demo();
weakHashMap.put(d1, "JAVA");
System.out.println(weakHashMap);
d1=null;
System.gc();
Thread.sleep(5000);
System.out.println(weakHashMap);
}
class Demo{
public String toString(){
return "demo";
}
public void finalize(){
System.out.println("Demo::finalize");
}
}
SortedMap
If we want arrange all entries according to some
sorting order of keys then we should go for
‘SortedMap’.
SortedMap interface defines the following 6 specific
methods.
Object firstKey()
Object lastKey()
SortedMap headMap(Object key)
SortedMap tailMap(Object key)
SortedMap subMap(Object key1,Object key2)
Comparator comparator()
TreeMap
The underlying data structure is RED-BLACK tree.
Duplicate keys are not allowed values can be duplicated.
Insertion order is not preserved and it is based on sorting
order of keys
If we are depending on natural sorting order,The keys
should be homogenous and comparable other wise we
will get ClassCastException.
If we are defining out own sorting by Comparator then keys
can be heterogeneous need not be Comparable.
There are no restrictions on values these can be
heterogeneous.
null insertion in TreeMap
If we are trying to insert null key in non empty TreeMap we
will get NullPointerException.
For the empty TreeMap as the first entry with null key is
allowed.But after inserting that entry if we are trying to
insert any other entry we will
get NullPointerException.
For the values no restrictions ,We can use any number of
nulls.
Constructors:
Constructor Description
TreeMap map=new
TreeMap(Map)
TreeMap map=new
TreeMap(SortedMap)
import java.util.TreeMap;
import java.util.Comparator;
import java.util.TreeMap;
Java Streams
Java I/O (Input and Output) is used to process the input and produce the output
based on the input.
Java uses the concept of stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
1.in
2.out
3.err
Note: the above all streams are defined as a static members in java.lang,System
class
Java.lang.System
Object references:
File
A java file object represent just name of the file/directory.
If ‘abc.txt’ is already available then ‘f’ will represent that physical file.
If it is not already available, It won’t create any new file and ‘f’ simply represents
the name of the file.
Ex:
import java.io.*;
class test
f.createNewFile();
System.out.println(f.exists()); true
I Run:
false
true
II Run:
true
true
Ex:
System.out.println(f.exists());
f.mkdir();
System.out.println(f.exists());
I Run:
false
true
II Run:
true
true
Here name may be file or directory name. Creates a java file object that represents a
file or directory name.
Creates a java file object that represents file or directory name present in specified
subdirectory.
import java.io.*;
class Test
f1.mkdir();
System.out.println(f.exists());
f.createNewFile();
System.out.println(f.exists());
2) boolean createNewFile():
returns ture if it creates a new file, if the required file is already available then
3) booelan mkdir()
4) boolean isFile():
5) boolean isDirectory():
6) String [] list():
returns the names of files and directories present in the directories represented
If the java file object represents a file instead of directory this method returns
null.
7) Boolean delete():
8.long length();
write a program to create a file named with ‘xyz.txt’ in the current working
directory.
f.createNewFile();
f.mkdir();
F1.createNewFile();
Write a program to list the names of files and directories in ‘jdk’ directory.
File f = new File(“jdk”);
String [] s = f.list();
For(String s1: s)
System.out.println(s1);
FileWriter
This class can be used for writing character data to the file.
Constructors
1) FileWriter fw = new FileWriter(String fname)
The above 2 constructors creates a file object to write character data to the file.
If the file already contains some data it will overwrite with the new data.
Instead of overriding if u have to perform append then we have to use the following
constructors.
If the underlying physical file is not already available then the above constructors
will create the required file also.
Ex:-
class test
System.out.println(f.exists());
System.out.println(f.exists());
fw.write("run\nsoftware\n");
fw.write(‘\n’);
fw.write(ch1);
fw.flush();
fw.close();
FileReader
This class can be used for reading character data from the file.
Constructors
1) FileReader fr = new FileReader(String name);
for reading next character from the file and returns it Unicode character value. If
there is no next character this method returns -1
2) int read(char[] ch): it attempts to read no of characters from file into array and
returns the no of characters which are read from the file.
3) void close():
to close FileReader
Ex:
class test
System.out.println(fr.read());
System.out.println(ch2.length);
fr.read(ch2);
System.out.print(ch1);
System.out.println(“************”);
Int i=fr1.read();
While(i!=-1)
System.out.println((char)i);
I=fr1.read();
}
}
BufferedWriter
This can be used for writing character data to the file.
Constructors
1) BufferedWriter bw = new BufferedWriter(writer w)
FileWriter(“abc.txt”)));
4) void newLine()
6) void close()
Ex:-
class test
System.out.println(f.exists());
bw.write(97);
bw.newLine();
bw.write(ch1);
bw.newLine();
bw.write("raju");
bw.newLine();
bw.write("software");
bw.flush();
bw.close();
Note: when ever we are closing BufferedWriter automatically under lying writers
will be closed
BufferedReader
The advantage of BufferedReader over FileReader is we can read the data line by
line instead of reading character by character. This approach improves the
performance of the system by reducing the no of read operations
Constructors
1) BufferedReader br = new BufferedReader(Reader r)
1) int read()
3) String readLine();
Reads the next line present in the file. If there is no nextline this method returns
null.
4) void close()
Ex:
class test
String s = br.readLine();
while(s != null)
System.out.println(s);
s = br.readLine();
}
Note:- When ever we r closing BufferedReader ,automatically underlying
FileReader object will be
closed.
types of streams:
===============
1.Byte streams
2.Character streams
1.Byte streams:
2.Character streams:
object
InputStream OutputStream
The hierarchy of character stream classes:
object
Reader Writer
BufferedReader InputStreamReader
BufferedWriter Printwriter
OutputStreamWriter
FileReader
FileWriter
java.io.InputStream
================
methods:
//program to demonstrate
import java.io.*
class Demo
try
System.in.read(b);
String s2=s1.trim();
int x=Integer.parseInt(s2);
System.out.println(x);
catch(IOException ie)
System.out.println(ie);
}
}
FileInputStream
FileInputStream class possesses the functionality of reading one byte at a time from
a file.
java.io.FileInputStream
================
constructor:
==> it opens a file for reading if the file is exist, otherwise FileNotFoundException
will be thrown
methods:
6. close a file.
import java.io.*
class ReadDemo
try
int n=fis.available();
fis.read(b);
System.out.println(s);
catch(Exception ie)
System.out.println(ie);
FileOutputStream:
FileOutputStream class possesses the functionality of writing one byte at a time into
a file.
java.io.FileOutputStream
================
constructor:
methods:
7. close a file.
import java.io.*
class CopyDemo
try
int n=fis.available();
byte b=new byte[n];
fis.read(b);
fos.write(b);
catch(Exception ie)
System.out.println(ie);
PrintWriter
This is the most enhanced writer to write character data to the file . by using
filewriter and bufferedwriter we can write only character data but by using
printwriter we can write any primitive datatypes to the file also
The most enhanced writer for writing character data to the file is PrintWriter
Constructors
1) PrintWriter pw = new PrintWriter(String fname)
Important methods
1) write(int ch)
2) write(char [] ch)
3) write(String s)
4) print(int i)
print(double d)
print(char ch)
print(Boolean b)
print(char ch[])
5) void flush()
6) close()
Ex:
class test
out.write(97);
out.println(100);
out.println(true);
out.println('c');
out.println("FDGH");
out.flush();
out.close();
Serialization Introduction
Serialization: The Process of Saving an object to a file is called “serialization”. But
strictly speaking
format.
supported format.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
int j=20;
//Serialization
oos.writeObject(d);
//De-Serialization
Dog d2=(Dog)ois.readObject();
System.out.println(d2.i+"----"+d2.j);
/*
Output:
10----20
*/
Serializable interface is defined in java.io package and doesn’t contain any method
,It is a marker inetrface.
If we are trying to perform serialization of non-serializable objects,We will get
RuntimeException saying “NotSerializableException“.
At the time of serialization,If you don’t want to send the value of a particular
variable,We have to declare that variable as transient.
At the time of serialization ,JVM ignores the original value of transient variable and
send default value.i.e transient means not to serialize.
static variables are not part of the object,Hence they won’t participate in
serialization process.
Declaration Output