Java Notes Core
Java Notes Core
Overview of Java
Java is one of the world's most important
and widely used computer languages, and it
has held this distinction for many years.
Unlike some other computer languages
whose influence has weared with passage of
time, while java's has grown.
Generics
Annotations
Enumerations
For-each Loop
Creation of Java
Varargs
Static Import
Formatted I/O
Concurrency utilities
Evolution of Java
Java was initially launched as Java 1.0 but
soon after its initial release, Java 1.1 was
launched. Java 1.1 redefined event handling,
new library elements were added.
In Java 1.2 Swing and Collection
framework was added and suspend(),
resume() and stop() methods were
deprecated from Thread class.
No major changes were made into Java 1.3
but the next release that was Java 1.4
contained several important changes.
try-with-resource statement
Application of Java
Generics
Annotations
Enumerations
For-each Loop
Varargs
Creation of Java
Static Import
Formatted I/O
Concurrency utilities
Download JDK
For running Java programs in your system
you will have to download and install JDK
kit from here (current version is jdk 1.7).
Evolution of Java
try-with-resource statement
Application of Java
Java is widely used in every corner of world
and of human life. Java is not only used in
softwares but is also widely used in
designing hardware controlling software
components. There are more than 930
million JRE downloads each year and 3
billion mobile phones run java.
( 2000/XP/vista/Window 7,8 )
Download JDK
For running Java programs in your system
you will have to download and install JDK
kit from here (current version is jdk 1.7).
Step 2: Go to the Advance System Settings
tab.
What is JVM?
Java virtual Machine(JVM) is a virtual
Machine that provides runtime environment
to execute java byte code. JVM are most
often implemented to run on existing
operating system.
JVM Architecture
Data-type
Java language has a rich implementation of
data type. Data type specify size and the
type of values that can be stored in an
identifier.
Floating-Point Number
Characters
This group represent char, which represent
symbols in a character set, like letters and
numbers.
char : It is 16 bit unsigned unicode
character. Range 0 to 65,535. example: char
Integer
c='a';
Boolean
This group represent boolean, which is a
special type for representing true/false
values. They are defined constant of the
language. example: boolean b=true;
Identifier
All Java components require name. Name
used for classes, methods, interfaces and
variables are called Identifier. Identifier
must follow some rule. Here are the rules:
Widening Casting(Implicit)
Example :
Type Casting
Assigning a value of one type to a variable
of another type is known as Type Casting.
Example :
int x = 10;
byte y = (byte)x;
"+i);
"+l);
System.out.println("Int value
System.out.println("Long value
System.out.println("Float
value "+f);
}
}
Output :
Int value 100
Long value 100
Float value 100.0
Variable
Java Programming language defines mainly
three kind of variables.
1.
Instance
variables
2.
Static
Variables
Output :
Double value 100.04
Long value 100
Int value 100
3.
Local
Variables
1) Instance variables
Instance variables are variables that are
declare inside a class but outside any
method,constructor or block. Instance
variable are also variable of object
commonly known as field or property.
class Student
{
String name;
int age;
}
class Student
{
String name;
int age;
static int instituteCode=1101;
}
datatype[]
identifier;
or
datatype
identifier[];
Both are valid syntax for array declaration.
But the former is more readable.
3) Local variables
Example :
int[] arr;
char[] arr;
short[] arr;
long[] arr;
int[][] arr; //two
dimensional array.
Initialization
Array
An array is a collection of similar data types.
Array is a container object that hold values
of homogenous type. It is also known as
static data structure because size of an array
must be specified at the time of its
declaration.
An array can be either primitive or reference
type. It gets memory in heap area. Index of
array starts from zero to size-1.
int[]
arr={10,20,30,40
,50};
Array Declaration
Accessing array element
Syntax :
the
uu[0][0] = 5;
for(int[] u: uu)
{
System.out.println(u[0]);
}
}
arrayname[n-1];
Example : To access 4th element of a given
array
int[] arr={10,20,30,40};
System.out.println("Element at index
3"+arr[2]);
}
Ex:3
class Test
{
public static void main(String[] args)
{
int[][] array1 = {{1, 2, 3, 4}, {5, 6, 7,
8}};
for(int[] val: array1)
{
System.out.print(val);
}
}
}
}
output: 10
20
30
40
Java Operators
Java provides a rich set of operators
enviroment. Java operators can be devided
into following categories
Arithmetic operators
Relation operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Misc operators
Arithmetic operators
Arithmetic operators are used in
mathematical expression in the same way
that are used in algebra.
operator
description
+
adds two operands
subtract second operands from
first
*
multiply two operand
/
divide numerator by denumerator
%
remainder of division
Increment operator increases
++
integer value by one
--
Relation operators
The following table shows all relation
operators supported by Java.
operator
description
==
Check if two operand are equal
Check if two operand are not
!=
equal.
Check if operand on the left is
>
greater than operand on the right
Check operand on the left is
<
smaller than right operand
check left operand is greater than
>=
or equal to right operand
Check if operand on left is smaller
<=
than or equal to right operand
Logical operators
Java supports following 3 logical operator.
Suppose a=1 and b=0;
operator description
example
&&
Logical AND (a && b) is false
||
Logical OR (a || b) is true
!
Logical NOT (!a) is false
Bitwise operators
Java defines several bitwise operators that
can be applied to the integer types long, int,
short, char and byte
operator
&
|
^
<<
description
Bitwise AND
Bitwise OR
Bitwise exclusive OR
left shift
>>
right shift
a
0
0
1
1
%=
B
0
1
0
1
a&b
0
0
0
1
a|b
0
1
1
1
a^b
0
1
1
0
Assignment Operators
Assignment operator supported by Java are
as follows
operator
=
+=
-=
*=
/=
description
example
assigns values from
right side operands to a=b
left side operand
adds right operand to a+=b is
the left operand and same as
assign the result to left a=a+b
subtracts right operand
a-=b is
from the left operand
same as
and assign the result to
a=a-b
left operand
mutiply left operand
a*=b is
with the right operand
same as
and assign the result to
a=a*b
left operand
divides left operand a/=b is
with the right operand same as
Misc operator
There are few other operator supported by
java language.
Conditional operator
It is also known as ternary operator and used
to evaluate Boolean expression
instanceOf operator
OOPS is a programming
approach which provides
solution to problems with
the help of algorithms
based on real world. It
uses real world approach
to solve a problem. So object
oriented technique offers better and easy
way to write program then procedural
programming model such as C, ALGOL,
PASCAL.
Inheritence
Polymorphism
Encapsulation
is an
instance of class. You may
also call it as physical
existence of a logical
template class.
A class is declared using class keyword. A
class contain both data and code that operate
on that data. The data or variables defined
within a class are called instance variables
and the code that operates on this data is
known as methods.
Abstraction
Datahiding
Class
In Java everything is
encapsulated under classes.
Local variables .
variables defined
inside methods,
constructors or blocks
are called local
variables. The variable will be
declared and initialized within the
method and the variable will be
destroyed when the method has
completed.
Instance variables .
Instance variables
are variables within
a class but outside
any method. These
variables are instantiated when the
class is loaded. Instance variables
can be accessed from inside any
method, constructor or blocks of that
particular class.
Class variables .
Class variables are
variables declared
with in a class,
outside any method,
with the static
keyword.
Q. How a class is initialized in java?
A Class is initialized in Java when an
instance of class is created using either new
operator or using reflection using
class.forName(). A class is also said to be
initialized when a static method of Class is
invoked or a static field of Class is assigned.
Methods in Java
Method describe behavior of an object. A
method is a collection of statements that are
group together to perform an operation.
Syntax :
return-type
methodName(parameter
-list)
{
//body of method
}
Example of a Method
public String getName(String st)
{
String name="hello";
name=name+st;
return name;
}
Parameter is variable
defined by a method
that receives value
when the method is
called. Parameter are always local to
the method they dont have scope outside the
While
argument is a value
that is passed to a
method when it is
called.
method.
call-by-value and
call-by-reference
There are two ways to pass an argument to a
method
1. call-by-value : In this approach copy
of an argument value is pass to a
method. Changes made to the
argument value inside the method
will have no effect on the arguments.
2. call-by-reference : In this reference
of an argument is pass to a method.
Any changes made inside the method
will affect the argument value.
System.out.println("After
"+ts.x+" "+ts.y);
}
}
Output :
Example of call-by-value
public class Test
{
public void callByValue(int x)
{
x=100;
}
public static void main(String[]
args)
{
int x=50;
Test t = new Test();
t.callByValue(x);
//function call
System.out.println(x);
}
}
Output : 50
Example of call-by-reference
public class Test
{
int x=10;
int y=20;
public void callByReference(Test
t)
{
t.x=100;
t.y=50;
}
public static void main(String[]
args)
{
Test ts = new Test();
System.out.println("Before
"+ts.x+" "+ts.y);
b.callByReference(ts);
Before 10 20
After 100 50
Method overloading
Output:
Sum is 13
Sum is 8.4
System.out.println("Area is"+
(l*b)) ;
}
void find(int l, int b,int h)
{
System.out.println("Area is"+
(l*b*h));
}
public static void main (String[]
args)
{
Area ar = new Area();
ar.find(8,5);
//find(int l,
int b) is method is called.
ar.find(4,6,2);
//find(int l,
int b,int h) is called.
}
}
Output:
Area is 40
Area is 48
class Area
{
void find(long l,long b)
{
System.out.println("Area is"+
(l*b)) ;
}
void find(int l, int b,int h)
{
System.out.println("Area is"+
(l*b*h));
}
public static void main (String[]
args)
{
Area ar = new Area();
ar.find(8,5);
//automatic type
conversion from find(int,int) to
find(long,long) .
ar.find(2,4,6)
//find(int l,
int b,int h) is called.
}
}
Output:
Area is 40
Area is 48
Constructors in Java
Default Constructor
A constructor is a special
method that is used to
initialize an object.Every
class has a constructor,if we
don't explicitly declare a
constructor for any java
class the compiler builds a
default constructor for that
class. A constructor does
not have any return type.
Parameterized
constructor
Constructor Overloading
Like methods, a constructor can also be
overloaded. Overloaded constructors are
differentiated on the basis of their type of
parameters or number of parameters.
Constructor overloading is not much
different than method overloading. In case
of method overloading you have multiple
methods with same name but different
signature, whereas in Constructor
overloading you have multiple constructor
with different signature but only difference
Cricketer c2 = new
Cricketer("sachin", "India", 32);
Cricketer c3 = new Cricketer(c2 );
System.out.println(c2);
System.out.println(c3);
c1.name = "Virat";
c1.team= "India";
c1.age = 32;
System .out. print in (c1);
}
}
output:
this is sachin of india
this is sachin of india
this is virat of india
Constructor chaining is a
phenomena of calling one
constructor from another
constructor of same class.
Since constructor can only be called from
another constructor in Java, constructor
chaining is used for this purpose.
class Test
{
Test()
{
this(10);
}
Test(int x)
{
System.out.println("x=
"+x);
}
}
Q. Does constructors return any value?
Yes, constructors return current instant of a
class. But yet constructor signature cannot
have any return type.
this keyword
Double w, weight,
dept;
Box (double w,
double h, double
d)
{
this.w = w;
this.height =
h;
this.depth =
d;
}
}
this is used to
return
current
Object
public Car
getCar()
{
return this;
}
Garbage Collection
1. Programmer doesn't
need to worry about
dereferencing an object.
Signature of
finalize() method
2. It is done automatically
by JVM.
protected void
finalize()
{
//finalize-code
}
3. Increases memory
efficiency and decreases
the chances for memory
leak.
finalize() method
Sometime an object will
need to perform some
specific task before it is
destroyed such as closing
an open connection or
releasing any resources
held. To handle such
situation finalize() method
is used. finalize() method is called by
garbage collection thread before collecting
object. Its
in
java.lang.Object
gc() Method
gc() method is used to call garbage collector
explicitly. However gc() method does not
guarantee that JVM will perform the
garbage collection. It only request the JVM
for garbage collection. This method is
present in System and Runtime class.
Output :
Garbage Collected
Modifiers in Java
Modifiers are keywords that
are added to change meaning
of a definition. In Java,
modifiers are catagorized into
two types,
1. Access control modifier
2. Non Access Modifier
1) Access control modifier
Java language has four access modifier to
control access levels for classes, variable
methods and constructor.
2) Non-access Modifier
Non-access modifiers do
not change the
accessibility of variables
and methods, but they do
provide them special
properties. Non-access modifiers are
of 5 types,
1. Final
2. Static
3. Transient
4. Synchronized
5. Volatile
Final
System.out.println("Minprice is" +
MIN_PRICE);
}
}
Static Modifier
Output
104 Abhijit StudyTonight
108 ankit StudyTonight
}
public static void main( String[]
args )
{
Test t1 = new Test();
Test t2 = new Test();
t1.increment();
t2.increment();
System.out.println(t2.y);
System.out.println(Test.x);
//accessed without any instance of
class.
}
}
Output
101
102
Static Method
A method can also be declared as static.
Static methods do not need instance of its
class for being accessed. main() method is
the most common example of static method.
main() method is declared as static because
it is called before any object of the class is
created.
Example :
{
square(8)
//static method square
() is called without any instance of
class.
}
}
Output: 64
Static block
Static block is used to initialize static data
member. Static block executes before
main() method.
Example
class ST_Employee
{
int eid;
String name;
static String company_name;
static {
company_name ="StudyTonight";
//static block invoked before main()
method
}
public void show()
{
System.out.println(eid+"
"+name+" "+company_name);
}
public static void
main( String[] args )
{
ST_Employee se1 = new
ST_Employee();
se1.eid = 104;
se1.name = "Abhijit";
se1.show();
class Test
{
}
}
Output
104 Abhijit StudyTonight
Output
compiler error: non-static variable
count cannot be referenced from a
static context
Transient modifier
When an instance
variable is declared as
transient, then its value
doesn't persist when an
object is serialized
Synchronized modifier
When a method is
synchronized it can be
accessed by only one
thread at a time. We will
discuss it in detail in
Thread.
Volatile modifier
extends keyword is
class Vehicle.
{
......
}
class Car extends Vehicle
{
.......
//extends the property of
vehicle class.
}
Purpose of
Inheritance
1. To promote
code reuse.
2. To use
Polymorphism.
Simple example of Inheritance
class Parent
{
public void p1()
{
System.out.println("Parent
method");
}
}
public class Child extends Parent {
public void c1()
{
System.out.println("Child
method");
}
public static void main(String[]
args)
{
Child cobj = new Child();
cobj.c1();
//method of
Child class
cobj.p1();
//method of
Parent class
}
}
Output
Child method
Parent method
Output
sports Car
Types of Inheritance
1. Single
Inheritance
2. Multilevel
Inheritance
3. Heirarchical
Inheritance
Multiple
inheritance is not
supported in java
NOTE :
Why multiple
inheritance is not
supported in Java
To remove
ambiguity.
To provide more
maintainable and
clear design.
super keyword
In Java, super keyword is used to refer to
immediate parent class of a class. In other
super keyword is
used by a subclass
whenever it needs to
refer to its immediate
super class.
words
Output
class Parent
{
String name;
public void details()
{
name = "Parent";
System.out.println(name);
}
}
public class Child extends Parent {
String name;
public void details()
{
super.details();
//calling Parent class
details() method
name = "Child";
System.out.println(name);
}
public static void main(String[]
args)
{
Child cobj = new Child();
cobj.details();
}
}
Output
Parent
Child
super(n1);
//passing
argument to parent class constructor
this.name = n2;
}
public void details()
{
System.out.println(super.name+" and
"+name);
}
public static void
main(String[] args)
{
Child cobj = new
Child("Parent","Child");
cobj.details();
}
}
Output
Parent and Child
class Student
{
String name;
Address ad;
}
Here you can say that Student has-a
Address.
Aggregation (HAS-A)
Example of Aggregation
class Author
{
String authorName;
int age;
String place;
Author(String name,int age,String
place)
{
this.authorName=name;
this.age=age;
this.place=place;
}
public String getAuthorName()
{
return authorName;
}
public int getAge()
{
return age;
}
public String getPlace()
{
return place;
}
}
class Book
{
String name;
int price;
Author auth;
Book(String n,int p,Author at)
{
this.name=n;
this.price=p;
this.auth=at;
}
public void showDetail()
{
System.out.println("Book
is"+name);
System.out.println("price
"+price);
System.out.println("Author is
"+auth.getAuthorName());
}
}
class Test
{
public static void main(String
args[])
{
Author ath=new
Author("Me",22,"India");
Book b=new Book("Java",550,ath);
b.showDetail();
}
}
Output:
Book is Java.
price is 550.
Author is me.
Composition is
restricted form of
Aggregation. For
example a class Car
cannot exist without
Engine.
class Car
{
private Engine engine;
Car(Engine en)
{
engine = en;
}
}
Description
One of the advantages of Object-Oriented
programming language is code reuse. There
are two ways we can do code reuse either by
implementation of inheritance (IS-A
relationship), or object composition (HAS-A
relationship). Although the compiler and
Java virtual machine (JVM) will do a lot of
work for you when you use inheritance, you
can also get at the functionality of
inheritance when you use composition.
IS-A Relationship:
In object oriented programming, the concept
of IS-A is a totally based on Inheritance,
which can be of two types Class Inheritance
or Interface Inheritance. It is just like saying
"A is a B type of thing". For example, Apple
is a Fruit, Car is a Vehicle etc. Inheritance is
uni-directional. For example House is a
Building. But Building is not a House.
It is key point to note that you can easily
identify the IS-A relationship. Wherever you
see an extends keyword or implements
keyword in a class declaration, then this
class is said to have IS-A relationship.
view plainprint?
1. package relationships;
2.
3. class Car {
4.
// Methods implementation an
d class/Instance members
5.
6.
7.
8.
9.
10.
HAS-A Relationship:
11.
12.
13.
this.color = color;
14.
15.
16.
17.
this.maxSpeed = maxSpee
d;
18.
1. package relationships;
2.
3. public class Engine {
4.
19.
5.
20.}
6.
7.
view plainprint?
9.
3.
4.
5.
Engine MarutiEngine = ne
w Engine();
6.
MarutiEngine.start();
7.
8.
8.
10.
11.
12.}
4.
5.
6.
7.
myMaruti.setColor("RED");
8.
myMaruti.setMaxSpeed(18
0);
9.
myMaruti.carInfo();
10.
11.
myMaruti.MarutiStartDemo
();
12.
13.
14.}
Summary
Has-a relationship is
composition relationship which
is productive way of code reuse.
Association
Association is a relationship between two
objects. In other words, association defines
the multiplicity between objects. You may
be aware of one-to-one, one-to-many, manyto-one, many-to-many all these words define
an association between objects. Aggregation
is a special form of association.
Composition is a special form of
aggregation.
Aggregation
Aggregation is a special case of association.
A directional association between objects.
When an object has-a another object, then
you have got an aggregation between them.
Direction between them specified which
object contains the other object. Aggregation
is also called a Has-a relationship.
Composition
Composition is a special case of
aggregation. In a more specific manner, a
restricted aggregation is called composition.
When an object contains the other object, if
the contained object cannot exist without the
existence of container object, then it is
called composition.
Realization
Realization is a relationship between the
blueprint class and the object containing its
respective implementation level details. This
object is said to realize the blueprint class.
In other words, you can understand this as
the relationship between the interface and
the implementing class.
Abstraction
Abstraction is specifying the framework and
hiding the implementation level information.
Concreteness will be built on top of the
abstraction. It gives you a blueprint to
follow to while implementing the details.
Abstraction reduces the complexity by
hiding low level details.
Example: A wire frame model of a car.
Generalization
Generalization uses a is-a relationship
from a specialization to the generalization
class. Common structure and behaviour are
used from the specializtion to the
generalized class. At a very broader level
you can understand this as inheritance. Why
I take the term inheritance is, you can relate
this term very well. Generalization is also
called a Is-a relationship.
Dependency
Change in structure or behaviour of a class
affects the other related class, then there is a
dependency between those two classes. It
need not be the same vice-versa. When one
class contains the other class it this happens.
Method Overriding
If
class Animal
{
Animal myType()
{
return new Animal();
}
}
class Dog extends Animal
{
Dog myType()
//Legal
override after Java5
onward
{
return new Dog();
}
}
Runtime Polymorphism or
Dynamic method dispatch
Dynamic method
dispatch is a
mechanism by which
a call to an
overridden method
is resolved at
runtime. This is how java
implements runtime polymorphism. When
an overridden method is called by a
reference, java determines which version of
that method to execute based on the type of
object it refer to. In simple words the type of
object which it referred determines which
version of overridden method will be called.
ck.type();
gm=ck;
//gm refers to
Cricket object
gm.type(); //calls Cricket's
version of type
}
}
Output:
Indoor & outdoor
Outdoor game
Outdoor game
Upcasting
When Parent class reference variable refers
to Child class object, it is known as
Upcasting
Example
class Game
{
public void type()
{ System.out.println("Indoor &
outdoor"); }
}
Class Cricket extends Game
{
public void type()
{ System.out.println("outdoor
game"); }
public static void main(String[]
args)
{
Game gm = new Game();
Cricket ck = new Cricket();
gm.type();
instanceof operator
In Java, instanceof
operator is used to
check the type of an
object at runtime. It is
the means by which your program can
obtain run-time type information about an
object. instanceof operator is also
important in case of casting object at
runtime. instanceof operator return
boolean value, if an object reference is of
specified type then it return true otherwise
false.
Example of instanceOf
public class Test
{
public static void main(String[]
args)
{
Test t= new Test();
System.out.println(t
instanceof Test);
}
}
output true
Downcasting
Output
Output
Sucessfull Casting
true
true
false
false
true
false
false
true
Java Package
User-definedpackage:- Java
package created by
user to categorized
classes and
interface
Creating a package
package
package_name[.subpackage
_name[..]];
package mypack;
public class employee
{
...statement;
}
class test
{
public static void main(String[]
args)
{
Book bk = new
Book("java","Herbert");
bk.show();
}
}
import keyword
class MyDate
extends
java.util.Date
{
//statement;
}
2.
import the
only class you
want to use.
import
java.util.Dat
e;
class MyDate extends Date
{
//statement.
}
3.
import all
the classes
from the
particular
package
Example :
import
java.util.*;
class MyDate extends Date
{
//statement;
}
Example :
package mypack;
import java.util.*;
Example :
Jar cfv hello.jar mypack(folder)
Set classpath=.;d:\java7\hello.jar
Static import
Syntax
import static
package.classtype-name.*;
Example
import static
java.lang.Math.*;
//importing all
static member of
Math class
Syntax
import static
package.classname.staticmember-name;
Example
import static
java.lang.Math.sqr
t;
//importing
Output
12
Output
12
Abstract class
abstract class
class_name { }
Abstract method
abstract return_type
method_name(para_lis
t);
// No
definition
Example of Abstract class
abstract class A
{
abstract void callme();
}
class B extends A
{
void callme()
{
System.out.println("this is
callme.");
}
public static void main(String[]
args)
{
B b=new B();
b.callme();
}
}
output: this is callme.
Points to Remember
1. Abstract classes are not Interfaces.
They are different, we will study this
when we will study Interfaces.
2. An abstract class must have an
abstract method.
3. Abstract classes can have
Constructors, Member variables and
Normal methods.
Output
Car engine
interface
interface_name { }
Example of Interface
interface Moveable
{
int AVERAGE-SPEED=40;
void move();
}
Interface
Compiler
automatically
converts methods of
Interface as public
NOTE :
true
true
Difference between an
interface and an abstract
class?
Abstract class
Interface
methods should be
implemented and
specialization
implemented.
behavior should be
implemented by
child classes.
Interface
Interface is a Java
Object containing
Abstract class is a
method declaration but
class which contain
no implementation.
one or more abstract
The classes which
methods, which has
implement the
to be implemented
Interfaces must provide
by its sub classes.
the method definition
for all the methods.
Abstract class is a
Interface is a pure
Class prefix with an
abstract class which
abstract keyword
starts with interface
followed by Class
keyword.
definition.
Whereas, Interface
Abstract class can
contains all abstract
also contain
methods and final
concrete methods.
variable declarations.
Abstract classes are Interfaces are useful in
useful in a situation a situation that all
that Some general properties should be
this.str = s;
}
public String get()
{
return str;
}
or,
String str5 =
"hello"+"Java";
String str1 =
"Hello";
String str=
"Hello";
String
str2=str;
Concatenating String
There are 2 methods to concatenate two or
more string.
1.
Using
concat() method
str2=str2.concat
("world");
2.
Using +
operator
string s = "Hello";
string str = "Java";
string str2 =
s.concat(str);
String str1 =
"Hello".concat("Java
");
//works with string
3.
By
CompareTo()
method
literals too.
string str =
"Rahul";
string str1 =
"Dravid";
string str2 =
str + str1;
string st =
"Rahul"+"Dravid"
;
boolean equals
(Object str)
It compares the content of the strings. It will
return true if string matches, else returns
false.
String s = "Hell";
String s1 = "Hello";
String s2 = "Hello";
s1.equals(s2);
//true
s.equals(s1) ;
//false
Using == operator
String Comparison
String comparison can be done in 3 ways.
1.
Using
equals() method
2.
Using ==
operator
String s1 =
"Java";
String s2 =
"Java";
String s3 = new
string ("Java");
test(Sl == s2)
//true
test(s1 == s3)
By
//false
compareTo() method
equalsIgnoreCase()
equalsIgnoreCase() determines the equality
of two Strings, ignoring thier case (upper or
lower case doesn't matters with this
fuction ).
length()
length() function returns the number of
characters in a String.
String str = "Count me";
System.out.println(str.length());
Output : 8
replace()
substring()
substring() method returns a part of the
string. substring() method has two forms,
public String
substring(int begin);
public String
substring(int begin,
int end);
The first argument represents the starting
point of the subtring. If the substring()
method is called with only one argument,
the subtring returned, will contain characters
from specified starting point to the end of
original string.
But, if the call to substring() method has two
arguments, the second argument specify the
end point of substring.
String str = "0123456789";
System.out.println(str.substring(4))
;
Output : 456789
System.out.println(str.substring(4,7
));
Output : 456
toLowerCase()
toLowerCase() method returns string with
all uppercase characters converted to
lowercase.
String str = "ABCDEF";
System.out.println(str.toLowerCase()
);
Output : abcdef
valueOf()
Overloaded version of valueOf() method is
present in String class for all primitive data
types and for type Object.
NOTE : valueOf() function is used to
convert primitive data types into Strings.
valueOf()
method calls toString()
But for objects,
function.
toString()
toString() method
returns the string
representation of the
object used to invoke
this method. toString() is used to
represent any Java Object into a meaningful
string representation. It is declared in the
Object class, hence can be overrided by any
java class. (Object class is super class of all
java classes.)
public class
Car {
public static
void
main(String
args[])
{
Car c=new
Car();
System.out.prin
tln(str.toStrin
g());
System.out.prin
tln(c);
}
public String
toString()
{
return "This
is my car
object";
}
}
String str =
"Hello World";
toUpperCase()
This method returns string with all
lowercase character changed to uppercase.
String str = "abcdef";
System.out.println(str.toLowerCase()
);
Output : ABCDEF
trim()
StringBuffer()
stringBuffer(int size)
Output : hello
StringBuffer class
StringBuffer class is used to create a
mutable string object. It represents
growable and writable character sequence.
As we know that String objects are
immutable, so if we do a lot of changes with
String objects, we will end up with a lot of
memory leak.
So StringBuffer class is used when we have
to make lot of modifications to our string. It
is also thread safe i.e multiple threads cannot
access it simultaneously. StringBuffer
defines 4 constructors. They are,
1. StringBuffer ( )
2. StringBuffer ( int size )
3. StringBuffer ( String
str )
creates an empty
string buffer and reserves room for
16 characters.
creates
an empty string and takes an integer
argument to set capacity of the
buffer.
strB = new
StringBuffer("study");
StringBuffer
strB.append("cm
tes");
System.out.println(strB);
Output: studycmtes
}
}
//
4. StringBuffer (
charSequence [ ]ch )
StringBuffer
append(String str)
StringBuffer
append(int n)
StringBuffer
append(Object obj)
The string representation of each parameter
is appended to StringBuffer object.
StringBuffer str = new
StringBuffer("test");
str.append(123);
System.out.println(str);
Output : test123
insert()
This method inserts one string into another.
Here are few forms of insert() method.
StringBuffer
insert(int index,
String str)
StringBuffer
insert(int index, int
num)
StringBuffer str =
new
StringBuffer("test")
;
str.insert(4, 123);
System.out.println(s
tr);
Output : test123
reverse()
This method reverses the characters within a
StringBuffer object.
StringBuffer str = new
StringBuffer("Hello");
str.reverse();
System.out.println(str);
Output : olleH
replace()
This method replaces the string from
specified start index to the end index.
StringBuffer str = new
StringBuffer
insert(int index,
Object obj)
Hello
StringBuffer("
World");
str.replace( 6,
11, "java");
System.out.println(str);
Output : Hello java
capacity()
exception means
exceptional condition, it
is a problem that may
arise during the
execution of program. A
Exception
Output : 16
ensureCapacity()
This method is used to ensure minimum
capacity of StringBuffer object.
StringBuffer str = new
StringBuffer("hello");
str.ensureCapacity(10);
Exception Handling
Exception Handling is the
mechanism to handle
runtime malfunctions. We
need to handle such
exceptions to prevent
abrupt termination of
program. The term
A Java Exception is
an object that
describes the
exception that occurs
in a program. When an
exceptional events occurs in java, an
exception is said to be thrown. The code
that's responsible for doing something about
the exception is called an exception
handler.
Error
Errors are typically ignored in code
because you can rarely do anything
about an error. Example : if stack
overflow occurs, an error will arise.
This type of error is not possible
handle in code.
Checked Exception
The exception that can be predicted
by the programmer.Example : File
that need to be opened is not found.
These type of exceptions must be
checked at compile time.
Uncaught Exceptions
Unchecked Exception
statement involves
declaring the type of
exception you are
trying to catch. If an
Exception Handling Mechanism
In java, exception handling is done using
five keywords,
1. try
2. catch
3. throw
4. throws
5. finally
Exception handling is done by transferring
the execution of a program to an appropriate
exception handler when exception occurs.
try
{
int arr[]={5,0,1,2};
try
{
int x=arr[3]/arr[1];
}
catch(ArithmeticException ae)
{
System.out.println("divide by
zero");
}
arr[4]=3;
}
catch(ArrayIndexOutOfBoundsException
e)
{
System.out.println("array index
out of bound exception");
}
}
}
BufferedReader br=new
BufferedReader(new
FileReader("d:\\myfile.txt"));
while((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
//closing
BufferedReader stream
}catch(IOException ie)
{ System.out.println("exception");
}
}
}
throw
ThrowableInstanc
e
Creating Instance of Throwable class
import java.io.*;
class Test
{
public static void main(String[]
args)
{
try(BufferedReader br=new
BufferedReader(new
FileReader("d:\\myfile.txt")))
{
String str;
while((str=br.readLine())!=null)
{
System.out.println(str);
}
}catch(IOException ie)
{ System.out.println("exception");
}
}
}
class Test
{
static void avg()
{
try
{
throw new
ArithmeticException("demo");
}
catch(ArithmeticException e)
{
System.out.println("Exception
caught");
}
}
throw Keyword
throws Keyword
Any method capable of causing exceptions
must list all the exceptions possible during
its execution, so that anyone calling that
method gets a prior knowledge about which
exceptions to handle. A method can do so by
using the throws keyword.
Syntax :
type method_name(parameter_list)
throws exception_list
{
//definition of method
}
finally clause
A finally keyword is used to create a block
of code that follows a try block. A finally
block of code always executes whether or
not exception has occurred. Using a finally
block, lets you run any cleanup type
statements that you want to execute, no
matter what happens in the protected code.
A finally block appears at the end of catch
block.
Points to Remember
1. Extend the Exception class to create
your own ecxeption class.
Example demonstrating finally Clause
Class ExceptionTest
{
public static void main(String[]
args)
{
int a[]= new int[2];
System.out.println("out of try");
try
{
System.out.println("Access
invalid element"+ a[3]);
/* the above statement will throw
ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is
always executed.");
}
}
}
Output:
Out of try
Because ArrayIndexOutOfBoundsException
is an unchecked exception hence, overrided
show() method can throw it.
Chained Exception
Chained Exception was added to Java in
JDK 1.4. This feature allow you to relate
one exception with another exception, i.e
one exception describes cause of another
exception. For example, consider a situation
in which a method throws an
ArithmeticException because of an attempt
to divide by zero but the actual cause of
exception was an I/O error which caused the
divisor to be zero. The method will throw
only ArithmeticException to the caller. So
the caller would not come to know about the
actual cause of exception. Chained
Exception is used in such type of situations.
Example
import java.io.IOException;
public class ChainedException
{
public static void divide(int a,
int b)
{
if(b==0)
{
ArithmeticException ae = new
ArithmeticException("top layer");
ae.initCause( new
IOException("cause") );
throw ae;
}
else
{
System.out.println(a/b);
}
}
Introduction to Multithreading
class MainThread
{
public static void main(String[]
args)
{
Thread t=Thread.currentThread();
t.setName("MainThread");
System.out.println("Name of thread
is "+t);
}
}
Output : Name of thread is
Thread[MainThread,5,main]
Thread Class
Thread class is the main class on which
Java's Multithreading system is based.
Thread class, along with its companion
interface Runnable will be used to create
and run threads for utilizing Multithreading
feature of Java.
Thread Priorities
Every thread has a priority that helps the
operating system determine the order in
which threads are scheduled for execution.
In java thread priority ranges between,
MIN-PRIORITY (a
constant of 1)
MAX-PRIORITY (a
constant of 10)
By default every thread is
given a NORMPRIORITY(5). The main thread
always have NORM-PRIORITY.
3. Thread ( Runnable r )
4. Thread ( Runnable r, String str)
You can create new thread, either by
extending Thread class or by implementing
Runnable interface. Thread class also
defines many methods for managing threads.
Some of them are,
Method
Description
setName() to give thread a name
getName() return thread's name
getPriority() return thread's priority
checks if thread is still running
isAlive()
or not
join()
Wait for a thread to end
run()
Entry point for a thread
suspend thread for a specified
sleep()
time
start a thread by calling run()
start()
method
Some Important points to Remember
Creating a thread
Java defines two ways by which a thread can
be created.
Joining threads
final boolean
isAlive()
But, join() method is used more commonly
than isAlive(). This method waits until the
thread on which it is called terminates.
}
public static void main(String[]
args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}
Output
r1
true
true
r1
r2
r2
Output
r1
r1
r2
r2
m1.join(1500);
Output
r1
r2
r1
r2
Synchronization
synchronized
(object)
{
//statement to be
synchronized
}
Synchronized Keyword
To synchronize above program, we must
serialize access to the shared display()
method, making it available to only one
thread at a time. This is done by using
keyword synchronized with display()
method.
synchronized void display (String
msg)
Interthread Communication
Java provide benefit of avoiding thread
pooling using interthread communication.
The wait(), notify(), notifyAll() of Object
class. These method are implemented as
final in Object. All three method can be
called only from within a synchronized
context.
sleep()
no such requirement
monitor is not
released
awake when notify() not awake when
or notifyAll() method notify() or notifyAll()
is called.
method is called
not a static method static method
sleep() method is
wait() is generaly
simply used to put
used on condition
your thread on sleep.
monitor is released
Thread Pooling
Pooling is usually implemented by loop i.e
to check some condition repeatedly. Once
condition is true appropriate action is taken.
This waste CPU time.
Example of deadlock
Deadlock
class Pen{}
class Paper{}
public class Write {
public static void main(String[]
args)
{
final Pen pn =new Pen();
final Paper pr =new Paper();
Thread t1 = new Thread(){
public void run()
{
synchronized(pn)
{
System.out.println("Thread1 is
holding Pen");
try{
Thread.sleep(1000);
}
catch(InterruptedException e){}
synchronized(pr)
{ System.out.println("Requesting
for Paper"); }
}
}
};
Thread t2 = new Thread(){
public void run()
{
synchronized(pr)
{
System.out.println("Thread2 is
holding Paper");
try{
Thread.sleep(1000);
}
catch(InterruptedException e){}
synchronized(pn)
{ System.out.println("requesting
for Pen"); }
}
};
t1.start();
t2.start();
Enumeration means
a list of named constant.
In Java, enumeration
defines a class type. An
Enumeration can have
constructors, methods
and instance variables. It
is created using enum
keyword. Each enumeration constant
JDK5.
Output
Thread1 is holding Pen
Thread2 is holding Paper
Enumerations
Example of Enumeration
enum WeekDays
{ sun, mon, tues, wed, thurs, fri,
sat }
class Test
{
public static void main(String
args[])
{
WeekDays wk;
wk = WeekDays.sun;
System.out.println("Today is
"+wk);
}
}
Output : Today is sun
type wrapper
Java uses primitive types such as int, double
or float to hold the basic data types for the
sake of performance. Despite the
performance benefits offered by the
primitive types, there are situation when you
will need an object representation. For
example, many data structures in Java
operate on objects, so you cannot use
primitive types with those data structures. To
handle these situations Java provides type
Wrappers which provide classes that
encapsulate a primitive type within an
object.
Character : It encapsulates
primitive type char within object.
Autoboxing and
Unboxing
Autoboxing is a
process by which
primitive type is
automatically
encapsulated(boxed
) into its equivalent
type wrapper
Auto-Unboxing is
a process by which
the value of object
is automatically
extracted from a
type wrapper.
class Test
{
public static void main(String[]
args)
{
Integer iob = 100;
//Autoboxing of int
int i = iob;
//unboxing
of Integer
System.out.println(i+" "+iob);
//Autoboxing of
2. We don't have to
perform Explicit
typecasting.
3.
It helps prevent
errors, but may lead
to unexpected results
sometimes. Hence
must be used with
care.
IO Stream
A
Stream is linked to a
physical layer by java
I/O system to make
input and output
operation in java. In
general, a stream means
continuous flow of data.
Java performs I/O through Streams.
OutputStream
PrintStream
input.
Abstract class that
describe stream
output.
Output Stream that
contain print()
and println()
method
Description
Used for Buffered
BufferedInputStream
Input Stream.
Used for Buffered
BufferedOutputStream
Output Stream.
Contains method
DataInputStream
for reading java
standard datatype
An output stream
that contain
DataOutputStream
method for writing
java standard data
type
Input stream that
FileInputStream
reads from a file
Output stream that
FileOutputStream
write to a file.
InputStream
Abstract class that
describe stream
Description
Handles buffered
input stream.
Handles buffered
BufferedWriter
output stream.
Input stream that
FileReader
reads from file.
Output stream that
FileWriter
writes to file.
Input stream that
InputStreamReader translate byte to
character
Output stream that
OutputStreamReader translate character to
byte.
Output Stream that
contain print() and
PrintWriter
println() method.
Abstract class that
Reader
define character
stream input
Abstract class that
Writer
define character
stream output
Reading Characters
BufferedReader
Reading Strings
{ e.printStackTrace(); }
}
}
Serialization and
Deserialization in
Java
Serialization is a
process of converting an
object into a sequence of
bytes which can be
persisted to a disk or
database or can be sent
through streams. The
reverse process of
creating object from
sequence of bytes is
called
deserialization.
A class must implement Serializable
interface present in java.io package in order
to serialize its object successfully.
Serializable is a marker interface that adds
serializable behaviour to the class
implementing it.
Java provides Serializable API encapsulated
under java.io package for serializing and
deserializing objects which include,
java.io.serializable
java.io.Externalizable
ObjectInputStream
writeObject() method of
ObjectOutputStream class
Marker interface
Marker Interface is a special interface in
Java without any field and method. Marker
interface is used to inform compiler that the
class implementing it has some special
behaviour or meaning. Some example of
Marker interface are,
java.io.Serializable
java.lang.Cloneable
java.rmi.Remote
java.util.RandomAccess
Signature
of
writeObject()
readObject()
public final
void
writeObject(ob
ject x) throws
IOException
readObject() method
of ObjectInputStream
and
public final
Object
readObject()
throws
IOException,Cla
ssNotFoundExcep
tion
while serializing if you do not want any field
to be part of object state then declare it
either static or transient based on your need
and it will not be included during java
serialization process.
{ e. printStackTrace(); }
}
}
Deserialization of Object
Serializing an Object
import java.io.*;
class studentinfo implements
Serializable
{
String name;
int rid;
static String contact;
studentinfo(string n, int r, string
c)
{
this.name = n;
this.rid = r;
this.contact = c;
}
}
class Test
{
public static void main(String[]
args)
{
try
{
Studentinfo si = new
studentinfo("Abhi", 104, "110044");
FileOutputStream fos = new
FileOutputStream("student.ser");
Objectoutputstream oos = new
ObjectOutputStream(fos);
oos.writeObject(si);
oos.close();
fos.close();
}
catch (Exception e)
import java.io * ;
class DeserializationTest
{
public static void main(String[]
args)
{
studentinfo si=null ;
try
{
FileInputStream fis = new
FileInputStream("student.ser");
ObjectOutputStream ois = new
ObjectOutputStream(fis);
si =
(studentinfo)ois.readObject();
}
catch (Exception e)
{ e.printStackTrace(); }
System.out.println(si.name);
System.out. println(si.rid);
System.out.println(si.contact);
}
}
Output :
Abhi
104
null
transient Keyword
Networking in Java
Java is a premier language for network
programming. java.net package encapsulate
large number of classes and interface that
provides an easy-to use means to access
network resources. Here are some important
classes and interfaces of java.net package.
URL class
Java URL Class present in java.net package,
deals with URL (Uniform Resource Locator)
which uniquely identify or locate resources
on internet.
getHost() : Returns
hostname(domain name) of URL
Generics
Generics
also provide type
safety.
}
Output :
java lang.Integer = 88
Java lang.String = this is string
Generic Constructors
iob = sob;
//Absolutely Wrong
Generic Methods
You can also create generic methods that can
be called with different types of arguments
based on the type of arguments passed to
generic method, the compiler handles each
method.
class Gen
{
private double val;
< T extends Number> Gen(T ob)
{
val=ob.doubleValue();
}
void show()
{
System.out.println(val);
}
}
class Test
{
public static void main(String[]
args)
{
Gen g = new Gen(100);
Gen g1 = new Gen(121.5f);
g.show();
g1.show();
}
}
Output :
100.0
121.5
Generic Interface
Like classes and methods, you can also
create generic interfaces.
interface MyInterface< T >
{ .. }
Collection Framework
Collection framework was not part of
original Java release. Collections was added
to J2SE 1.2. Prior to Java 2, Java provided
adhoc classes such as Dictionary, Vector,
Stack and Properties to store and manipulate
Collection
framework provides
many important
classes and interfaces
to collect and
organize group of
alike objects.
groups of objects.
If display(88,"This is string")
is uncommented, it will give an error
of type incompatibility, as String is
not a subclass of Number class.
Description
Enables you to work with groups
Collection of object; it is at the top of
collection hierarchy
Extends queue to handle double
Deque
ended queue.
Extends collection to handle
List
sequences list of object.
Extends collection to handle
special kind of list in which
Queue
element are removed only from
the head.
Extends collection to handle
Set
sets, which must contain unique
element.
SortedSet Extends sets to handle sorted set.
Description
occurs if a
UnSupportedOperationExcepti Collection
on
cannot be
modified
occurs when
one object is
ClassCastException
incompatibl
e with
another
occurs when
you try to
NullPointerException
store null
object in
Collection
thrown if an
invalid
IllegalArgumentException
argument is
used
thrown if
you try to
add an
IllegalStateException
element to
an already
full
Collection
Methods
isEmpty()
add( E obj )
addAll( Collection C )
removeAll( Collection C )
Description
Used to add
objects to a
collection.
Doesn't add
duplicate
elements to
the collection.
Add all
elements of
collection C to
the invoking
collection
To remove an
object from
collection
Removes all
element of
collection C
from the
invoking
collection
To determine
whether an
object is
present in
collection or
not
size()
Description
Returns true if
collection is
empty, else
returns false
returns
number of
elements
present in
collection
Description
Returns object
stored at the
specified
index
Stores object
at the
specified
index in the
calling
collection
Returns index
of first
occurence of
obj in the
collection
Methods
lastIndexOf( Object obj )
Description
Returns index
of last
occurence of
obj in the
collection
Returns a list
containing
elements
between start
and end index
in the
collection
Description
removes element at the head of
poll()
the queue and returns null if
queue is empty
removes element at the head of
the queue and throws
remove()
NoSuchElementException if
queue is empty
returns the element at the head
of the queue without removing
peek()
it. Returns null if queue is
empty
same as peek(), but throws
element() NoSuchElementException if
queue is empty
offer( E obj
Adds object to queue.
)
The Dequeue Interface
1. It extends Queue interface and
declares behaviour of a double-ended
queue. Its general declaration is,
interface Dequeue < E >
Output : [ab,bc,cd]
ArrayList class
1. ArrayList class extends
AbstractList class and implements
the List interface.
2. ArrayList supports dynamic array
that can grow as needed. ArrayList
has three constructors.
ArrayList()
ArrayList( Collection C )
ArrayList( int capacity )
Example of ArrayList
import java.util.*
class Test
{
public static void main(String[]
args)
{
ArrayList< String> al = new
ArrayList< String>();
al.add("ab");
al.add("bc");
al.add("cd");
system.out.println(al);
}
}
HashSet class
Output
[Ricky Pointing(999100091), David
Beckham(998392819), Virat
Kohli(998131319)]
LinkedList class
1. LinkedList class extends
AbstractSequentialList and
implements List,Deque and Queue
inteface.
LinkedHashSet Class
1. LinkedHashSet class extends
HashSet class
2. LinkedHashSet maintains a linked
list of entries in the set.
3. LinkedHashSet stores elements in
the order in which elements are
inserted.
Output : [B, A, D, E, C, F]
TreeSet Class
1. It extends AbstractSet class and
implements the NavigableSet
interface.
2. It stores elements sorted ascending
order.
3. Uses a Tree structure to store
elements.
4. Access and retrieval times are quite
fast.
5. It has four Constructors.
TreeSet()
TreeSet( Collection C )
TreeSet( Comparator comp )
TreeSet( SortedSet ss )
Accessing a Collection
Example of LinkedHashSet class
import java.util.*;
class LinkedHashSetDemo
{
public static void main(String
args[])
{
LinkedHashSet< String> hs = new
LinkedHashSet< String>();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
1.Using Iterator
interface
2.Using ListIterator
interface
ListIterator Interface is
used to traverse a list in
both forward and
backward direction. It is
available to only those collections that
implement the List Interface.
import java.util.*;
class Test_Iterator
import java.util.*;
class ForEachDemo
{
public static void main(String[]
args)
{
LinkedList< String> ls = new
LinkedList< String>();
ls.add("a");
ls.add("b");
ls.add("c");
ls.add("d");
in an
ascending
order.
Output : a b c d
Map Interface
A Map stores data in key and value
association. Both key and values are objects.
The key must be unique but the values can
be duplicate. Although Maps are a part of
Collection Framework, they can not actually
be called as collections because of some
properties that they posses. However we can
obtain a collection-view of maps.
Interface
Map
Map.Entry
NavigableMap
SortedMap
Description
Maps unique
key to value.
Describe an
element in
key and
value pair in
a map. This
is an inner
class of map.
Extends
SortedMap
to handle the
retrienal of
entries based
on closest
match
searches
Extends Map
so that key
are
maintained
HashMap class
1. HashMap class extends
AbstractMap and implements Map
interface.
a 100
d 400
b 200
TreeMap class
HashMap()
HashMap(Map< ? extends k, ?
extends V> m)
HashMap(int capacity)
HashMap(int capacity, float
fillratio)
Comparator Interface
LinkedHashMap class
1. LinkedHashMap extends
HashMap class.
2. It maintains a linked list of entries in
map in order in which they are
inserted.
3. LinkedHashMap defines the
following constructor
LinkedHashMap()
LinkedHashMap(Map< ? extends
k, ? extends V> m)
LinkedHashMap(int capacity)
LinkedHashMap(int capacity,
float fillratio)
LinkedHashMap(int capacity,
float fillratio, boolean
order)
In Java, Comparator
interface is used to order
the object in your own
way. It gives you ability to
decide how element are
stored within sorted
collection and map.
Comparator Interface
defines compare()
method. This method
compare two object and
return 0 if two object are
equal. It returns a positive
value if object1 is greater
than object2. Otherwise a
negative value is return. The
method can throw a ClassCastException if
the type of object are not compatible for
comparison.
protected boolean
removeEldestEntry(Map.Entry e)
Example
EnumMap class
Student class
1. EnumMap extends AbstractMap
and implements Map interface.
2. It is used for key as enum
class Student
int roll;
String name;
Student(int r,String n)
{
roll = r;
name = n;
}
public String toString()
{
return roll+" "+name;
}
MyComparator class
This class defines the comparison logic for
Student class based on their roll. Student
object will be sotred in ascending order of
their roll.
class MyComparator implements
Comparator
{
public int compare(Student
s1,Student s2)
{
if(s1.roll == s2.roll)
return 0;
else if(s1.roll > s2.roll)
return 1;
else return -1;
}
}
public class Test
{
public static void main(String[]
args)
{
TreeSet< Student> ts = new
TreeSet< Student>(new
MyComparator());
ts.add(new Student(45,
"Rahul"));
ts.add(new Student(11,
"Adam"));
ts.add(new Student(19,
"Alex"));
System.out.println(ts);
}
}
Output
[ 11 Adam, 19 Alex, 45 Rahul ]
Legacy Classes
Early version of java did not include the
Collection framework. It only defined
several classes and interface that provide
method for storing objects. When Collection
framework were added in J2SE 1.2, the
original classes were reengineered to
support the collection interface. These
classes are also known as Legacy classes.
All legacy claases and interface were
redesign by JDK 5 to support Generics.
The following are the legacy classes defined
by java.util package
1. Dictionary
2. HashTable
3. Properties
4. Stack
5. Vector
There is only one legacy interface called
Enumeration
NOTE: All the legacy classes are
syncronized
Enumeration interface
1. Enumeration interface defines
method to enumerate through
collection of object.
2. This interface is suspended by
Iterator interface.
3. However some legacy classes such
as Vector and Properties defines
Vector class
1. Vector is similar to ArrayList which
represents a dynamic array.
2. The only difference between Vector
and ArrayList is that Vector is
synchronised while Array is not.
the Vector
Example of Vector
import java.util.*;
public class Test
{
public static void main(String[]
args)
{
Vector ve = new Vector();
ve.add(10);
ve.add(20);
ve.add(30);
ve.add(40);
ve.add(50);
ve.add(60);
Enumeration en =
ve.elements();
while(en.hasMoreElements())
{
Description
add element to the
addElement()
Vector
return the element at
elementAt()
specified index
return an enumeration
elements
of element in vector
return first element in
firstElement()
the Vector
return last element in
lastElement()
the Vector
removeAllElement() remove all element of
System.out.println(en.nextElement())
;
}
}
}
Output
10
20
30
40
50
60
Hashtable class
1. Like HashMap, Hashtable also stores
key/value pair in hashtable. However
neither keys nor values can be null.
2. There is one more difference
between HashMap and Hashtable
that is Hashtable is synchronized
while HashMap is not.
Example of Hashtable
import java.util.*;
class HashTableDemo
{
public static void main(String
args[])
{
Hashtable< String,Integer> ht =
new Hashtable< String,Integer>();
ht.put("a",new Integer(100));
ht.put("b",new Integer(200));
ht.put("c",new Integer(300));
ht.put("d",new Integer(400));
Set st = ht.entrySet();
Iterator itr=st.iterator();
while(itr.hasNext())
{
Map.Entry
m=(Map.Entry)itr.next();
System.out.println(itr.getKey()+"
"+itr.getValue());
}
}
}
Output:
a 100
b 200
c 300
d 400
HashMap
HastMap is not
synchronize.
HashMap works
faster.
}
}
Output
Java was created by James Ghosling
C++ was created by Bjarne Stroustrup
C was created by Dennis Ritchie
C# was created by Microsoft Inc
Applet in Java
A Simple Applet
import java.awt.*;
import java.applet.*;
public class Simple extends Applet
Advantages of Applets
1. Very less response time as it works
on the client side.
2. Can be run using any browser, which
has JVM running in it.
Applet class
{
public void destroy()
{
//perform shutdown activity
}
public void paint (Graphics g)
{
//display the content of window
}
Example of an Applet
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
int height, width;
public void init()
{
height = getSize().height;
width = getSize().width;
setName("MyApplet");
}
public void paint(Graphics g)
{
g.drawRoundRect(10, 30, 120, 120,
2, 3);
}
}
Event Handling
Any program that uses GUI (graphical user
interface) such as Java application written
for windows, is event driven. Event
describes the change of state of any object.
Example : Pressing a button, Entering a
character in Textbox.
ActionEven
t
MouseEven
t
ItemEvent
TextEvent
Description
Listener
Interface
generated
when button
is pressed,
menu-item is ActionListener
selected, listitem is double
clicked
generated
when mouse
is dragged,
moved,clicke
d,pressed or MouseListener
released also
when the
enters or exit
a component
generated
when input is
KeyListener
received from
keyboard
generated
when checkbox or list
ItemListener
item is
clicked
generated
TextListener
when value of
textarea or
textfield is
changed
generated
MouseWhe when mouse MouseWheelLi
elEvent
wheel is
stener
moved
generated
when window
is activated,
WindowEve deactivated, WindowListene
nt
deiconified, r
iconified,
opened or
closed
generated
when
component is
Component
ComponentEve
hidden,
Event
ntListener
moved,
resized or set
visible
generated
when
ContainerE component is ContainerListen
vent
added or
er
removed from
container
generated
Adjustment when scroll AdjustmentList
Event
bar is
ener
manipulated
generated
when
component
FocusEvent
FocusListener
gains or loses
keyboard
focus
java.awt.*;
java.awt.event.*;
java.applet.*;
java.applet.*;
java.awt.event.*;
java.awt.*;
AWT
AWT Hierarchy
Panel
Panel class is concrete sub class of
Container. Panel does not contain title bar,
menu bar or border.
Window class
Window class creates a top level window.
Window does not have borders and
menubar.
Frame
Component class
Component class is at the top of AWT
hierarchy. Component is an abstract class
that encapsulates all attribute of visual
component. A component object is
responsible for remembering the current
foreground and background colours and the
currently selected text font.
Container
Creating a Frame
There are two ways to create a Frame. They
are,
1.By Instantiating
Frame class
2.By extending
Frame class
Creating Frame Window by Instantiating
Frame class
import java.awt.*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame();
//Creating a frame.
Label lb = new Label("welcome to
java graphics");
//Creating a
label
fm.add(lb);
//adding label to the frame.
fm.setSize(300, 300);
//setting frame size.
fm.setVisible(true);
//set frame visibilty true.
}
public static void main(String
args[])
{
Testawt ta = new Testawt();
}
}
//set
}
public static void main (String[]
args)
{
Testawt ta = new Testawt();
//creating a frame.
}
}
1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
Features of JFC
Swing
Swing Framework contains a set of classes
that provides more powerful and flexible
GUI components than those of AWT. Swing
provides the look and feel of modern Java
GUI. Swing library is an official Java GUI
tool kit released by Sun Microsystems. It is
used to create graphical user interface with
Java.
Java 2D.
Creating a JFrame
There are two way to create a JFrame
Window.
1. By instantiating JFrame class.
2. By extending JFrame class.
import javax.swing.*;
import java.awt.*;
public class First
{
JFrame jf;
public First() {
jf = new JFrame("MyWindow");
//Creating a JFrame with name
MyWindow.
JButton btn = new JButton("Say
Hello");
//Creating a Button.
jf.add(btn);
//adding button to frame.
jf.setLayout(new FlowLayout());
//setting layout using FlowLayout
object.
jf.setDefaultCloseOperation(JFrame.E
XIT_ON_CLOSE); //setting close
operation.
jf.setSize(400, 400);
//setting size
jf.setVisible(true);
//setting frame visibilty
}
public static void main(String[]
args)
new First();
setSize(400, 400);
//setting size
setVisible(true);
//setting frame visibilty
}
public static void main(String[]
args)
{
new Second();
}
}
Swing Component
Swing Framework contains a large set of
components which provide rich
functionalities and allow high level of
customization. All these components are
lightweight components. They all are
derived from JComponent class. It supports
the pluggable look and feel.
JButton
javax.swing.*;
java.awt.event.*;
java.awt.*;
class testswing extends
testswing()
{
JButton bt1 = new JButton("Yes");
//Creating a Yes Button.
JButton bt2 = new JButton("No");
//Creating a No Button.
setDefaultCloseOperation(JFrame.EXIT
_ON_CLOSE)
//setting close
operation.
setLayout(new FlowLayout());
//setting layout using FlowLayout
object
setSize(400, 400);
//setting size of Jframe
add(bt1);
//adding Yes
button to frame.
add(bt2);
//adding No
button to frame.
setVisible(true);
}
public static void main(String[]
args)
{
new testswing();
}
}
JTextField
JTextField is used for taking input of single
line of text. It is most widely used text
component. It has three constructors,
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
JCheckBox
JCheckBox class is used to create
checkboxes in frame. Following is
constructor for JCheckBox,
JCheckBox(String str)
JRadioButton
JComboBox
Combo box is a combination of text fields
and drop-down list.JComboBox component
is used to create a combo box in Swing.
Following is the constructor for
JComboBox,
JComboBox(String arr[])
new Test();
Uses of Reflection
Reflection API
Developing IDE
Disadvantages of Reflection
Low performance
Security risk
java.lang.Class class
Some Important Classes of
java.lang.reflect package
Class
Array
What it does ?
allow you to dynamically create
forName()
This method takes fully qualified name of
classes or interface as its argument and
returns instance of the class assocaited with
it. Syntax
static Class< ?> forName(String
className)
getConstructors() and
getDeclaredConstructors()
method returns array
of Constructors object that represent all the
public constructors of the invoking object.
Remember, this method only returns public
constructors. If you want to see all the
getConstructors()
}
}
Output :
public Student()
public Student()
Student(java.lang.String)
getDeclaredMethods()
import java.lang.reflect.*;
class Student
{
public String name;
int roll;
}
class Test
{
public static void main(String
args[])
{
try
{
Class c =
Class.forName("Student");
Field ff[] = c.getFields();
for(int i=0; i< ff.length; i++)
{ System.out.println(ff[i]); }
Field f[] =
c.getDeclaredFields();
for(int i=0;i< f.length; i++)
{ System.out.println(f[i]); }
}
catch(Exception e)
{ e.printStackTrace();}
}
}
Output :
public java.lang.String
Student.name
public java.lang.String
Student.name
int Student.roll
RMI
getFields()
import java.rmi.*;
import java.rmi.server.*;
public class Adder extends
UnicastRemoteObject implements
AddServerInterface
{
Adder()throws RemoteException{
super();
}
public int sum(int a,int b)
{
return a+b;
}
}
AddServerInterface
st=(AddServerInterface)Naming.lookup
("rmi://"+args[0]+"/AddService");
System.out.println(st.sum(25,8));
}catch(Exception e)
{System.out.println(e);}
}
}
import java.rmi.*;
import java.rmi.registry.*;
public class AddServer{
public static void main(String
args[]){
try{
AddServerInterface addService=new
Adder();
Naming.rebind("AddService",addServic
e);
//addService object is hosted with
name AddService.
}catch(Exception e)
{System.out.println(e);}
}
}
Introduction to JDBC
Java Database Connectivity(JDBC) is an
Application Programming Interface(API)
used to connect Java application with
Database. JDBC is used to interact with
various type of Database such as Oracle, MS
Access, My SQL and SQL Server. JDBC
can also be defined as the platformindependent interface between a relational
database and Java programming. It allows
java program to execute SQL statement and
retrieve result from database.
JDBC Driver
JDBC Driver is required to process SQL
requests and generate result. The following
are the different types of driver available in
JDBC.
JDBC-ODBC bridge
Connection Management
Advantage
Easy to use
Disadvantage
Disadvantage
Advantage
Advantage
Database Independency.
Disadvantage
Thin Driver
1. java.sql
2. javax.sql
java.sql package
This package include classes and interface to
perform almost all JDBC operation such as
creating and executing SQL Queries.
Advantage
Disadvantage
Description
Provide
support for
java.sql.BLOB
BLOB(Binary
Large Object)
SQL type.
creates a
connection
java.sql.Connection
with specific
database
java.sql.CallableStatem Execute stored
ent
procedures
Provide
support for
CLOB(Charact
java.sql.CLOB
er Large
Object) SQL
type.
java.sql.Date
Provide
support for
Date SQL
type.
create an
instance of a
java.sql.Driver
driver with the
DriverManager
.
This class
manages
java.sql.DriverManager
database
drivers.
Used to create
java.sql.PreparedStatem and execute
ent
parameterized
query.
It is an
interface that
provide
java.sql.ResultSet
methods to
access the
result row-byrow.
Specify
java.sql.Savepoint
savepoint in
transaction.
Encapsulate all
java.sql.SQLException JDBC related
exception.
This interface
is used to
java.sql.Statement
execute SQL
statements.
classes/interface
Description
Provide
information
javax.sql.ConnectionEve
about
nt
occurence of
event.
Used to
register event
javax.sql.ConnectionEve
generated by
ntListener
PooledConne
ction object.
Represent the
DataSource
javax.sql.DataSource
interface used
in an
application.
provide object
javax.sql.PooledConnect to manage
ion
connection
pools.
javax.sql package
Syntax
public Statement createStatement()
throws SQLException
class explicitly.
Example to register with JDBC-ODBC
Driver
Class.forName("sun.jdbc.odbc.JdbcOdb
cDriver");
Create a Connection
method of
DriverManager class is used to create a
connection.
getConnection()
Syntax
getConnection(String url)
getConnection(String url, String
username, String password)
getConnection(String url, Properties
info)
Statement s=con.createStatement();
Syntax
public ResultSet executeQuery(String
query) throws SQLException
2. Go to Administrative tools
Example
We suppose that you have created a student
table with sid and name column name in
access database.
import java.sql.*;
class Test
{
public static void main(String
[]args)
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdb
cDriver");
Connection con =
DriverManager.getConnection("jdbc:od
bc:Test", "", "");
Statement s=con.createStatement();
//creating statement
ResultSet rs=s.executeQuery("select
* from student");
//executing
statement
while(rs.next()){
System.out.println(rs.getInt(1)+"
"+rs.getString(2));
}
con.close();
//closing connection
}catch(Exception e)
{
e.printStackTrace();
}
}
}
folder.
or,
Example
Create a table in Oracle Database
create table Student(sid
number(10),sname varchar2(20));
import java.sql.*;
class Test
{
public static void main(String
[]args)
{
try{
//Loading driver
Class.forName("oracle.jdbc.driver.Or
acleDriver");
//creating connection
Connection con =
DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:X
E","username","password");
Statement s=con.createStatement();
//creating statement
ResultSet rs=s.executeQuery("select
* from Student");
//executing
statement
while(rs.next()){
System.out.println(rs.getInt(1)+"
"+rs.getString(2));
}
con.close();
//closing connection
}catch(Exception e){
e.printStacktrace();
}
}
}
Output
101 adam
102 abhi
//creating connection...
Connection con =
DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:X
E","username","password");
PreparedStatement
pst=con.prepareStatement("insert
into Student values(?,?)");
pst.setInt(1,104);
pst.setString(2,"Alex");
pst.executeUpdate();
con.close();
//closing connection
}catch(Exception e){
e.printStacktrace();
}
}
}
folder.
or,
Example
Create a table in MySQL Database
create table Student(sid
int(10),name varchar(20));
import java.sql.*;
class Test
{
public static void main(String
[]args)
{
try{
//Loading driver
Class.forName("com.mysql.jdbc.Driver
");
//creating connection
Connection con =
DriverManager.getConnection
("jdbc:mysql://localhost:3306/test",
"username","password");
Statement s = con.createStatement();
//creating statement
ResultSet rs =
s.executeQuery("select * from
Student");
//executing
statement
while(rs.next()){
System.out.println(rs.getInt(1)+"
"+rs.getString(2));
}
con.close();
//closing connection
}catch(Exception e){
e.printStacktrace();
}
}
}
Output
102 adam
103 abhi
import java.sql.*;
class Test
{
public static void main(String
[]args)
{
try{
//Loading driver
Class.forName("com.mysql.jdbc.Driver
");
//creating connection
Connection con =
DriverManager.getConnection
("jdbc:mysql://localhost:3306/test",
"username","password");
PreparedStatement
pst=con.prepareStatement("insert
into Student values(?,?)");
pst.setInt(1,104);
pst.setString(2,"Alex");
pst.executeUpdate();
con.close();
//closing connection
}catch(Exception e){
e.printStacktrace();
}
}
}
Usage
Basic usage
Evaluating expressions
Implicit multiplication
Complex numbers
Using Vectors
Using Strings
Custom types
Manipulating expressions
10. myParser.parseExpression(ExpressionString
result = myParser.getValue();
Basic usage
Using the JEP package of classes in your project is simple. The following steps will get you
started quickly.
1. Download the JEP package from the
2. Unpack the archive
Evaluating expressions
4. IMPORTANT: For the Java compiler to be able to find the JEP classes when
getComplexValue():
Use
this if you are expect
compiling your program, it needs to know their
location. So you will
need
to add the location of the .jar file to your CLASSPATH environment
variable (if you don't know how, read this getValueAsObject(): Returns the result as an O
should contain something like C:\java\packages\jep-x.xx.jar, depending
The first two methods call getValueAsObject() internally, an
on where you place the jar file.
Using Vectors
4, to
5]*2
A list of all the variables and constants that have been[3,
added
the parser, can be obtained
It would be evaluated as [6, 8, 10] by JEP. To add a vector as
with the getSymbolTable() method.
addVariableAsObject() method. If the result of an expression
by calling
theisgetValueAsObject()
This method is most useful when the undeclared variables
option
enabled. After an function.
expression has been parsed, a list of all variables occurring in that expression can be
obtained using the getSymbolTable() method. The return value is a SymbolTable object.
order to be able to this, you will need direct access to the exp
Using Strings
ASTFunNode
and operators
Strings can be entered in an expression by using double quotes.
They can be- Functions
concatenated
with the + operator and compared with the == and != relational operators. A sample
ASTConstant - Constants
expression involving the string type is "foo" + "bar" == "foobar", which would be evaluated
by JEP as 1 (true).
ASTVarNode - Variables
Custom types
In most cases, you will only need to work with the few built in types that JEP supplies
(Double, Complex, Vector, String). But suppose you want to evaluate expressions that
involve other types. This is possible by using the
variables of any type. The only place where the type of a variable matters, is in the function
classes.
Using custom number classes
Manipulating expressions
The getTopNode() method can be used to get the expression tree after parsing an
expression. This will be useful if you want to do more than just evaluate the expressions
you parse. For example, you may want to determine the derivative of an expression. In
Factory methods
LogManager.getLogManager
Pattern.compile
Collections.unmodifiableCollect
ion,
Collections.synchronizeCollecti
on , and so on
Calendar.getInstance
Factory methods:
Example
public final class ComplexNumber {
/**
* Static factory method returns an
object of this class.
*/
public static ComplexNumber
valueOf(float aReal, float
aImaginary) {
return new ComplexNumber(aReal,
aImaginary);
}
/**
* Caller cannot see this private
constructor.
*
* The only way to build a
ComplexNumber is by calling the
static
* factory method.
*/
private ComplexNumber(float aReal,
float aImaginary) {
fReal = aReal;
fImaginary = aImaginary;
}
private float fReal;
private float fImaginary;
}
//..elided
Factory Method
Definition
Provides an abstraction or an interface and
lets subclass or implementing classes decide
which class or method should be instantiated
or called, based on the conditions or
parameters given.
Examples
To illustrate such concept, let's use a simple
example. To paint a picture, you may need
several steps. A shape is an interface.
Several implementing classes may be
designed in the following way.
interface Shape {
public void draw();
}
class Line implements Shape {
Point x, y;
Line(Point a, Point b) {
x = a;
y = b;
}
public void draw() {
//draw a line;
}
}
class Square implements Shape {
Point start;
int width, height;
Square(Point s, int w, int h) {
start = s;
width = w;
height = h;
}
public void draw() {
//draw a square;
}
}
class Circle implements Shape {
....
}
class Painting {
Point x, y;
int width, height, radius;
Painting(Point a, Point b, int w,
int h, int r) {
x = a;
y = b;
width = w;
height = h;
radius = r;
}
Shape drawLine() {
return new Line(x,y);
}
Shape drawSquare() {
return new Square(x, width,
height);
}
Shape drawCircle() {
return new Circle(x, radius);
}
....
}
...
Shape pic;
Painting pt;
//initializing pt
....
if (line)
pic = pt.drawLine();
if (square)
pic = pt.drawSquare();
if (circle)
pic = pt.drawCircle();
System.out.println("load
from an xml file");
}
public void formatConsistency()
{
System.out.println("xml file
format changed");
}
}
//deal with binary format file
class DBFile implements Display {
{
public
System.out.println("load
from a db file");
}
public void formatConsistency()
{
System.out.println("db file
format changed");
}
}
//Test the functionality
class TestFactory {
public static void main(String[]
args) {
Display display = null;
//use a command line data as
a trigger
if (args[0].equals("1"))
display = new CSVFile();
else if
(args[0].equals("2"))
display = new XMLFile();
else if
(args[0].equals("3"))
display = new DBFile();
else
System.exit(1);
//converging code follows
display.load("");
display.formatConsistency();
}
}
//after compilation and run it
C:\>java TestFactory 1
load from a txt file
txt file format changed
C:\>java TestFactory 2
load from an xml file
xml file format changed
C:\>java TestFactory 3
load from a db file
db file format changed
Introduction
Java is an object-oriented language and can
view everything as an object. A simple file
can be treated as an object (with
java.io.File), an address of a system can be
int m = it1.intValue();
System.out.println(m*m); // prints 10000
intValue() is a method of Integer class that
returns an int data type.
List of Wrapper classes
In the above code, Integer class is known as
a wrapper class (because it wraps around int
data type to give it an impression of object).
To wrap (or to convert) each primitive data
type, there comes a wrapper class. Eight
wrapper classes exist in java.lang package
that represent 8 data types. Following list
gives.
Primitive data type
byte
short
int
long
float
double
char
boolean
Wrapper class
Byte
Short
Integer
Long
Float
Double
Character
Boolean
20
21
22
23
24
25
26
27
28
29
30
31 // let us print the values from
32 data types
System.out.println("Unwrapped
values (printing as data
types)");
System.out.println("byte
value, bv: " + bv);
System.out.println("int
value, iv: " + iv);
System.out.println("float
value, fv: " + fv);
System.out.println("double
value, dv: " + dv);
}
}
Description
Each of Java's eight primitive data types has
a class dedicated to it. These are known as
wrapper classes, because they "wrap" the
primitive data type into an object of that
class. The wrapper classes are part of the
java.lang package, which is imported by
default into all Java programs.
The wrapper classes in java servers two
primary purposes.
To provide an assortment of
utility functions for primitives
like converting primitive types
to and from string objects,
converting to various bases like
binary, octal or hexadecimal, or
comparing various objects.
Constructor
Argument
boolea
Boolean
n
boolean or String
byte
Byte
byte or String
char
Character
char
int
Integer
int or String
float
Float
float, double or
String
double Double
double or String
long
Long
long or String
short
Short
short or String
Purpose
parseInt(s)
toString(i)
byteValue()
intValue()
shortValue()
longValue()
num2.
view plainprint?
1. package WrapperIntro;
2.
3. public class WrapperDemo {
4.
5.
6.
7.
8.
9.
//compareTo demo
10.
System.out.println("Compa
ring using compareTo Obj1 and
Obj2: " + intObj1.compareTo(int
Obj2));
11.
System.out.println("Compa
ring using compareTo Obj1 and
Obj3: " + intObj1.compareTo(int
Obj3));
12.
13.
//Equals demo
14.
System.out.println("Compa
ring using equals Obj1 and Obj2
: " + intObj1.equals(intObj2));
15.
System.out.println("Compa
ring using equals Obj1 and Obj3
: " + intObj1.equals(intObj3));
Output
16.
17.
18.
19.
20.
System.out.println("Compa
ring using compare f1 and f2: "
+Float.compare(f1,f2));
21.
System.out.println("Compa
ring using compare f1 and f3: "
+Float.compare(f1,f3));
22.
23.
2.
oat
24.
Float f = intObj1.floatValue
() + f1;
4.
25.
System.out.println("Additio
n of intObj1 and f1: "+ intObj1
+"+" +f1+"=" +f );
26.
27.
28.}
5.
6.
7.
8.
9.
10.
17.
18.}
11.
12.
System.out.println("Value o
f intWrapper Object: "+ intWrap
per);
13.
System.out.println("Value o
f intWrapper2 Object: "+ intWra
pper2);
14.
System.out.println("Value o
f intWrapper3 Object: "+ intWra
pper3);
15.
System.out.println("Hex va
lue of intWrapper: " + Integer.to
HexString(intWrapper));
16.
System.out.println("Binary
Value of intWrapper2: "+ Integer
.toBinaryString(intWrapper2));
Output