Core Java Full Notes by kiran @satya technologies
Core Java Full Notes by kiran @satya technologies
Core Java
Core Java
Java technology is widely used currently. Let's start learning of java from basic questions like
what is java, where it is used, what type of applications are created in java and why use java?
What is Java?
Java is a programming language and a platform.
Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is currently
used. Some of them are as follows:
1) Standalone Application
2) Web Application
An application that runs on the server side and creates dynamic page, is called web
application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web
applications in java.
An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for
creating enterprise applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used
for creating mobile applications.
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 (i.e.JVM is plateform
dependent).
JRE
JRE is an acronym 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.
Implementation of JVMs are also actively released by other companies besides Sun Micro
Systems.
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.
JVMs are available for many hardware and software platforms (i.e.JVM is plateform
dependent).
1) Classloader:
Classloader is a subsystem of JVM that is used to load class files.
2) Class(Method) Area:
Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.
3) Heap:
It is the runtime data area in which objects are allocated.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its
method invocation completes.
7) Execution Engine:
It contains:
1) A virtual processor
Bytecode Verifier: checks the code fragments for illegal code that can violate accesss
right to objects.
Q)Can you save a java source file by other name than the class
name?
Yes, like the figure given below illustrates:
Unicode System
Unicode is a universal international standard character encoding that is capable of
representing most of the world's written languages.
• ASCII (American Standard Code for Information Interchange) for the United
States.
• ISO 8859-1 for Western European Language.
• KOI-8 for Russian.
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF
History of Java
Java history is interesting to know. Java team members (also known as Green Team),
initiated a revolutionary task to develop a language for digital devices such as set-top boxes,
televisions etc.
At that time, it was a advanced concept for the green team. But, it was good for internet
programming. Later, Netscape Navigator incorporated Java technology.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions
etc. Let's see the major points that describes the history of java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top
boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries
like U.S.A., France, Germany, Romania etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
7) Why they choosed java name for java language? The team gathered to choose a new
name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They
According to James Gosling "Java was one of the top choices along with Silk". Since java
was so unique, most of the team members preferred java.
8) Java is an island of Indonesia where first coffee was produced (called java coffee).
10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary
of Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
Features of Java
There is given many features of java. They are also called java buzzwords.
1.Simple
2.Object-oriented
3.Platform independent
4.Secured
5.Robust
7.Portable
8.Dynamic
9.Interpreted
10.High Performance
11.Multithreaded
12.Distributed
Simple
Java is simple in the sense that:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
Object-oriented
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behaviour.
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
A platform is the hardware or software environment in which a program runs. There are
two types of platforms software-based and hardware-based. Java provides software-based
platform. The Java platform differs from most other platforms in the sense that it's a
software-based platform that runs on top of other hardware-based platforms.It has two
components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code
can be run
on multiple
platforms
e.g.Windo
ws,Linux,S
un
Solaris,Ma
c/OS etc.
Java code
is
compiled by the compiler and converted into bytecode.This bytecode is a platform
independent code because it can be run on multiple platforms i.e. Write Once and Run
Anywhere(WORA).
Secured
Java is secured because:
• No explicit pointer
• Programs run inside virtual machine sandbox.
• Classloader- adds security by separating the package for the classes of the local
file system from those that are imported from network sources.
• Bytecode Verifier- checks the code fragments for illegal code that can violate
accesss right to objects.
• Security Manager- determines what resources a class can access such as reading
and writing to the local disk.
These security are provided by java language. Some sucurity can also be provided by
application developer through SSL,JAAS,cryptography etc.
Robust
Robust simply means strong. Java uses strong memory management. There are lack of
pointers that avoids security problem. There is automatic garbage collection in java. There
is exception handling and type checking mechanism in java. All these points makes java
robust.
Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is set.
Portable
We may carry the java bytecode to any platform.
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still
Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any machine on
the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it shares the same memory. Threads are important for multi-media,
Web applications etc.
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java")
4. }
5. }
Output:Hello Java
To write the simple program, open notepad and write simple program as displayed below:
As displayed in the above diagram, write the simple program of java in notepad and saved
it as Simple.java. To compile and run this program, you need to open command prompt by
start -> All Programs -> Accessories -> command prompt.
Bytecode Verifier: checks the code fragments for illegal code that can violate accesss
right to objects.
Q)Can you save a java source file by other name than the class
name?
Yes, like the figure given below illustrates:
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
• Go to MyComputer properties -> advanced tab -> environment variables -> new tab
of user variable -> write path in variable name -> write path of bin folder in variable
value -> ok -> ok -> ok
For Example:
1)Go to MyComputer properties
8)click on ok button
9)click on ok button
Now your permanent path is set.You can now execute any program of java from any drive.
export PATH=$PATH:/home/jdk1.6.01/bin/
Here, we have installed the JDK in the home directory under Root (/home).
Variable
Variable is name of reserved area allocated in memory.
Types of Variable
There are three types of variables in java
• local variable
• instance variable
• static variable
Local Variable
Instance Variable
A variable that is declared inside the class but outside the method is called instance
variable . It is not declared as static.
Static variable
class A{
void method(){
int n=90;//local variable
}
}//end of class
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
because java uses unicode system rather than ASCII code system. \u0000 is the lowest
range of unicode system.To get detail about Unicode see below.
Unicode System
Unicode is a universal international standard character encoding that is capable of
representing most of the world's written languages.
• ASCII (American Standard Code for Information Interchange) for the United States.
• ISO 8859-1 for Western European Language.
• KOI-8 for Russian.
• GB18030 and BIG-5 for chinese, and so on.
Precedence of Operators
Operators Precedence
multiplicative */%
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
ternary ?:
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF
Operators in java
Operator is a special symbol that is used to perform operations. There are many types of
operators in java such as unary operator, arithmetic operator, relational operator, shift
operator, bitwise operator, ternary operator and assignment operator.
Useful Programs:
There is given some useful programs such as factorial number, prime number, fibonacci
series etc.
}
}
}
}
}
}
System.out.println("a= "+a);
System.out.println("b= "+b);
}
}
return n*=fact(n-1);
}
int f=fact(5);
System.out.println(f);
}
}
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known
as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example:
to convense the customer differently, to draw something e.g. shape or rectangle etc.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
3)OOPs provides ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented
Programming language.
• Advantage of OOPs
• Naming Convention
• Object and class
• Method overloading
• Constructor
By using standard Java naming conventions they make their code easier to read for
themselves and for other programmers. Readability of Java code is important because it
means less time is spent trying to figure out what the code does.
Name Convension
class name should begin with uppercase letter and be a noun e.g.String,System,Thread etc.
Interface should begin with uppercase letter and be an adjective (whereever possible). e.g.
name Runnable,ActionListener etc.
method name should begin with lowercase letter and be a verb. e.g.
main(),print(),println(),actionPerformed() etc.
Object
A runtime entity that has state and behaviour is known as an object. For example: chair, table,
pen etc. It can be tengible or intengible (physical or logical).
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state.
It is used to write, so writing is its behaviour.
Class
A class is a group of objects that have common property. It is a template or blueprint from
which objects are created.
1. class Student{
2. int id;//data member (also instance variable)
3. String name;//data member(also instance variable)
4.
5. public static void main(String args[]){
6. Student s1=new Student();//creating an object of Student
7. System.out.println(s1.id+" "+s1.name);
8.
9. }
10. }
Output:0 null
Instance variable
A variable that is created inside the class but outside the method, is known as instance
variable.Instance variable doesn't get memory at compile time.It gets memory at runtime
when object(instance) is created.That is why, it is known as instance variable.
Advantage of Method
• Code Reusability
• Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.
1. class Student{
2. int rollno;
3. String name;
4.
5. void insertRecord(int r, String n){ //method
6. rollno=r;
7. name=n;
8. }
9.
10. void displayInformation(){System.out.println(rollno+" "+name);}//method
11.
12. public static void main(String args[]){
13. Student s1=new Student();
14. Student s2=new Student();
15.
16. s1.insertRecord(111,"Karan");
17. s2.insertRecord(222,"Aryan");
18.
19. s1.displayInformation();
20. s2.displayInformation();
21.
22. }
23. }
Output:111 Karan
222 Aryan
As you see in the above figure, object gets the memory in Heap area and reference
variable refers to the object allocated in the Heap memory area. Here, s1 and s2 both are
reference variables that refer to the objects allocated in memory.
1. class Rectangle{
2. int length;
3. int width;
4.
5. void insert(int l,int w){
6. length=l;
7. width=w;
8. }
9.
10. void calculateArea(){System.out.println(length*width);}
11.
12. public static void main(String args[]){
13. Rectangle r1=new Rectangle();
14. Rectangle r2=new Rectangle();
15.
16. r1.insert(11,5);
17. r2.insert(3,15);
18.
19. r1.calculateArea();
20. r2.calculateArea();
21. }
22. }
Output:55
45
Annonymous object
Annonymous simply means nameless.An object that have no reference is known as
annonymous object.
If you have to use an object only once, annonymous object is a good approach.
1. class Calculation{
2.
3. void fact(int n){
4. int fact=1;
5. for(int i=1;i<=n;i++){
6. fact=fact*i;
7. }
8. System.out.println("factorial is "+fact);
9. }
10.
11. public static void main(String args[]){
12. new Calculation().fact(5);//calling method with annonymous object
13. }
14. }
Output:Factorial is 120
1. class Rectangle{
2. int length;
3. int width;
4.
5. void insert(int l,int w){
6. length=l;
7. width=w;
8. }
9.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behaviour of the method because its name differs. So, we perform method overloading to
figure out the program quickly.
In this example, we have created two overloaded methods, first sum method performs
addition of two numbers and second sum method performs addition of three numbers.
1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10,10,10);
8. obj.sum(20,20);
9.
10. }
11. }
Output:30
40
1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(double a,double b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10.5,10.5);
8. obj.sum(20,20);
9.
10. }
11. }
Output:21.0
40
Que) Why Method Overloaing is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method
1. class Calculation{
2. int sum(int a,int b){System.out.println(a+b);}
3. double sum(int a,int b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. int result=obj.sum(20,20); //Compile Time Error
8.
9. }
10. }
int result=obj.sum(20,20); //Here how can java determine which sum() method should be
called
Yes, by method overloading. You can have any number of main methods in a class by
method overloading. Let's see the simple example:
1. class Simple{
2. public static void main(int a){
3. System.out.println(a);
4. }
5.
6. public static void main(String args[]){
7. System.out.println("main() method invoked");
8. main(10);
9. }
10. }
Output:main() method invoked
10
As displayed in the above diagram, byte can be promoted to short, int, long, float or
double. The short datatype can be promoted to int,long,float or double. The char datatype
can be promoted to int,long,float or double and so on.
1. class Calculation{
2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b){System.out.println("long arg method invoked");}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
1. class Calculation{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(20,20);//now ambiguity
8. }
9. }
Output:Compile Time Error
Constructor in Java
Constructor is a special type of method that is used to initialize the object.
Constructor is invoked at the time of object creation. It constructs the values i.e. provides
data for the object that is why it is known as constructor.
Types of constructors
1) Default Constructor
A constructor that have no parameter is known as default constructor.
1. class Bike{
2.
3. Bike(){System.out.println("Bike is created");}
4.
5. public static void main(String args[]){
6. Bike b=new Bike();
7. }
8. }
Output: Bike is created
Default constructor provides the default values to the object like 0, null etc. depending on the
type.
Explanation:In the above class,you are not creating any constructor so compiler provides
you a default constructor.Here 0 and null values are provided by default constructor.
Parameterized constructor
A constructor that have parameters is known as parameterized constructor.
1. class Student{
2. int id;
3. String name;
4.
5. Student(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
Constructor Method
Constructor is used to initialize the state of an object. Method is used to expose behaviour of an
object.
Constructor must not have return type. Method must have return type.
The java compiler provides a default constructor if you don't Method is not provided by compiler in
have any constructor. any case.
Constructor name must be same as the class name. Method name may or may not be same as
class name.
In this example, we are going to copy the values of one object into another using
constructor.
1. class Student{
2. int id;
3. String name;
4. Student(int i,String n){
5. id = i;
6. name = n;
7. }
8.
9. Student(Student s){
10. id = s.id;
11. name =s.name;
12. }
13. void display(){System.out.println(id+" "+name);}
14.
15. public static void main(String args[]){
16. Student s1 = new Student(111,"Karan");
1. class Student{
2. int id;
3. String name;
4. Student(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student(){}
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student s1 = new Student(111,"Karan");
13. Student s2 = new Student();
14. s2.id=s1.id;
15. s2.name=s1.name;
16. s1.display();
17. s2.display();
18. }
19. }
Output:111 Karan
111 Karan
Que)Does constructor return any value?
Ans:yes,that is current class instance (You cannot use return type yet it returns a value).
Yes, like object creation, starting a thread, calling method etc. You can perform any operation
in the constructor as you perform in the method.
static keyword
1) static variable
If you declare any variable as static, it is known static variable.
• The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of students
etc.
• The static variable gets memory only once in class area at the time of class loading.
Suppose there are 500 students in my college, now all instance data members will get
memory each time when object is created.All student have its unique rollno and name so
instance data member is good.Here, college refers to the common property of all objects.If
we make it static,this field will get memory only once.
1. class Counter{
2. int count=0;//will get memory when instance is created
3.
4. Counter(){
5. count++;
6. System.out.println(count);
7. }
8.
9. public static void main(String args[]){
10.
1. class Counter{
2. static int count=0;//will get memory only once and retain its value
3.
4. Counter(){
5. count++;
6. System.out.println(count);
7. }
8.
9. public static void main(String args[]){
10.
11. Counter c1=new Counter();
12. Counter c2=new Counter();
13. Counter c3=new Counter();
14.
15. }}
Output:1
2
3
2) static method
If you apply static keyword with any method, it is known as static method.
1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
Output:Compile Time Error
Que)why main method is static?
Ans) because object is not required to call static method if it were non-static method, jvm
creats object first then call main() method that will lead the problem of extra memory
allocation.
3)static block
• Is used to initialize the static data member.
• It is excuted before main method at the time of classloading.
1. class A{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
Output:static block is invoked (if not JDK7)
this keyword
There can be a lot of usage of this keyword. In java, this is a reference variable that refers
to the current object.
Suggestion:If you are beginner to java, lookup only two usage of this keyword.
1. class student{
2. int id;
3. String name;
4.
5. student(int id,String name){
6. id = id;
7. name = name;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
1. class Student{
2. int id;
3. String name;
4. String city;
5.
6. Student(int id,String name){
7. this.id = id;
8. this.name = name;
9. }
10. Student(int id,String name,String city){
11. this(id,name);//now no need to initialize id and name
12. this.city=city;
13. }
14. void display(){System.out.println(id+" "+name+" "+city);}
15.
16. public static void main(String args[]){
17. Student e1 = new Student(111,"karan");
18. Student e2 = new Student(222,"Aryan","delhi");
19. e1.display();
20. e2.display();
21. }
22. }
Output:111 Karan null
222 Aryan delhi
1. class S{
2. void m(){
3. System.out.println("method is invoked");
4. }
5. void n(){
6. this.m();//no need because compiler does it for you.
7. }
8. void p(){
9. n();//complier will add this to invoke n() method as this.n()
10. }
11. public static void main(String args[]){
12. S s1 = new S();
13. s1.p();
14. }
15. }
Output:method is invoked
1. class S{
2. void m(S obj){
3. System.out.println("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8.
9. public static void main(String args[]){
10. S s1 = new S();
11. s1.p();
12. }
13. }
Output:method is invoked
Application of this that can be passed as an argument:
In event handling (or) in a situation where we have to provide reference of a class to
another one.
1. class B{
2. A obj;
3. B(A obj){
4. this.obj=obj;
5. }
6. void display(){
7. System.out.println(obj.data);//using data member of A class
8. }
9. }
10.
11. class A{
12. int data=10;
13. A(){
14. B b=new B(this);
15. b.display();
16. }
17. public static void main(String args[]){
18. A a=new A();
19. }
20. }
Output:10
1. class A{
2. void m(){
3. System.out.println(this);//prints same reference ID
4. }
5.
6. public static void main(String args[]){
7. A obj=new A();
8. System.out.println(obj);//prints the reference ID
9.
10. obj.m();
11. }
12. }
Output:A@13d9c02
A@13d9c02
Inheritance in Java
Kiran Sir 9866243099 Page 61
Core Java
Inheritance is a mechanism in which one object acquires all the properties and behaviours of
parent object.
The idea behind inheritance is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you reuse (or inherit) methods and fields,
and you add new methods and fields to adapt your new class to new situations.
Syntax of Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
The keyword extends indicates that you are making a new class that derives from an
existing class. In the terminology of Java, a class that is inherited is called a superclass.
The new class is called a subclass.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer
is a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4.
5. class Programmer extends Employee{
In the above example,Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
Types of Inheritance
On the basis of class, there can be three types of inheritance: single, multilevel and
hierarchical.
Multiple and Hybrid is supported through interface only. We will learn about interfaces later.
When a class extends multiple classes i.e. known as multiple inheritance. For Example:
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4.
5. class B{
6. void msg(){System.out.println("Welcome");}
7. }
8.
9. class C extends A,B{//suppose if it were
10.
11. Public Static void main(String args[]){
12. C obj=new C();
13. obj.msg();//Now which msg() method would be invoked?
14. }
15. }
Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-
A relationship.
Consider a situation, Employee object contains many informations such as id, name, emailId
etc. It contains one more object named address, which contains its own informations such as
city, state, country, zipcode etc. as given below.
1. class Employee{
2. int id;
3. String name;
4. Address address;//Address is a class
5. ...
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
In this example, we have created the reference of Operation class in the Circle class.
1. class Operation{
2. int square(int n){
3. return n*n;
4. }
5. }
6.
7. class Circle{
8. Operation op;//aggregation
9. double pi=3.14;
10.
11. double area(int radius){
12. op=new Operation();
13. int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
14. return pi*rsquare;
15. }
16.
17.
18.
19. public static void main(String args[]){
20. Circle c=new Circle();
21. double result=c.area(5);
22. System.out.println(result);
23. }
24. }
Output:78.5
Address.java
1. public class Address {
2. String city,state,country;
3.
4. public Address(String city, String state, String country) {
5. this.city = city;
6. this.state = state;
7. this.country = country;
8. }
9.
10. }
Emp.java
1. public class Emp {
2. int id;
3. String name;
4. Address address;
5.
6. public Emp(int id, String name,Address address) {
7. this.id = id;
8. this.name = name;
9. this.address=address;
10. }
11.
12. void display(){
13. System.out.println(id+" "+name);
14. System.out.println(address.city+" "+address.state+" "+address.country);
15. }
16.
17. public static void main(String[] args) {
18. Address address1=new Address("gzb","UP","india");
19. Address address2=new Address("gno","UP","india");
20.
21. Emp e=new Emp(111,"varun",address1);
22. Emp e2=new Emp(112,"arun",address2);
23.
24. e.display();
In other words, If subclass provides the specific implementation of the method i.e. already
provided by its parent class, it is known as Method Overriding.
Let's understand the problem that we may face in the program if we don't use method
overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike extends Vehicle{
5.
6. public static void main(String args[]){
7. Bike obj = new Bike();
8. obj.run();
9. }
10. }
Output:Vehicle is running
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6.
7. public static void main(String args[]){
8. Bike obj = new Bike();
9. obj.run();
10. }
Output:Bike is running safely
Can we override static method?
No, static method cannot be overridden. It can be proved by runtime polymorphism so we
will learn it later.
There are three basic differences between the method overloading and method overriding.
They are as follows:
1) Method overloading is used to Method overriding is used to provide the specific implementation
increase the readability of the program. of the method that is already provided by its super class.
2) method overlaoding is performed Method overriding occurs in two classes that have IS-A
within a class. relationship.
Access Modifiers
There are two types of modifiers in java: access modifier and non-access modifier. The
access modifiers specifies accessibility (scope) of a datamember, method, constructor or
class.
1. private
2. default
3. protected
4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.
1) private
The private access modifier is accessible only within class.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
1. class A{
2. private A(){}//private constructor
3.
4. void msg(){System.out.println("Hello java");}
5. }
6.
7. public class Simple{
8. public static void main(String args[]){
9. A obj=new A();//Compile Time Error
10. }
11. }
2) default
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.
1. //save by A.java
2.
3. package pack;
4. class A{
5. void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();//Compile Time Error
9. obj.msg();//Compile Time Error
Kiran Sir 9866243099 Page 70
Core Java
10. }
11. }
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. protected void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B extends A{
7. public static void main(String args[]){
8. B obj = new B();
9. obj.msg();
10. }
11. }
Output:Hello
4) public
The public access modifier is accessible everywhere. It has the widest scope among all
other modiers.
Access Modifier within class within package outside package by subclass only outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
If you are overriding any method, overriden method (i.e. declared in subclass) must not be
more restrictive.
1. class A{
2. protected void msg(){System.out.println("Hello java");}
3. }
4.
5. public class Simple extends A{
6. void msg(){System.out.println("Hello java");}//C.T.Error
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. obj.msg();
10. }
11. }
The default modifier is more restrictive than protected. That is why there is compile time
error.
2) Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but can declare unchecked exception.
1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg()throws ArithmeticException{
8. System.out.println("child");
9. }
10. public static void main(String args[]){
11. Parent p=new Child();
12. p.msg();
13. }
14. }
Output:child
Before Java5, it was not possible to override any method by changing the return type. But
now, since Java5, it is possible to override method by changing the return type if subclass
overrides any method whose return type is Non-Primitive but it changes its return type to
subclass type. Let's take a simple example:
As you can see in the above example, the return type of the get() method of A class is A but
the return type of the get() method of B class is B. Both methods have different return type
but it is method overriding. This is known as covariant return type.
super keyword
The super is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitely i.e. referred by super reference variable.
1. class Vehicle{
2. int speed=50;
3. }
4.
5. class Bike extends Vehicle{
6. int speed=100;
7.
8. void display(){
9. System.out.println(speed);//will print speed of Bike
10. }
11. public static void main(String args[]){
1. class Vehicle{
2. Vehicle(){System.out.println("Vehicle is created");}
3. }
4.
5. class Bike extends Vehicle{
6. Bike(){
7. super();//will invoke parent class constructor
8. System.out.println("Bike is created");
9. }
10. public static void main(String args[]){
11. Bike b=new Bike();
12.
As we know well that default constructor is provided by compiler automatically but it also
adds super() for the first statement.If you are creating your own constructor and you don't
have either this() or super() as the first statement, compiler will provide super() as the first
statement of the consructor.
Another example of super keyword where super() is provided by the compiler implicitely.
1. class Vehicle{
2. Vehicle(){System.out.println("Vehicle is created");}
3. }
4.
5. class Bike extends Vehicle{
6. int speed;
7. Bike(int speed){
8. this.speed=speed;
9. System.out.println(speed);
10. }
11. public static void main(String args[]){
12. Bike b=new Bike(10);
13. }
14. }
Output:Vehicle is created
10
1. class Person{
2. void message(){System.out.println("welcome");}
3. }
In case there is no method in subclass as parent, there is no need to use super. In the
example given below message() method is invoked from Student class but Student class
does not have message() method, so you can directly call message() method.
The initialization of the instance variable can be directly but there can be performed extra
operations while initilizing the instance variable in the instance initializer block.
Que) What is the use of instance initializer block while we can directly
assign a value in instance data member? For example:
1. class Bike{
2. int speed=100;
3. }
1. class Bike{
2. int speed;
3.
4. Bike(){System.out.println("speed is "+speed);}
5.
6. {speed=100;}
7.
8. public static void main(String args[]){
9. Bike b1=new Bike();
10. Bike b2=new Bike();
11. }
12. }
Output:speed is 100
speed is 100
There are three places in java where you can perform operations:
1. method
2. constructor
3. block
Note: The java compiler copies the code of instance initializer block in every
constructor.
1. The instance initializer block is created when instance of the class is created.
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of final
keyword.
1) final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
1. class Bike{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike obj=new Bike();
8. obj.run();
9. }
10. }//end of class
Output:Compile Time Error
2) final method
If you make any method as final, you cannot override it.
3) final class
If you make any class as final, you cannot extend it.
Ans) Yes, final method is inherited but you cannot override it. For Example:
1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda extends Bike{
5. public static void main(String args[]){
6. new Honda().run();
7. }
8. }
Output:running...
Q) What is blank or uninitialized final variable?
A final variable that is not initalized at the time of declaration is known as blank final
variable.
If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an
employee.
1. class Bike{
2. final int speedlimit;//blank final variable
3.
4. Bike(){
5. speedlimit=70;
A static final variable that is not initalized at the time of declaration is known as static blank
final variable. It can be initialized only in static block.
If you declare any parameter as final, you cannot change the value of it.
1. class Bike{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final
4. n*n*n;
5. }
6. public static void main(String args[]){
7. Bike b=new Bike();
8. b.cube(5);
9. }
10. }
Output:Compile Time Error
Q) Can we declare a constructor final?
Runtime Polymorphism
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting
Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.
1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splender extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splender();//upcasting
9. b.run();
10. }
11. }
Output: running safely with 60km.
In the example given below, both the classes have a datamember speedlimit, we are
accessing the datamember by the reference variable of Parent class which refers to the
subclass object. Since we are accessing the datamember which is not overridden, hence it
will access the datamember of Parent class always.
1. class Animal{
2. void eat(){System.out.println("eating");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("eating fruits");}
7. }
8.
9. class BabyDog extends Dog{
10. void eat(){System.out.println("drinking milk");}
11.
12. public static void main(String args[]){
13. Animal a1,a2,a3;
14. a1=new Animal();
15. a2=new Dog();
16. a3=new BabyDog();
17.
18. a1.eat();
19. a2.eat();
20. a3.eat();
21. }
Kiran Sir 9866243099 Page 89
Core Java
22. }
Output: eating
eating fruits
drinking Milk
Try for Output
1. class Animal{
2. void eat(){System.out.println("animal is eating...");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7. }
8.
9. class BabyDog extends Dog{
10. public static void main(String args[]){
11. Animal a=new BabyDog();
12. a.eat();
13. }}
Output: Dog is eating
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.
Understanding Type
Let's understand the type of instance.
1. int data=30;
1. class Animal{}
2.
3. class Dog extends Animal{
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. }
7. }
Here d1 is an instance of Dog class, but it is also an instance of Animal.
static binding
When type of the object is determined at compiled time(by the compiler), it is known as static
binding.
If there is any private, final or static method in a class, there is static binding.
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
instanceof operator
The instanceof operator is used to test whether the object is an instance of the specified type
(class or subclass or interface).
The instanceof operator is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with any
variable that have null value, it returns false.
1. class Simple{
2. public static void main(String args[]){
3. Simple s=new Simple();
4. System.out.println(s instanceof Simple);//true
5. }
6. }
Output:true
An object of subclass type is also a type of parent class. For example, if Dog extends Animal
then object of Dog can be reffered by either Dog or Animal class.
1. class Dog{
2. public static void main(String args[]){
3. Dog d=null;
4. System.out.println(d instanceof Dog);//false
5. }
6. }
Output:false
1. class Animal { }
2.
3. class Dog extends Animal {
4. static void method(Animal a) {
5. if(a instanceof Dog){
6. Dog d=(Dog)a;//downcasting
7. System.out.println("ok downcasting performed");
8. }
9. }
10.
11. public static void main (String [] args) {
12. Animal a=new Dog();
13. Dog.method(a);
14. }
15.
16. }
1. class Animal { }
2. class Dog extends Animal {
3. static void method(Animal a) {
4. Dog d=(Dog)a;//downcasting
5. System.out.println("ok downcasting performed");
6. }
7. public static void main (String [] args) {
8. Animal a=new Dog();
9. Dog.method(a);
10. }
11. }
Output:ok downcasting performed
Let's take closer look at this, actual object that is referred by a, is an object of Dog class. So if
we downcast it, it is fine. But what will happen if we write:
1. interface Printable{}
2. class A implements Printable{
3. public void a(){System.out.println("a method");}
4. }
5. class B implements Printable{
6. public void b(){System.out.println("b method");}
7. }
8.
9. class Call{
10. void invoke(Printable p){//upcasting
11. if(p instanceof A){
12. A a=(A)p;//Downcasting
13. a.a();
14. }
15. if(p instanceof B){
16. B b=(B)p;//Downcasting
17. b.b();
18. }
Abstraction
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
Abstraction lets you focus on what the object does instead of how it does it.
Abstract class
A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
A factory method is the method that returns the instance of the class. We will learn about the
factory method later.
In this example, if you create the instance of Rectangle class, draw method of Rectangle class
will be invoked.
Rule: If there is any abstract method in a class, that class must be abstract.
1. class Bike{
2. abstract void run();
3. }
Output:compile time error
Rule: If you are extending any abstact class that have abstract method, you must either
provide the implementation of the method or make this class abstract.
Note: If you are beginner to java, learn interface first and skip this example.
1. interface A{
Interface in Java
An interface is a blueprint of a class. It has static 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.
The java compiler adds public and abstract keywords before the interface method and public,
static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods are public
and abstract.
As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.
1. interface printable{
2. void print();
3. }
4.
5. class A implements printable{
6. public void print(){System.out.println("Hello");}
7.
8. public static void main(String args[]){
9. A obj = new A();
10. obj.print();
11. }
12. }
Output:Hello
1. interface Printable{
2. void print();
3. }
4.
5. interface Showable{
6. void show();
1. interface Printable{
2. void print();
3. }
4.
5. interface Showable{
6. void print();
7. }
8.
9. class A implements Printable,Showable{
10.
11. public void print(){System.out.println("Hello");}
12.
13. public static void main(String args[]){
14. A obj = new A();
15. obj.print();
16. }
17. }
Output:Hello
As you can see in the above example, Printable and Showable interface have same
methods but its implementation is provided by class A, so there is no ambiguity.
Note: A class implements interface but One interface extends another interface .
1. interface Printable{
2. void print();
3. }
Nested Interface
Note: An interface can have another interface i.e. known as nested interface. We will learn it
in detail in the nested classes chapter. For example:
1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }
Nested Interface
1. interface Showable{
2. void show();
3. interface Message{
4. void msg();
5. }
6. }
7.
8. class Test implements Showable.Message{
9. public void msg(){System.out.println("Hello nested interface");}
10.
11. public static void main(String args[]){
12. Showable.Message message=new Test();//upcasting here
1. class A{
2. interface Message{
3. void msg();
4. }
5. }
6.
7. class Test implements A.Message{
8. public void msg(){System.out.println("Hello nested interface");}
9.
10. public static void main(String args[]){
11. A.Message message=new Test();//upcasting here
12. message.msg();
13. }
14. }
Output:hello nested interface
1. interface M{
2. class A{}
3. }
Package in Java
Package can be categorized in two form, built-in package and user-defined package. There
are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Package
• Package is used to categorize the classes and interfaces so that they can be easily
maintained.
• Package provids access protection.
• Package removes naming collision.
1. //save as Simple.java
2.
3. package mypack;
4. public class Simple{
5. public static void main(String args[]){
6. System.out.println("Welcome to package");
7. }
8. }
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible
but not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
If you import package.classname then only declared class of this package will be accessible.
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.
Note: Sequence of the program must be package then import then class.
Subpackage
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Let's take an example, Sun Microsystem has definded a package named java that contains
many classes like System, String, Reader, Writer, Socket etc. These classes represent a
particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and
ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java
package into subpackages such as lang, net, io etc. and put the Input/Output related classes in
io package, Server and ServerSocket classes in net packages and so on.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
Output:Hello subpackage
To Run:
To run this program from e:\source directory, you need to set classpath of the directory
where the class file resides.
To run this program from e:\source directory, you can use -classpath switch of java that
tells where to look for class file. For example:
Output:Welcome to package
• Temporary
o By setting the classpath in the command prompt
o By -classpath switch
• Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file
in the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved by the
public class name.
1. //save as A.java
2.
3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}
Access Modifiers
There are two types of modifiers in java: access modifier and non-access modifier. The
access modifiers specifies accessibility (scope) of a datamember, method, constructor or
class.
1. private
2. default
3. protected
4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.
1) private
The private access modifier is accessible only within class.
1. class A{
1. class A{
2. private A(){}//private constructor
3.
4. void msg(){System.out.println("Hello java");}
5. }
6.
7. public class Simple{
8. public static void main(String args[]){
9. A obj=new A();//Compile Time Error
10. }
11. }
2) default
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.
1. //save by A.java
2.
3. package pack;
4. class A{
5. void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
Kiran Sir 9866243099 Page 113
Core Java
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();//Compile Time Error
9. obj.msg();//Compile Time Error
10. }
11. }
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. protected void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B extends A{
7. public static void main(String args[]){
8. B obj = new B();
9. obj.msg();
10. }
11. }
Output:Hello
4) public
The public access modifier is accessible everywhere. It has the widest scope among all
other modiers.
Access Modifier within class within package outside package by subclass only outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Encapsulation in Java
Encapsulation is a process of wrapping code and data together into a single unit e.g. capsule
i.e mixed of several medicines.
Advantage of Encapsulation
By providing only setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data. Suppose you want to set the value of id i.e. greater
than 100 only, you can write the logic inside the setter method.
1. //save as Student.java
Kiran Sir 9866243099 Page 116
Core Java
2. package com.javatpoint;
3. public class Student{
4. private String name;
5.
6. public String getName(){
7. return name;
8. }
9. public void setName(String name){
10. this.name=name
11. }
12. }
1. //save as Test.java
2. package com.javatpoint;
3. class Test{
4. public static void main(String[] args){
5. Student s=new Student();
6. s.setname("vijay");
7. System.out.println(s.getName());
8. }
9. }
Compile By: javac -d . Test.java
Run By: java com.javatpoint.Test
Output: vijay
The Object class is beneficial if you want to refer any object whose type you don't know.
Notice that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any
type like Employee,Student etc, we can use Object class reference to refer that object. For
example:
1. Object obj=getObject();//we don't what object would be returned from this method
The Object class provides some common behaviours to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
Method Description
public final Class getClass() returns the Class class object of this object. The Class
class can further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws causes the current thread to wait for the specified
InterruptedException miliseconds, until another thread notifies (invokes notify()
or notifyAll() method).
public final void wait(long timeout,int causes the current thread to wait for the specified
nanos)throws InterruptedException miliseconds and nanoseconds, until another thread notifies
(invokes notify() or notifyAll() method).
public final void wait()throws causes the current thread to wait, until another thread
InterruptedException notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is being
garbage collected.
The object cloning is a way to create exact copy of an object. For this purpose, clone()
method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object clone we
want to create. If we don't implement Cloneable interface, clone() method
generatesCloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as
follows:
The clone() method saves the extra processing task for creating the exact copy of an object.
If we perform it by using the new keyword, it will take a lot of processing to be performed
that is why we use object cloning.
As you can see in the above example, both reference variables have the same value. Thus, the
clone() copies the values of an object to another. So we don't need to write explicit code to
copy the value of an object to another.
If we create another object by new keyword and assign the values of another object to this
one, it will require a lot of processing on this object. So to save the extra processing task we
use clone() method.
Array in Java
Normally, array is a collection of similar type of elements that have contigious memory
location.
In java, array is an object the contains elements of similar data type. It is a data structure
where we store similar elements. We can store only fixed elements in an array.
Advantage of Array
• Code Optimization: It makes the code optimized, we can retrive or sort the data
easily.
• Random access: We can get any data located at any index position.
Disadvantage of Array
• Size Limit: We can store only fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in java.
Types of Array
There are two types of array.
1. class B{
2. public static void main(String args[]){
3.
4. int a[]=new int[5];//declaration and instantiation
5. a[0]=10;//initialization
6. a[1]=20;
7. a[2]=70;
8. a[3]=40;
9. a[4]=50;
10.
11. //printing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14.
15. }}
Output: 10
20
70
40
50
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
1. class B{
2. public static void main(String args[]){
3.
4. int a[]={33,3,4,5};//declaration, instantiation and initialization
5.
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9.
10. }}
Output:33
3
4
5
Let's see the simple example to get minimum number of an array using method.
1. class B{
2. static void min(int arr[]){
3. int min=arr[0];
4. for(int i=1;i<arr.length;i++)
5. if(min>arr[i])
6. min=arr[i];
7.
8. System.out.println(min);
9. }
10.
11. public static void main(String args[]){
12.
13. int a[]={33,3,4,5};
14. min(a);//passing array in the method
15.
16. }}
Output:3
Multidimensional array
In such case, data is stored in row and column based index (also known as matrix form).
1. class B{
2. public static void main(String args[]){
3.
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.
7. //printing 2D array
8. for(int i=0;i<3;i++){
9. for(int j=0;j<3;j++){
10. System.out.print(arr[i][j]+" ");
11. }
12. System.out.println();
13. }
14.
15. }}
Output:1 2 3
245
445
1. class B{
2. public static void main(String args[]){
3.
4. int arr[]={4,4,5};
5.
6. Class c=arr.getClass();
7. String name=c.getName();
8.
9. System.out.println(name);
10.
11. }}
Output:[I
Copying an array
We can copy an array to another by the arraycopy method of System class.
Addition 2 matrices
Let's see a simple example that adds two matrices.
1. class AE{
2. public static void main(String args[]){
3. //creating two matrices
4. int a[][]={{1,3,4},{3,4,5}};
5. int b[][]={{1,3,4},{3,4,5}};
6.
7. //creating another matrix to store the sum of two matrices
8. int c[][]=new int[2][3];
9.
10. //adding and printing addition of 2 matrices
11. for(int i=0;i<2;i++){
12. for(int j=0;j<3;j++){
13. c[i][j]=a[i][j]+b[i][j];
14. System.out.print(c[i][j]+" ");
15. }
16. System.out.println();//new line
17. }
18.
19. }}
Output:2 6 8
6 8 10
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a
value, it is known as call by value. The changes being done in the called method, is not
affected in the calling method.
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8. public static void main(String args[]){
9. Operation op=new Operation();
10.
11. System.out.println("before change "+op.data);
12. op.change(500);
13. System.out.println("after change "+op.data);
14.
15. }
16. }
output:before change 50
after change 50
1. class Operation2{
2. int data=50;
3.
4. void change(Operation2 op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7.
8.
9. public static void main(String args[]){
10. Operation2 op=new Operation2();
11.
12. System.out.println("before change "+op.data);
13. op.change(op);//passing object
14. System.out.println("after change "+op.data);
15.
16. }
17. }
Output:before change 50
after change 150
strictfp keyword
The 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. So, now you have better control over the
floating-point arithmetic.
1. class B{
2. strictfp abstract void m();//Illegal combination of modifiers
3. }
1. class B{
2. strictfp int data=10;//modifier strictfp not allowed here
3. }
1. class B{
2. strictfp B(){}//modifier strictfp not allowed here
3. }
Creating API Document | javadoc tool
We can create document api in java by the help of javadoc tool. In the java file, we must use
the documentation comment /**... */ to post information for the class, method, constructor,
fields etc.
1. package com.abc;
2. /** This class is a user-defined class that contains one methods cube.*/
3. public class M{
4.
5. /** The cube method prints cube of the given number */
6. public static void cube(int n){System.out.println(n*n*n);}
7. }
javadoc M.java
to generate the document api. Now, there will be created a lot of html files. Open the
index.html file to get the information about the classes.
So, it provides a convenient way to check out the behavior of the program on different values.
You can pass N numbers of arguments from the command prompt.
1. class A{
2. public static void main(String args[]){
3.
4. System.out.println("first argument is: "+args[0]);
5.
6. }
7. }
1. compile by > javac A.java
2. run by > java A sonoo
Output:first argument is: sonoo
1. class A{
2. public static void main(String args[]){
3.
4. for(int i=0;i<args.length;i++)
5. System.out.println(args[i]);
6.
7. }
8. }
1. compile by > javac A.java
2. run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc
In java, string is basically an immutable object. We will discuss about immutable string later.
Let's first understand what is string and how we can create the string object.
String
Generally string is a sequence of characters. But in java, string is an object. String class is
used to create string object.
1) String literal
String literal is created by double quote.For Example:
1. String s="Hello";
Each time you create a string literal, the JVM checks the string constant pool first. If the
string already exists in the pool, a reference to the pooled instance returns. If the string
does not exist in the pool, a new String object instantiates, then is placed in the pool.For
example:
1. String s1="Welcome";
2. String s2="Welcome";//no new object will be created
In the above example only one object will be created.First time JVM will find no string
object with the name "Welcome" in string constant pool,so it will create a new
object.Second time it will find the string with the name "Welcome" in string constant
pool,so it will not create new object whether will return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool inside the Heap
memory.
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new String object in normal(nonpool) Heap memory and
the literal "Welcome" will be placed in the string constant pool.The variable s will refer to
the object in Heap(nonpool).
• Concept of String
• Immutable String
• String Comparison
• String Concatenation
• Concept of Substring
• String class methods and its usage
• StringBuffer class
• StringBuilder class
• Creating Immutable class
• toString() method
• StringTokenizer class
Once string object is created its data or state can't be changed but a new string object is
created.
Let's try to understand the immutability concept by the example given below:
1. class Simple{
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the end
5. System.out.println(s);//will print Sachin because strings are immutable objects
6. }
7. }
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new
object is created with sachintendulkar. That is why string is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still
refers to "Sachin" not to "Sachin Tendulkar".
But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar"
object.For example:
1. class Simple{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=s.concat(" Tendulkar");
5. System.out.println(s);
6. }
7. }
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not
modified.
We can compare two given strings on the basis of content and reference.
1. By equals() method
2. By = = operator
3. By compareTo() method
1) By equals() method
equals() method compares the original content of the string.It compares values of string
for equality.String class provides two methods:
1. class Simple{
2. public static void main(String args[]){
3.
4. String s1="Sachin";
5. String s2="Sachin";
6. String s3=new String("Sachin");
7. String s4="Saurav";
8.
9. System.out.println(s1.equals(s2));//true
10. System.out.println(s1.equals(s3));//true
11. System.out.println(s1.equals(s4));//false
12. }
13. }
Output:true
true
false
1. //Example of equalsIgnoreCase(String) method
2. class Simple{
3. public static void main(String args[]){
4.
5. String s1="Sachin";
6. String s2="SACHIN";
7.
8. System.out.println(s1.equals(s2));//false
9. System.out.println(s1.equalsIgnoreCase(s3));//true
10. }
11. }
Output:false
true
2) By == operator
The = = operator compares references not values.
1. //<b><i>Example of == operator</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s1="Sachin";
7. String s2="Sachin";
8. String s3=new String("Sachin");
9.
10. System.out.println(s1==s2);//true (because both refer to same instance)
11. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
• s1 == s2 :0
• s1 > s2 :positive value
• s1 < s2 :negative value
1. class Simple{
2. public static void main(String args[]){
3.
4. String s=50+30+"Sachin"+40+40;
5. System.out.println(s);//80Sachin4040
6. }
7. }
Output:80Sachin4040
Note:If either operand is a string, the resulting operation will be string concatenation. If
both operands are numbers, the operator will perform an addition.
2) By concat() method
concat() method concatenates the specified string to the end of current string.
Syntax:public String concat(String another){}
1. //<b><i>Example of concat(String) method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s1="Sachin ";
7. String s2="Tendulkar";
8.
9. String s3=s1.concat(s2);
10.
11. System.out.println(s3);//Sachin Tendulkar
12. }
Substring in Java
A part of string is called substring. In other words, substring is a subset of another string.
In case of substring startIndex starts from 0 and endIndex starts from 1 or startIndex is
inclusive and endIndex is exclusive.
You can get substring from the given String object by one of the two methods:
1. public String substring(int startIndex): This method returns new String object
containing the substring of the given string from specified startIndex (inclusive).
2. public String substring(int startIndex,int endIndex): This method returns new
String object containing the substring of the given string from specified startIndex to
endIndex.
In case of string:
Method Description
1)public boolean equals(Object anObject) Compares this string to the specified object.
2)public boolean equalsIgnoreCase(String Compares this String to another String, ignoring case.
another)
3)public String concat(String str) Concatenates the specified string to the end of this string.
4)public int compareTo(String str) Compares two strings and returns int
5)public int compareToIgnoreCase(String str) Compares two strings, ignoring case differences.
6)public String substring(int beginIndex) Returns a new string that is a substring of this string.
7)public String substring(int beginIndex,int Returns a new string that is a substring of this string.
endIndex)
8)public String toUpperCase() Converts all of the characters in this String to upper case
9)public String toLowerCase() Converts all of the characters in this String to lower case.
10)public String trim() Returns a copy of the string, with leading and trailing
whitespace omitted.
11)public boolean startsWith(String prefix) Tests if this string starts with the specified prefix.
12)public boolean endsWith(String suffix) Tests if this string ends with the specified suffix.
13)public char charAt(int index) Returns the char value at the specified index.
15)public String intern() Returns a canonical representation for the string object.
First seven methods have already been discussed.Now Let's take the example of other
methods:
trim() method
1. //<b><i>Example of trim() method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s=" Sachin ";
7. System.out.println(s);// Sachin
8. System.out.println(s.trim());//Sachin
9. }
10. }
Output: Sachin
Sachin
charAt() method
1. //<b><i>Example of charAt() method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin";
7. System.out.println(s.charAt(0));//S
8. System.out.println(s.charAt(3));//h
9. }
10. }
Output:S
h
length() method
1. //<b><i>Example of length() method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin";
7. System.out.println(s.length());//6
8. }
9. }
Output:6
intern() method
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this
String object as determined by the equals(Object) method, then the string from the pool is
returned. Otherwise, this String object is added to the pool and a reference to this String
object is returned.
StringBuffer class:
The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer
class is same as String except it is mutable i.e. it can be changed.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello ");
5. sb.append("Java");//now original string is changed
6.
7. System.out.println(sb);//prints Hello Java
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello ");
5. sb.insert(1,"Java");//now original string is changed
6.
7. System.out.println(sb);//prints HJavaello
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.replace(1,3,"Java");
6.
7. System.out.println(sb);//prints HJavalo
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.delete(1,3);
6.
7. System.out.println(sb);//prints Hlo
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.reverse();
6.
7. System.out.println(sb);//prints olleH
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10. sb.append("java is my favourite language");
11. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12. }
13. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10. sb.append("java is my favourite language");
11. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12.
13. sb.ensureCapacity(10);//now no change
14. System.out.println(sb.capacity());//now 34
15.
16. sb.ensureCapacity(50);//now (34*2)+2
17. System.out.println(sb.capacity());//now 70
18.
19. }
20. }
StringBuilder class:
The StringBuilder class is used to create mutable (modifiable) string. The StringBuilder
class is same as StringBuffer class except that it is non-synchronized. It is available since
JDK1.5.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello ");
5. sb.append("Java");//now original string is changed
6.
7. System.out.println(sb);//prints Hello Java
8. }
9. }
1. class A{
2. public static void main(String args[]){
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.replace(1,3,"Java");
6.
7. System.out.println(sb);//prints HJavalo
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.delete(1,3);
6.
7. System.out.println(sb);//prints Hlo
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.reverse();
6.
7. System.out.println(sb);//prints olleH
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10. sb.append("java is my favourite language");
11. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12. }
13. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10. sb.append("java is my favourite language");
11. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12.
13. sb.ensureCapacity(10);//now no change
14. System.out.println(sb.capacity());//now 34
15.
16. sb.ensureCapacity(50);//now (34*2)+2
17. System.out.println(sb.capacity());//now 70
18.
19. }
20. }
If you print any object, java compiler internally invokes the toString() method on the object.
So overriding the toString() method, returns the desired output, it can be the state of an object
etc. depends on your implementation.
1. class Student{
2. int rollno;
3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
7. this.rollno=rollno;
8. this.name=name;
9. this.city=city;
10. }
11.
12. public static void main(String args[]){
13. Student s1=new Student(101,"Raj","lucknow");
14. Student s2=new Student(102,"Vijay","ghaziabad");
15.
16. System.out.println(s1);//compiler writes here s1.toString()
17. System.out.println(s2);//compiler writes here s2.toString()
18. }
19. }
Output:Student@1fee6fc
Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values of the
objects but I want to print the values of these objects. Since java compiler internally calls
toString() method, overriding this method will return the specified values. Let's
understand it with the example given below:
1. class Student{
2. int rollno;
3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple
way to break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
Constructor Description
StringTokenizer(String str, String creates StringTokenizer with specified string and delimeter.
delim)
StringTokenizer(String str, String creates StringTokenizer with specified string, delimeter and
delim, boolean returnValue) returnValue. If return value is true, delimiter characters are considered
to be tokens. If it is false, delimiter characters serve to separate tokens.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }
Output:my
name
is
khan
In this page, we will know about exception, its type and the difference between checked and
unchecked exceptions.
Exception
• Dictionary Meaning:Exception is an abnormal condition.
• In java, exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
Exception Handling
Exception Handling is a mechanism to handle runtime errors.
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement
5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform
exception handling, rest of the exception will be executed. That is why we use exception
handling.
Types of Exception:
There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun microsystem says there are three types of
exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked
at compile-time.
2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3)Error
1. int a=50/0;//ArithmeticException
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
3) Scenario where NumberFormatException occurs
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
4) Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
try block
Enclose the code that might throw an exception in try block. It must be used within the
method and must be followed by either catch or finally block.
As displayed in the above example, rest of the code is not executed i.e. rest of the code...
statement is not printed. Let's see what happens behind the scene:
The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:
• Prints out exception description.
• Prints the stack trace (Hierarchy of methods where the exception occurred).
• Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application
is maintained i.e. rest of the code is executed.
Rule:All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception .
1. class Excep4{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....
Example:
1. <b><i>Example of nested try block</i></b>
2.
3. class Excep6{
finally block
The finally block is a block that is always executed. It is mainly used to perform some
important tasks such as closing connection, stream etc.
case 1
Program in case exception does not occur
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Output:5
finally block is always executed
rest of the code...
case 2
Program in case exception occured but not handled
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
case 3
Program in case exception occured and handled
1. class Simple{
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling System.exit() or
by causing a fatal error that causes the process to abort).
throw keyword
The throw keyword is used to explictily throw an exception.
We can throw either checked or uncheked exception. The throw keyword is mainly used
to throw custom exception. We will see custom exceptions later.
1. class Excep13{
2.
3. static void validate(int age){
4. if(age<18)
5. throw new ArithmeticException("not valid");
6. else
7. System.out.println("welcome to vote");
8. }
9.
10. public static void main(String args[]){
11. validate(13);
12. System.out.println("rest of the code...");
Exception propagation:
An exception is first thrown from the top of the stack and if it is not caught, it drops down
the call stack to the previous method,If not caught there, the exception again drops down
to the previous method, and so on until they are caught or until they reach the very bottom
of the call stack.This is called exception propagation.
1. class Simple{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handled");}
12. }
13. public static void main(String args[]){
14. Simple obj=new Simple();
15. obj.p();
16. System.out.println("normal flow...");
17. }
18. }
Output:exception handled
normal flow...
Exception can be handled in any method in call stack either in main() method,p() method,n()
method or m() method.
1. class Simple{
2. void m(){
3. throw new java.io.IOException("device error");//checked exception
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handeled");}
12. }
13. public static void main(String args[]){
14. Simple obj=new Simple();
15. obj.p();
16. System.out.println("normal flow");
17. }
18. }
Output:Compile Time Error
throws keyword
The throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
Program which describes that checked exceptions can be propagated by throws keyword.
1. import java.io.IOException;
2. class Simple{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Simple obj=new Simple();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
Output:exception handled
normal flow...
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7.
8.
9. class Test{
10. public static void main(String args[]){
11. try{
12. Test t=new Test();
13. t.method();
14. }catch(Exception e){System.out.println("exception handled");}
15.
16. System.out.println("normal flow...");
17. }
18. }
Output:exception handled
normal flow...
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7.
8.
9. class Test{
10. public static void main(String args[])throws IOException{//declare exception
11. Test t=new Test();
12. t.method();
13.
14. System.out.println("normal flow...");
15. }
16. }
Output:Runtime Exception
2)checked exception can not be propagated without checked exception can be propagated with throws.
throws.
4)throw is used within the method. throws is used with the method signature.
5)You cannot throw multiple exception You can declare multiple exception e.g.
public void method()throws
IOException,SQLException.
2) Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but can declare unchecked exception.
1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg()throws ArithmeticException{
8. System.out.println("child");
9. }
10. public static void main(String args[]){
Custom Exception
If you are creating your own Exception that is known as custom exception or user-defined
exception.
1. class InvalidAgeException extends Exception{
2. InvalidAgeException(String s){
• Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
• Nested classes can lead to more readable and maintainable code because it logically
group classes in one place only.
• Code Optimization as we need less code to write.
Do You Know ?
• What is the internal code generated by the compiler for member inner class ?
• What are the two ways to create annonymous inner class ?
• Can we access the non-final local variable inside the local inner class ?
• How to access the static nested class ?
• Can we define an interface within the class ?
• Can we define a class within the interface ?
Que) What is the difference between nested class and inner class?
Inner class is a part of nested class. Non-static nested classes are known as nested classes.
• Nested class
• Member inner class
• Annonymous inner class
• Local Inner class
• static nested class
• Nested interface
1. class Outer{
2. private int data=30;
3. class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6.
7. void display(){
8. Inner in=new Inner();
9. in.msg();
10. }
11. public static void main(String args[]){
12. Outer obj=new Outer();
13. obj.display();
14. }
15. }
Output:data is 30
1. import java.io.PrintStream;
2.
3. class Outer$Inner
4. {
5. final Outer this$0;
6. Outer$Inner()
7. { super();
8. this$0 = Outer.this;
9. }
10.
11. void msg()
12. {
13. System.out.println((new StringBuilder()).append("data is ")
14. .append(Outer.access$000(Outer.this)).toString());
15. }
16.
17. }
The internal code generated by the compiler for annonymous inner class created
by interface
1. import java.io.PrintStream;
2. static class Emp$1 implements Eatable
3. {
4. Emp$1(){}
5.
6. void eat(){System.out.println("nice fruits");}
7. }
3)Local inner class
A class that is created inside a method is known as local inner class. If you want to invoke
the methods of local inner class, you must instantiate this class inside the method.
1. import java.io.PrintStream;
2. class Simple$1Local
3. {
4. final Simple this$0;
5.
6. Simple$1Local()
7. {
8. super();
9. this$0 = Simple.this;
10. }
11. void msg()
12. {
13. System.out.println(Simple.access$000(Simple.this));
14. }
15.
16. }
In this example, you need to create the instance of static nested class because it has
instance method msg(). But you don't need to create the object of Outer class because
nested class is static and static properties, methods or classes can be accessed without
object.
Nested Interface
An interface which is declared within another interface or class is known as nested
interface. The nested interfaces are used to group related interfaces so that they can be
easy to maintain. The nested interface must be referred by the outer interface or class. It
can't be accessed directly.
1. interface Showable{
2. void show();
3. interface Message{
4. void msg();
5. }
6. }
7.
8. class Test implements Showable.Message{
9. public void msg(){System.out.println("Hello nested interface");}
10.
11. public static void main(String args[]){
12. Showable.Message message=new Test();//upcasting here
13. message.msg();
14. }
15. }
Output:hello nested interface
As you can see in the above example, we are acessing the Message interface by its outer
1. class A{
2. interface Message{
3. void msg();
4. }
5. }
6.
7. class Test implements A.Message{
8. public void msg(){System.out.println("Hello nested interface");}
9.
10. public static void main(String args[]){
11. A.Message message=new Test();//upcasting here
12. message.msg();
13. }
14. }
Output:hello nested interface
1. interface M{
2. class A{}
3. }
Multithreading in Java
Multithreading is a process of executing multiple threads simultaneously.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking
to utilize the CPU. Multitasking can be achieved by two ways:
• Process-based Multitasking(Multiprocessing)
• Thread-based Multitasking(Multithreading)
What is Thread?
A thread is a lightweight subprocess, a smallest unit of processing. It is a separate path of
execution. It shares the memory area of process.
As shown in the above figure, thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS and one
process can have multiple threads.
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1)New
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2)Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.
3)Running
The thread is in running state if the thread scheduler has selected it.
5)Terminated
A thread is in terminated or dead state when its run() method exits.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended
to be executed by a thread. Runnable interface have only one method named run().
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
• A new thread starts(with new callstack).
• The thread moves from New state to the Runnable state.
• When the thread gets a chance to execute, its target run() method will run.
As you can see in the above program that there is no context-switching because here t1
and t2 will be treated as normal object not thread object.
Syntax:
public void join()throws InterruptedException
As you can see in the above example,when t1 completes its task then t2 and t3 starts
executing.
In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then t2
and t3 starts executing.
Syntax:
public static Thread currentThread()
Naming a thread:
The Thread class provides methods to change and get the name of a thread.
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of a thread.
Daemon Thread
There are two types of threads user thread and daemon thread. The daemon thread is a
service provider thread. It provides services to the user thread. Its life depends on the user
threads i.e. when all the user threads dies, JVM termintates this thread automatically.
Note: If you want to make a user thread as Daemon, it must not be started otherwise it will
throw IllegalThreadStateException.
1. class MyThread extends Thread{
2. public void run(){
3. System.out.println("Name: "+Thread.currentThread().getName());
4. System.out.println("Daemon: "+Thread.currentThread().isDaemon());
5. }
6.
7. public static void main(String[] args){
8. MyThread t1=new MyThread();
9. MyThread t2=new MyThread();
10. t1.start();
11. t1.setDaemon(true);//will throw exception here
12. t2.start();
13. }
14. }
Output:exception in thread main: java.lang.IllegalThreadStateException
In case of thread pool, a group of fixed size threads are created. A thread from the thread pool
is pulled out and assigned a job by the service provider. After completion of the job, thread is
contained in the thread pool again.
Better performance It saves time because there is no need to create new thread.
Where is it used?
It is used in Servlet and JSP where container creates a thread pool to process the request.
1. import java.util.concurrent.ExecutorService;
2. import java.util.concurrent.Executors;
3. class WorkerThread implements Runnable {
4. private String message;
5. public WorkerThread(String s){
6. this.message=s;
7. }
8.
9. public void run() {
10. System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);
11. processmessage();
12. System.out.println(Thread.currentThread().getName()+" (End)");
13. }
14.
15. private void processmessage() {
16. try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
17. }
18. }
19.
20. public class SimpleThreadPool {
21. public static void main(String[] args) {
22. ExecutorService executor = Executors.newFixedThreadPool(5);
23. for (int i = 0; i < 10; i++) {
24. Runnable worker = new WorkerThread("" + i);
25. executor.execute(worker);
26. }
27. executor.shutdown();
28. while (!executor.isTerminated()) { }
29.
30. System.out.println("Finished all threads");
31. }
32.
33. }
Output:
1. pool-1-thread-1 (Start) message = 0
2. pool-1-thread-2 (Start) message = 1
3. pool-1-thread-3 (Start) message = 2
4. pool-1-thread-5 (Start) message = 4
5. pool-1-thread-4 (Start) message = 3
6. pool-1-thread-2 (End)
7. pool-1-thread-2 (Start) message = 5
8. pool-1-thread-1 (End)
9. pool-1-thread-1 (Start) message = 6
10. pool-1-thread-3 (End)
11. pool-1-thread-3 (Start) message = 7
Kiran Sir 9866243099 Page 198
Core Java
12. pool-1-thread-4 (End)
13. pool-1-thread-4 (Start) message = 8
14. pool-1-thread-5 (End)
15. pool-1-thread-5 (Start) message = 9
16. pool-1-thread-2 (End)
17. pool-1-thread-1 (End)
18. pool-1-thread-4 (End)
19. pool-1-thread-3 (End)
20. pool-1-thread-5 (End)
21. Finished all threads
Shutdown Hook
The shutdown hook can be used to perform cleanup resource or save the state when JVM
shuts down normally or abruptly. Performing clean resource means closing log file,
sending some alerts or something else. So if you want to execute some code before JVM
shuts down, use shutdown hook.
The object of Runtime class can be obtained by calling the static factory method
getRuntime(). For example:
Runtime r = Runtime.getRuntime();
Factory method
The method that returns the instance of a class is known as factory method.
Note: The shutdown sequence can be stopped by invoking the halt(int) method of Runtime
class.
Garbage Collection:
In java, garbage means unreferenced objects.
1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;
3) By annonymous object:
1. new Employee();
finalize() method:
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in System
class as:
gc() method:
The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.
Synchronization
Synchronization is the capabilility of control the access of multiple threads to any shared
resource. Synchronization is better in case we want only one thread can access the shared
resource at a time.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
• Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
• Cooperation (Inter-thread communication)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
This can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
1. Class Table{
2.
3. void printTable(int n){//method not synchronized
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
Synchronized block
Synchronized block can be used to perform synchronization on any specific resouce of the
method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
1. class Table{
2.
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12.
13. class MyThread1 extends Thread{
14. public void run(){
15. Table.printTable(1);
16. }
17. }
18.
19. class MyThread2 extends Thread{
20. public void run(){
21. Table.printTable(10);
22. }
23. }
24.
25. class MyThread3 extends Thread{
26. public void run(){
27. Table.printTable(100);
28. }
29. }
30.
31.
32.
33.
34. class MyThread4 extends Thread{
35. public void run(){
36. Table.printTable(1000);
37. }
38. }
39.
40. class Use{
41. public static void main(String t[]){
42. MyThread1 t1=new MyThread1();
43. MyThread2 t2=new MyThread2();
44. MyThread3 t3=new MyThread3();
1. class Table{
2.
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12.
13. public class Test {
14. public static void main(String[] args) {
15.
16. Thread t1=new Thread(){
17. public void run(){
18. Table.printTable(1);
19. }
20. };
21.
22. Thread t2=new Thread(){
23. public void run(){
24. Table.printTable(10);
25. }
26. };
27.
28. Thread t3=new Thread(){
29. public void run(){
30. Table.printTable(100);
31. }
32. };
33.
34. Thread t4=new Thread(){
35. public void run(){
36. Table.printTable(1000);
37. }
38. };
39. t1.start();
40. t2.start();
41. t3.start();
42. t4.start();
43.
44. }
Deadlock:
Deadlock can occur in a situation when a thread is waiting for an object lock, that is
acquired by another thread and second thread is waiting for an object lock that is acquired
by first thread. Since, both threads are waiting for each other to release the lock, the
condition is called daedlock.
• wait()
• notify()
• notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description
public final void wait(long timeout)throws InterruptedException waits for the specified amount of time.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on
this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation. Syntax:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
should be notified by notify() or notifyAll() after the specified amount of time, sleep is
methods completed.
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
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 but sets the
interrupt flag to true. Let's first see the methods provided by the Thread class for thread
interruption.
Let's understand the java reentrant monitor by the example given below:
1. class Reentrant {
2. public synchronized void m() {
3. n();
4. System.out.println("this is m() method");
5. }
6. public synchronized void n() {
7. System.out.println("this is n() method");
8. }
9. }
In this class, m and n are the synchronized methods. The m() method internally calls the n()
method.
Kiran Sir 9866243099 Page 225
Core Java
Now let's call the m() method on a thread. In the class given below, we are creating thread
using annonymous class.
1. class ReentrantExample{
2. public static void main(String args[]){
3. final Reentrant re=new Reentrant();
4.
5. Thread t1=new Thread(){
6. public void run(){
7. re.m();//calling method of Reentrant class
8. }
9. };
10. t1.start();
11. }}
Output: this is n() method
this is m() method
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream
because it's like a stream of water that continues to flow.
Do You Know ?
• How to write a common data to multiple files using single stream only ?
• How can we access multiple files by single stream ?
• How can we improve the performance of Input and Output operation ?
• How many ways can we read data from the keyboard?
• What is console class ?
• How to compress and uncompress the data of a file?
OutputStream
Java application uses an output stream to write data to a destination, it may be a file,an
array,peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source, it may be a file,an
array,peripheral device or socket.
OutputStream class
OutputStream class ia an abstract class.It is the superclass of all classes representing an
output stream of bytes. An output stream accepts output bytes and sends them to some
sink.
1) public void write(int)throws IOException: is used to write a byte to the current output stream.
2) public void write(byte[])throws IOException: is used to write an array of byte to the current output stream.
4) public void close()throws IOException: is used to close the current output stream.
InputStream class
InputStream class ia an abstract class.It is the superclass of all classes representing an input
stream of bytes.
1) public abstract int read()throws reads the next byte of data from the input stream.It returns -1 at the end of file.
IOException:
2) public int available()throws IOException: returns an estimate of the number of bytes that can be read from the current
input stream.
3) public void close()throws IOException: is used to close the current input stream.
FileOutputStream class:
A FileOutputStream is an output stream for writing data to a file.
If you have to write primitive values then use FileOutputStream.Instead, for character-
oriented data, prefer FileWriter.But you can write byte-oriented as well as character-
oriented data.
1. import java.io.*;
2.
3. class C{
4. public static void main(String args[])throws Exception{
5.
6. FileInputStream fin=new FileInputStream("C.java");
7. FileOutputStream fout=new FileOutputStream("M.java");
Kiran Sir 9866243099 Page 231
Core Java
8.
9. int i=0;
10. while((i=fin.read())!=-1){
11. fout.write((byte)i);
12. }
13.
14. fin.close();
15. }
16. }
ByteArrayOutputStream class:
In this stream, the data is written into a byte array. The buffer automatically grows as data
is written to it.
SequenceInputStream class:
SequenceInputStream class is used to read data from multipule streams.
BufferedOutputStream class:
BufferedOutputStream used an internal buffer. It adds more efficiency than to write data
directly into a stream. So, it makes the performance fast.
FileWriter class:
FileWriter class is used to write character-oriented data to the file. Sun Microsystem has
suggested not to use the FileInputStream and FileOutputStream classes if you have to read
and write the textual information.
1. import java.io.*;
2. class Simple{
3. public static void main(String args[]){
4. try{
5. FileWriter fw=new FileWriter("abc.txt");
6. fw.write("my name is sachin");
7. fw.flush();
8.
9. fw.close();
10. }catch(Exception e){System.out.println(e);}
11. System.out.println("success");
12. }
13. }
Output:success...
FileReader class:
FileReader class is used to read data from the file.
1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4.
5. FileReader fr=new FileReader("abc.txt");
6. int i;
7. while((i=fr.read())!=-1)
8. System.out.println((char)i);
9.
10. fr.close();
11. }
12. }
Output:my name is sachin
CharArrayWriter class:
The CharArrayWriter class can be used to write data to multiple files. This class
implements the Appendable interface. Its buffer automatically grows when data is written
in this stream. Calling the close() method on this object has no effect.
1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4.
5. CharArrayWriter out=new CharArrayWriter();
6. out.write("my name is");
7.
8. FileWriter f1=new FileWriter("a.txt");
9. FileWriter f2=new FileWriter("b.txt");
10. FileWriter f3=new FileWriter("c.txt");
11. FileWriter f4=new FileWriter("d.txt");
12.
13. out.writeTo(f1);
14. out.writeTo(f2);
15. out.writeTo(f3);
16. out.writeTo(f4);
17.
18.
19. f1.close();
20. f2.close();
21. f3.close();
22. f4.close();
23. }
24. }
InputStreamReader class:
InputStreamReader class can be used to read data from keyboard.It performs two tasks:
• connects to input stream of keyboard
• converts the byte-oriented stream into character-oriented stream
BufferedReader class:
BufferedReader class can be used to read data line by line by readLine() method.
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
System.out.println("Enter ur name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Output:Enter ur name
Amit
Welcome Amit
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
String name="";
while(name.equals("stop")){
System.out.println("Enter data: ");
name=br.readLine();
System.out.println("data is: "+name);
}
br.close();
r.close();
}
}
Output:Enter data: Amit
data is: Amit
Enter data: 10
data is: 10
Enter data: stop
data is: stop
Syntax:
1. public static Console console(){}
3) public char[] readPassword(): is used to read password that is not being displayed on
the console.
java.util.Scanner class:
There are various ways to read input from the keyboad, the java.util.Scanner class is one
of them. The Scanner class breaks the input into tokens using a delimiter which is
whitespace bydefault. It provides many methods to read and parse various primitive
values.
1. import java.util.Scanner;
2. class ScannerTest{
3. public static void main(String args[]){
4.
5. Scanner sc=new Scanner(System.in);
6.
7. System.out.println("Enter your rollno");
8. int rollno=sc.nextInt();
9. System.out.println("Enter your name");
10. String name=sc.next();
11. System.out.println("Enter your fee");
12. double fee=sc.nextDouble();
13.
14. System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
15.
16. }
17. }
Output:Enter your rollno
111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000
java.io.PrintStream class:
The PrintStream class provides methods to write data to another stream. The PrintStream
class automatically flushes the data so there is no need to call flush() method. Moreover,
its methods don't throw IOException.
1. import java.io.*;
2. class PrintStreamTest{
3. public static void main(String args[])throws Exception{
4.
5. FileOutputStream fout=new FileOutputStream("mfile.txt");
6. PrintStream pout=new PrintStream(fout);
7. pout.println(1900);
8. pout.println("Hello Java");
9. pout.println("Welcome to Java");
10. pout.close();
11. fout.close();
12.
13. }
14. }
1. class PrintStreamTest{
2. public static void main(String args[]){
3. int a=10;
4. System.out.printf("%d",a);//Note, out is the object of PrintStream class
5.
6. }
7. }
Output:10
DeflaterOutputStream class:
The DeflaterOutputStream class is used to compress the data in the deflate compression
format. It provides facility to the other compression filters, such as GZIPOutputStream.
1. import java.io.*;
2. import java.util.zip.*;
3.
4. class Compress{
5. public static void main(String args[]){
6.
7. try{
8. FileInputStream fin=new FileInputStream("Deflater.java");
9.
10. FileOutputStream fout=new FileOutputStream("def.txt");
11. DeflaterOutputStream out=new DeflaterOutputStream(fout);
12.
13. int i;
14. while((i=fin.read())!=-1){
15. out.write((byte)i);
16. out.flush();
17. }
18.
19. fin.close();
20. out.close();
21.
22. }catch(Exception e){System.out.println(e);}
23. System.out.println("rest of the code");
24. }
25. }
InflaterInputStream class:
The InflaterInputStream class is used to uncompress the file in the deflate compression
format. It provides facility to the other uncompression filters, such as GZIPInputStream
class.
1. import java.io.*;
2. import java.util.zip.*;
3.
4. class UnCompress{
5. public static void main(String args[]){
1. import java.io.*;
2.
3. class PipedWR{
4. public static void main(String args[])throws Exception{
5.
6. final PipedOutputStream pout=new PipedOutputStream();
7. final PipedInputStream pin=new PipedInputStream();
8.
9. pout.connect(pin);//connecting the streams
10.
11. //creating one thread t1 which writes the data
12. Thread t1=new Thread(){
Serialization
Serialization is a machanism of writing the state of an object into a byte stream. It is
mainly used in Hibernate, JPA, EJB etc. The reverse operation of the serialization is called
deserialization. The String class and all the wrapper classes implements Serializable
interface bydefault.
Advantage of Serialization
It is mainly used to travel object's state on the network.
1. import java.io.Serializable;
2.
3. public class Student implements Serializable{
4. int id;
5. String name;
6. public Student(int id, String name) {
7. this.id = id;
8. this.name = name;
9. }
10. }
ObjectOutputStream class:
An ObjectOutputStream is used to write primitive data types and Java objects to an
OutputStream.Only objects that support the java.io.Serializable interface can be written to
streams.
2) public void flush() throws IOException {}flushes the current output stream.
1. import java.io.*;
2. class Persist{
3. public static void main(String args[])throws Exception{
4. Student s1 =new Student(211,"ravi");
5.
6. FileOutputStream fout=new FileOutputStream("f.txt");
7. ObjectOutputStream out=new ObjectOutputStream(fout);
8.
9. out.writeObject(s1);
10. out.flush();
11.
12. System.out.println("success");
13. }
14. }
1. <strong>Output:</strong>success
Deserilization:
Deserialization is the process of reconstructing the object from the serialized state.It is the
reverse operation of serialization.
ObjectInputStream class:
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.
Example of Deserialization:
1. import java.io.*;
2. class Depersist{
3. public static void main(String args[])throws Exception{
4.
5. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
6. Student s=(Student)in.readObject();
7. System.out.println(s.id+" "+s.name);
8.
9. in.close();
10. }
11. }
1. <strong>Output:</strong>211 ravi
Rule: In case of array or collection, all the objects of array or collection must be serializable,if
any object is not serialiizable then serialization will be failed.
1. import java.io.Serializable;
2.
3. public class Student implements Serializable{
Collection simply means a single unit of objects. Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
What is Collection>
What is framework?
• provides readymade architecture.
• represents set of classes and interface.
• is optional.
Collection framework
Collection framework represents a unified architecture for storing and manipulating group of
object. It has:
Do You Know ?
Method Description
public boolean addAll(collection c) is used to insert the specified collection elements in the invoking
collection.
public boolean is used to delete all the elements of specified collection from the
removeAll(Collection c) invoking collection.
public boolean retainAll(Collection is used to delete all the elements of invoking collection except the
c) specified collection.
public int size() return the total number of elements in the collection.
public void clear() removes the total no of element from the collection.
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
ArrayList class:
• uses a dynamic array for storing the elements.It extends AbstractList class and
implements List interface.
• can contain duplicate elements.
• maintains insertion order.
• not synchronized.
• random access because array works at the index basis.
• manipulation slow because a lot of shifting needs to be occured.
LinkedList class:
• uses doubly linked list to store the elements. It extends the AbstractList class and
implements List and Deque interfaces.
• can contain duplicate elements.
• maintains insertion order.
• not synchronized.
• No random access.
• manipulation fast because no shifting needs to be occured.
• can be used as list, stack or queue.
Example of LinkedList:
1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4.
5. LinkedList al=new LinkedList();
6. al.add("Ravi");
List Interface:
List Interface is the subinterface of Collection.It contains methods to insert and delete
elements in index basis.It is a factory of ListIterator interface.
ListIterator Interface:
ListIterator Interface is used to traverse the element in backward and forward direction.
HashSet class:
• uses hashtable to store the elements.It extends AbstractSet class and implements
Set interface.
• contains unique elements only.
LinkedHashSet class:
• contains unique elements only like HashSet. It extends HashSet class and
implements Set interface.
• maintains insertion order.
TreeSet class:
• contains unique elements only like HashSet. The TreeSet class implements
NavigableSet interface that extends the SortedSet interface.
• maintains ascending order.
Queue Interface:
The Queue interface basically orders the element in FIFO(First In First Out)manner.
PriorityQueue class:
The PriorityQueue class provides the facility of using queue. But it does not orders the
elements in FIFO manner.
Example of PriorityQueue:
1. import java.util.*;
2. class Simple8{
3. public static void main(String args[]){
4.
5. PriorityQueue queue=new PriorityQueue();
6. queue.add("Amit");
7. queue.add("Vijay");
8. queue.add("Karan");
9. queue.add("Jai");
Map Interface
A map contains values based on the key i.e. key and value pair.Each pair is known as an
entry.Map contains only unique elements.
3. public Object remove(object key):is used to delete an entry for the specified key.
4. public Object get(Object key):is used to return the value for the specified key.
5. public boolean containsKey(Object key):is used to search the specified key from
this map.
6. public boolean containsValue(Object value):is used to search the specified value
from this map.
7. public Set keySet():returns the Set view containing all the keys.
8. public Set entrySet():returns the Set view containing all the keys and values.
Entry
Entry is the subinterface of Map.So we will access it by Map.Entry name.It provides
methods to get key and value.
HashMap class:
• A HashMap contains values based on the key. It implements the Map interface and
extends AbstractMap class.
• It contains only unique elements.
• It may have one null key and multiple null values.
• It maintains no order.
LinkedHashMap class:
• A LinkedHashMap contains values based on the key. It implements the Map
interface and extends HashMap class.
• It contains only unique elements.
• It may have one null key and multiple null values.
• It is same as HashMap instead maintains insertion order.
TreeMap class
• A TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
• It contains only unique elements.
• It cannot have null key but can have multiple null values.
• It is same as HashMap instead maintains ascending order.
Hashtable
• A Hashtable is an array of list.Each list is known as a bucket.The position of
bucket is identified by calling the hashcode() method.A Hashtable contains values
based on the key. It implements the Map interface and extends Dictionary class.
• It contains only unique elements.
• It may have not have any null key or value.
• It is synchronized.
Example of Hashtable:
1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4.
5. Hashtable hm=new Hashtable();
6.
7. hm.put(100,"Amit");
8. hm.put(102,"Ravi");
9. hm.put(101,"Vijay");
10. hm.put(103,"Rahul");
11.
12. Set set=hm.entrySet();
13. Iterator itr=set.iterator();
14.
15. while(itr.hasNext()){
16. Map.Entry m=(Map.Entry)itr.next();
17. System.out.println(m.getKey()+" "+m.getValue());
18. }
19. }
20. }
2) HashMap can contain one null key and Hashtable cannot contain any null key
multiple null values. nor value.
Sorting
We can sort the elements of:
1. String objects
2. Wrapper class objects
3. User-defined class objects
Collections class provides static methods for sorting the elements of collection.If
collection elements are of Set type, we can use TreeSet.But We cannot sort the elements
of List.Collections class provides methods for sorting the elements of List type elements.
Note: String class and Wrapper classes implements the Comparable interface.So if you
store the objects of string or wrapper classes, it will be Comparable.
Comparable interface
Comparable interface is used to order the objects of user-defined class.This interface is
found in java.lang package and contains only one method named compareTo(Object).It
provide only single sorting sequence i.e. you can sort the elements on based on single
datamember only.For instance it may be either rollno,name,age or anything else.
Collections class provides static methods for sorting the elements of collection.If
collection elements are of Set type, we can use TreeSet.But We cannot sort the elements
of List.Collections class provides methods for sorting the elements of List type elements.
Note: String class and Wrapper classes implements the Comparable interface.So if you store
the objects of string or wrapper classes, it will be Comparable.
Simple.java
1. import java.util.*;
2. import java.io.*;
3.
4. class Simple{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10. al.add(new Student(105,"Jai",21));
11.
12. Collections.sort(al);
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. Student st=(Student)itr.next();
16. System.out.println(st.rollno+""+st.name+""+st.age);
17. }
18. }
19. }
Output:105 Jai 21
101 Vijay 23
106 Ajay 27
Comparator interface
Comparator interface is used to order the objects of user-defined class.
It provides multiple sorting sequence i.e. you can sort the elements based on any data
member. For instance it may be on rollno, name, age or anything else.
public int compare(Object obj1,Object obj2): compares the first object with second object.
Collections class provides static methods for sorting the elements of collection. If collection
elements are of Set type, we can use TreeSet. But We cannot sort the elements of List.
Collections class provides methods for sorting the elements of List type elements.
public void sort(List list,Comparator c): is used to sort the elements of List by the given
comparator.
Student.java
AgeComparator.java
NameComparator.java
Simple.java
Student.java
This class contains three fields rollno, name and age and a parameterized constructor.
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
AgeComparator.java
This class defines comparison logic based on the age. If age of first object is greater than the
second, we are returning positive value, it can be any one such as 1, 2 , 10 etc. If age of first
object is less than the second object, we are returning negative value, it can be any negative
value and if age of both objects are equal, we are returning 0.
1. import java.util.*;
2. class AgeComparator implements Comparator{
3. public int Compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. if(s1.age==s2.age)
8. return 0;
9. else if(s1.age>s2.age)
This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.
1. import java.util.*;
2. class NameComparator implements Comparator{
3. public int Compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. return s1.name.compareTo(s2.name);
8. }
9. }
Simple.java
In this class, we are printing the objects values by sorting on the basis of name and age.
1. import java.util.*;
2. import java.io.*;
3.
4. class Simple{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10. al.add(new Student(105,"Jai",21));
11.
12. System.out.println("Sorting by Name...");
13.
14. Collections.sort(al,new NameComparator());
15. Iterator itr=al.iterator();
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20.
21. System.out.println("sorting by age...");
22.
23. Collections.sort(al,new AgeComparator());
24. Iterator itr2=al.iterator();
25. while(itr2.hasNext()){
26. Student st=(Student)itr2.next();
It can be used to get property value based on the property key. The Properties class provides
methods to get data from properties file and store data into properties file. Moreover, it can be
used to get properties of system.
Easy Maintenance: If any information is changed from the properties file, you don't need to
recompile the java class. It is mainly used to contain variable information i.e. to be changed.
Method Description
public void load(InputStream is) loads data from the InputStream object
public void setProperty(String key,String value) sets the property in the properties object.
public void store(Writer w, String comment) writers the properties in the writer object.
public void store(OutputStream os, String writes the properties in the OutputStream object.
comment)
storeToXML(OutputStream os, String comment) writers the properties in the writer object for generating
xml document.
public void storeToXML(Writer w, String writers the properties in the writer object for generating
comment, String encoding) xml document with specified encoding.
db.properties
1. user=system
2. password=oracle
Now, lets create the java class to read the data from the properties file.
Test.java
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5. FileReader reader=new FileReader("db.properties");
6.
7. Properties p=new Properties();
8. p.load(reader);
9.
10. System.out.println(p.getProperty("user"));
11. System.out.println(p.getProperty("password"));
12. }
13. }
Output:system
oracle
Test.java
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=System.getProperties();
7. Set set=p.entrySet();
8.
9. Iterator itr=set.iterator();
10. while(itr.hasNext()){
11. Map.Entry entry=(Map.Entry)itr.next();
12. System.out.println(entry.getKey()+" = "+entry.getValue());
13. }
14.
15. }
16. }
Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD
...........
Test.java
1. import java.util.*;
2. import java.io.*;
info.properties
JDBC
This JDBC tutorial covers all the topics of JDBC with the simple examples. JDBC is a
Java API that is used to connect and execute query to the database. JDBC API uses jdbc
drivers to connects to the database.
Do You Know ?
• How to connect Java application with Oracle and Mysql database using
JDBC?
• What is the difference between Statement and PreparedStatement interface?
• How to print total numbers of tables and views of a database using JDBC ?
• How to store and retrieve images from Oracle database using JDBC?
• How to store and retrieve files from Oracle database using JDBC?
What is API?
API (Application programming interface) is a document that contains description of all
the features of a product or software. It represents classes and interfaces that software
programs can follow to communicate with each other. An API can be created for
applications, libraries, operating systems, etc
2) JDBC Drivers
In this JDBC tutorial, we will learn 4 types of JDBC drivers, their advantages and
disadvantages.
In this JDBC tutorial, we will see the 5 steps to connect to the database in java using
JDBC.
In this JDBC tutorial, we will connect a simple java program with the oracle database.
In this JDBC tutorial, we will connect a simple java program with the mysql database.
Let's connect java application with access database with and without DSN.
7) DriverManager class
In this JDBC tutorial, we will learn what does the DriverManager class and what are its
methods.
8) Connection interface
In this JDBC tutorial, we will learn what is Connection interface and what are its methods.
In this JDBC tutorial, we will learn what is Statement interface and what are its methods.
In this JDBC tutorial, we will learn what is ResultSet interface and what are its methods.
Moreover, we will learn how we can make the ResultSet scrollable.
In this JDBC tutorial, we will learn what is benefit of PreparedStatement over Statement
interface. We will see examples to insert, update or delete records using the
PreparedStatement interface.
In this JDBC tutorial, we will learn how we can get the metadata of a table.
In this JDBC tutorial, we will learn how we can get the metadata of a database.
Let's learn how to store image in the oracle database using JDBC.
Let's see the simple example to retrieve image from the oracle database using JDBC.
Let's see the simple example to store file in the oracle database using JDBC.
Let's see the simple example to retrive file from the oracle database using JDBC.
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database.There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
Advantages:
• easy to use.
• can be easily connected to any database.
Disadvantages:
• Performance degraded because JDBC method call is converted into the ODBC
funcion calls.
• The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.
Advantage:
• performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
• The Native driver needs to be installed on the each client machine.
• The Vendor client library needs to be installed on client machine.
Disadvantages:
• Network support is required on client machine.
• Requires database-specific coding to be done in the middle tier.
• Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol.
That is why it is known as thin driver. It is fully written in Java language.
Advantage:
• Better performance than all other drivers.
• No software is required at client side or server side.
Disadvantage:
• Drivers depends on the Database.
1. import java.sql.*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. //step1 load the driver class
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7.
8. //step2 create the connection object
9. Connection con=DriverManager.getConnection(
10. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
11.
12. //step3 create the statement object
13. Statement stmt=con.createStatement();
14.
15. //step4 execute query
16. ResultSet rs=stmt.executeQuery("select * from emp");
17. while(rs.next())
18. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
19.
20. //step5 close the connection object
21. con.close();
22.
23. }catch(Exception e){ System.out.println(e);}
24.
25. }
26. }
The above example will fetch all the records of emp table.
To connect java application with the Oracle database ojdbc14.jar file is required to be
loaded.
2) set classpath:
There are two ways to set the classpath:
• temporary
• permament
1. C:>set classpath=c:\folder\ojdbc14.jar;.;
In this example we are using MySql as the database. So we need to know following
informations for the mysql database:
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
isjdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address,
3306 is the port number and sonoo is the database name. We may use any database, in
such case, you need to replace the sonoo with your database name.
3. Username: The default username for the mysql database is root.
4. Password: Password is given by the user at the time of installing the mysql database.
In this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create
database first.
1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:mysql://localhost:3306/sonoo","root","root");
9.
10. //here sonoo is database name, root is username and password
11.
12. Statement stmt=con.createStatement();
13.
14. ResultSet rs=stmt.executeQuery("select * from emp");
15.
16. while(rs.next())
17. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
18.
19. con.close();
20.
21. }catch(Exception e){ System.out.println(e);}
22.
23. }
24. }
The above example will fetch all the records of emp table.
To connect java application with the mysql database mysqlconnector.jar file is required to
be loaded.
2) set classpath:
There are two ways to set the classpath:
• temporary
• permament
1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;
Java is mostly used with Oracle, mysql, or DB2 database. So you can learn this topic only for
knowledge.
1. import java.sql.*;
2. class Test{
3. public static void main(String ar[]){
4. try{
5. String database="student.mdb";//Here database exists in the current directory
6.
7. String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};
8. DBQ=" + database + ";DriverID=22;READONLY=true";
1. import java.sql.*;
2. class Test{
3. public static void main(String ar[]){
4. try{
5. String url="jdbc:odbc:mydsn";
6. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
7. Connection c=DriverManager.getConnection(url);
8. Statement st=c.createStatement();
9. ResultSet rs=st.executeQuery("select * from login");
10.
11. while(rs.next()){
12. System.out.println(rs.getString(1));
13. }
14.
15. }catch(Exception ee){System.out.println(ee);}
16.
17. }}
DriverManager class:
The DriverManager class acts as an interface between user and drivers. It keeps track of
the drivers that are available and handles establishing a connection between a database
and the appropriate driver. The DriverManager class maintains a list of Driver classes that
have registered themselves by calling the method DriverManager.registerDriver().
Connection interface:
A Connection is the session between java application and database. The Connection
interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object
of Connection can be used to get the object of Statement and DatabaseMetaData. The
Connection interface provide many methods for transaction management like
commit(),rollback() etc.
4) public void commit(): saves the changes made since the previous commit/rollback
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
Statement interface
The Statement interface provides methods to execute queries with the database. The
statement interface is a factory of ResultSet i.e. it provides factory method to get the object of
ResultSet.
3) public boolean execute(String sql): is used to execute queries that may return multiple
results.
1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");
7. Statement stmt=con.createStatement();
8.
9. //stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
10. //int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 where id=3
3");
ResultSet interface
The object of ResultSet maintains a cursor pointing to a particular row of data. Initially,
cursor points to before the first row.
By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in
createStatement(int,int) method as well as we can make this object as updatable by:
1) public boolean next(): is used to move the cursor to the one row next from the current
position.
2) public boolean previous(): is used to move the cursor to the one row previous from the current
position.
3) public boolean first(): is used to move the cursor to the first row in result set object.
4) public boolean last(): is used to move the cursor to the last row in result set object.
5) public boolean absolute(int row): is used to move the cursor to the specified row number in the ResultSet
object.
6) public boolean relative(int row): is used to move the cursor to the relative row number in the ResultSet
object, it may be positive or negative.
7) public int getInt(int is used to return the data of specified column index of the current row
columnIndex): as int.
8) public int getInt(String is used to return the data of specified column name of the current row
columnName): as int.
9) public String getString(int is used to return the data of specified column index of the current row
columnIndex): as String.
10) public String getString(String is used to return the data of specified column name of the current row
columnName): as String.
1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");
7. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CO
NCUR_UPDATABLE);
8. ResultSet rs=stmt.executeQuery("select * from emp765");
9.
10. //getting the record of 3rd row
11. rs.absolute(3);
12. System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
13.
14. con.close();
15. }}
PreparedStatement:
The PreparedStatement interface is a subinterface of Statement. It is used to exeucte
parameterized query.
DatabaseMetaData interface:
DatabaseMetaData interface provides methods to get meta data of a database such as
database product name, database product version, driver name, name of total number of
tables, name of total number of views etc.
For storing image into the database, BLOB (Binary Large Object) datatype is used in the
table. For example:
Let's write the jdbc code to store the image in the database. Here we are using d:\\d.jpg for
the location of image. You can change it according to the image location.
1. import java.sql.*;
2. import java.io.*;
3. public class InsertImage {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("insert into imgtable values(?,?)");
11. ps.setString(1,"sonoo");
12.
13. FileInputStream fin=new FileInputStream("d:\\g.jpg");
14. ps.setBinaryStream(2,fin,fin.available());
15. int i=ps.executeUpdate();
16. System.out.println(i+" records affected");
17.
18. con.close();
19. }catch (Exception e) {e.printStackTrace();}
20. }
If you see the table, record is stored in the database but image will not be shown. To do so,
you need to retrieve the image from the database which we are covering in the next page.
The getBlob() method of PreparedStatement is used to get Binary information, it returns the
instance of Blob. After calling the getBytes() method on the blob object, we can get the array
of binary information that can be written into the image file.
Now let's write the code to retrieve the image from the database and write it into the directory
so that it can be displayed.
In AWT, it can be displayed by the Toolkit class. In servlet, jsp, or html it can be displayed
by the img tag.
1. import java.sql.*;
2. import java.io.*;
3. public class RetrieveImage {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("select * from imgtable");
11. ResultSet rs=ps.executeQuery();
12. if(rs.next()){//now on 1st row
13.
14. Blob b=rs.getBlob(2);//2 means 2nd column data
15. byte barr[]=b.getBytes(1,(int)b.length());//1 means first image
16.
Kiran Sir 9866243099 Page 306
Core Java
17. FileOutputStream fout=new FileOutputStream("d:\\sonoo.jpg");
18. fout.write(barr);
19.
20. fout.close();
21. }//end of if
22. System.out.println("ok");
23.
24. con.close();
25. }catch (Exception e) {e.printStackTrace(); }
26. }
27. }
Syntax:
1) public void setBinaryStream(int paramIndex,InputStream stream)throws SQLException
For storing file into the database, CLOB (Character Large Object) datatype is used in the
table. For example:
Let's see the table structure of this example to retrieve the file.
The example to retrieve the file from the Oracle database is given below.
1. import java.io.*;
2. import java.sql.*;
3.
4. public class RetrieveFile {
5. public static void main(String[] args) {
6. try{
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection(
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.
11. PreparedStatement ps=con.prepareStatement("select * from filetable");
12. ResultSet rs=ps.executeQuery();
13. rs.next();//now on 1st row
14.
15. Clob c=rs.getClob(2);
CallableStatement Interface
To call the stored procedures and functions, CallableStatement interface is used.
We can have business logic on the database by the use of stored procedures and functions that
will make the performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may create
a function that receives date as the input and returns age of the employee as the output.
must not have the return type. must have the return type.
We can call functions from the procedure. Procedure cannot be called from function.
Procedure supports input and output parameters. Function supports only input parameter.
Exception handling using try/catch block can be Exception handling using try/catch can't be used in
used in stored procedures. user defined functions.
The differences between stored procedures and functions are given below:
In this example, we are going to call the stored procedure INSERTR that receives id and
name as the parameter and inserts it into the table user420. Note that you need to create the
user420 table as well to run this application.
1. import java.sql.*;
2. public class Proc {
3. public static void main(String[] args) throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
Now check the table in the database, value is inserted in the user420 table.
The Types class defines many constants such as INTEGER, VARCHAR, FLOAT,
DOUBLE, BLOB, CLOB etc.
1. import java.sql.*;
2.
3. public class FuncSum {
4. public static void main(String[] args) throws Exception{
5.
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
The ACID properties describes the transaction management well. ACID stands for Atomicity,
Consistency, isolation and durability.
Consistency ensures bringing the database from one consistent state to another consistent
state.
Durability means once a transaction has been committed, it will remain so, even in the event
of errors, power loss etc.
fast performance It makes the performance fast because database is hit at the time of
commit.
Method Description
void setAutoCommit(boolean status) It is true bydefault means each transaction is committed bydefault.
1. import java.sql.*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");
6. con.setAutoCommit(false);
7.
8. Statement stmt=con.createStatement();
9. stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
10. stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
11.
If you see the table emp400, you will see that 2 records has been added.
1. import java.sql.*;
2. import java.io.*;
3. class TM{
4. public static void main(String args[]){
5. try{
6.
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");
9. con.setAutoCommit(false);
10.
11. PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");
12.
13. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
14. while(true){
15.
16. System.out.println("enter id");
17. String s1=br.readLine();
18. int id=Integer.parseInt(s1);
19.
20. System.out.println("enter name");
21. String name=br.readLine();
22.
23. System.out.println("enter salary");
24. String s3=br.readLine();
25. int salary=Integer.parseInt(s3);
26.
27. ps.setInt(1,id);
28. ps.setString(2,name);
29. ps.setInt(3,salary);
30. ps.executeUpdate();
31.
32. System.out.println("commit/rollback");
33. String answer=br.readLine();
34. if(answer.equals("commit")){
35. con.commit();
36. }
37. if(answer.equals("rollback")){
38. con.rollback();
It will ask to add more records until you press n. If you press n, transaction is commited.
Fast Performance
Method Description
1. import java.sql.*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");
6. con.setAutoCommit(false);
7.
8. Statement stmt=con.createStatement();
9. stmt.addBatch("insert into user420 values(190,'abhi',40000)");
10. stmt.addBatch("insert into user420 values(191,'umesh',50000)");
11.
12. stmt.executeBatch();//executing the batch
13.
14. con.commit();
15. con.close();
16. }}
If you see the table user420, two records has been added.
It will add the queries into the batch until user press n. Finally it executes the batch. Thus all
the added queries will be fired.
JDBC RowSet
The instance of RowSet is the java bean component because it has properties and java bean
notification mechanism. It is introduced since JDK 5.
It is the wrapper of ResultSet. It holds tabular data like ResultSet but it is easy and flexible to
use.
• JdbcRowSet
• CachedRowSet
• WebRowSet
• JoinRowSet
Advantage of RowSet
1. import java.sql.Connection;
2. import java.sql.DriverManager;
3. import java.sql.ResultSet;
4. import java.sql.Statement;
5. import javax.sql.RowSetEvent;
6. import javax.sql.RowSetListener;
7. import javax.sql.rowset.JdbcRowSet;
8. import javax.sql.rowset.RowSetProvider;
9.
10. public class RowSetExample {
11. public static void main(String[] args) throws Exception {
12. Class.forName("oracle.jdbc.driver.OracleDriver");
13.
14. //Creating and Executing RowSet
15. JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
16. rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
17. rowSet.setUsername("system");
18. rowSet.setPassword("oracle");
19.
20. rowSet.setCommand("select * from emp400");
21. rowSet.execute();
22.
Kiran Sir 9866243099 Page 318
Core Java
23. while (rowSet.next()) {
24. // Generating cursor Moved event
25. System.out.println("Id: " + rowSet.getString(1));
26. System.out.println("Name: " + rowSet.getString(2));
27. System.out.println("Salary: " + rowSet.getString(3));
28. }
29.
30. }
31. }
1. Id: 55
2. Name: Om Bhim
3. Salary: 70000
4. Id: 190
5. Name: abhi
6. Salary: 40000
7. Id: 191
8. Name: umesh
9. Salary: 50000
The RowSetListener interface provides 3 method that must be implemented. They are as
follows:
Let's write the code to retrieve the data and perform some additional tasks while cursor is
moved, cursor is changed or rowset is changed. The event handling operation can't be
performed using ResultSet so it is preferred now.
1. import java.sql.Connection;
2. import java.sql.DriverManager;
3. import java.sql.ResultSet;
4. import java.sql.Statement;
5. import javax.sql.RowSetEvent;
6. import javax.sql.RowSetListener;
7. import javax.sql.rowset.JdbcRowSet;
8. import javax.sql.rowset.RowSetProvider;
9.
10. public class RowSetExample {
1. Cursor Moved...
2. Id: 55
3. Name: Om Bhim
4. Salary: 70000
5. Cursor Moved...
6. Id: 190
7. Name: abhi
8. Salary: 40000
9. Cursor Moved...
10. Id: 191
11. Name: umesh
Here, we are going to see the features included in Jdbc 3.0 and Jdbc 4.0.
• Jdbc RowSet We have done the great discussion on JdbcRowSet in the previous
page.
• Savepoint in transaction management Now you are able to create, rollback and
release the savepoint by Connection.setSavepoint(), Connection.rollback(Savepoint
svpt) and Connection.releaseSavepoint(Savepoint svpt) methods.
• Statement and ResultSet Caching for Connection Pooling Now you are able to
reuse the statement and result set because jdbc 3 provides you the facility of statement
caching and result set caching.
• Switching between Global and Local Transactions
• Retrieval of auto generated keys Now you are able to get the auto generated keys by
the method getGeneratedKeys().
• Automatic Loading of Driver class You don't need to write Class.forName() now
because it is loaded bydefault since jdbc4.
• Subclasses of SQLException Jdbc 4 provides new subclasses of SQLException class
for better readability and handling.
• New methods There are many new methods introduced in Connection,
PreparedStatement, CallableStatement, ResultSet etc.
• Improved DataSource Now data source implemenation is improved.
• Event Handling support in Statement for Connection Pooling Now Connection
Pooling can listen statement error and statement closing events.
The java.lang.Class class provides many methods that can be used to get metadata, examine
and change the runtime behaviour of a class.
Where is it used?
The Reflection API is mainly used in:
• IDE (Integreted Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.
• Debugger
• Test Tools etc.
2) public static Class forName(String className)throws ClassNotFoundException loads the class and returns the
reference of Class class.
11) public Method getDeclaredMethod(String name,Class[] parameterTypes)throws returns the method class instance.
NoSuchMethodException,SecurityException
Do You Know ?
• How many ways we can get the instance of Class class ?
• How to create the javap tool ?
• How to create the appletviewer tool ?
• How to access the private method from outside the class ?
java.lang.Class class
The java.lang.Class class performs mainly two tasks:
• provides methods to get the metadata of a class at runtime.
• provides methods to examine and change the runtime behaviour of a class.
1. class Simple{}
2.
3. class Test{
4. public static void main(String args[]){
5. Class c=Class.forName("Simple");
6. System.out.println(c.getName());
7. }
8. }
Output:Simple
1. class Simple{}
2.
3. class Test{
4. void printName(Object obj){
5. Class c=obj.getClass();
6. System.out.println(c.getName());
7. }
8. public static void main(String args[]){
9. Simple s=new Simple();
10.
11. Test t=new Test();
12. t.printName(s);
13. }
14. }
15.
Output:Simple
1. class Test{
2. public static void main(String args[]){
3. Class c = boolean.class;
4. System.out.println(c.getName());
5.
6. Class c2 = Test.class;
7. System.out.println(c2.getName());
8. }
9. }
Output:boolean
2) public boolean isArray(): determines if this Class object represents an array class.
Let's see the simple example of reflection api to determine the object type.
1. class Simple{}
2. interface My{}
3.
4. class Test{
5. public static void main(String args[]){
6. try{
7. Class c=Class.forName("Simple");
8. System.out.println(c.isInterface());
9.
10. Class c2=Class.forName("My");
11. System.out.println(c2.isInterface());
12.
13. }catch(Exception e){System.out.println(e);}
14.
15. }
16. }
Output:false
true
newInstance() method
The newInstance() method of Class class and Constructor class is used to create a new
instance of the class.
The newInstance() method of Class class can invoke zero-argument constructor whereas
newInstance() method of Constructor class can invoke any number of arguments. So
Constructor class is preferred over Class class.
Here T is the generic version. You can think it like Object class. You will learn about
generics later.
1. class Simple{
2. void message(){System.out.println("Hello Java");}
3. }
4.
5. class Test{
6. public static void main(String args[]){
7. try{
8. Class c=Class.forName("Simple");
9. Simple s=(Simple)c.newInstance();
10. s.message();
11.
12. }catch(Exception e){System.out.println(e);}
13.
14. }
15. }
Output:Hello java
Method Description
public Field[] getDeclaredFields()throws returns an array of Field objects reflecting all the fields
SecurityException declared by the class or interface represented by this
Class object.
public Method[] getDeclaredMethods()throws returns an array of Method objects reflecting all the
1. import java.lang.reflect.*;
2.
3. public class MyJavap{
4. public static void main(String[] args)throws Exception {
5. Class c=Class.forName(args[0]);
6.
7. System.out.println("Fields........");
8. Field f[]=c.getDeclaredFields();
9. for(int i=0;i<f.length;i++)
10. System.out.println(f[i]);
11.
12. System.out.println("Constructors........");
13. Constructor con[]=c.getDeclaredConstructors();
14. for(int i=0;i<con.length;i++)
15. System.out.println(con[i]);
16.
17. System.out.println("Methods........");
18. Method m[]=c.getDeclaredMethods();
19. for(int i=0;i<m.length;i++)
20. System.out.println(m[i]);
21. }
22. }
At runtime, you can get the details of any class, it may be user-defined or pre-defined class.
1. import java.applet.Applet;
2. import java.awt.Frame;
3. import java.awt.Graphics;
4.
5. public class MyViewer extends Frame{
6. public static void main(String[] args) throws Exception{
7. Class c=Class.forName(args[0]);
8.
9. MyViewer v=new MyViewer();
10. v.setSize(400,400);
11. v.setLayout(null);
12. v.setVisible(true);
13.
14. Applet a=(Applet)c.newInstance();
15. a.start();
16. Graphics g=v.getGraphics();
17. a.paint(g);
18. a.stop();
19.
20. }
21.
22. }
1. //simple program of applet
2.
3. import java.applet.Applet;
4. import java.awt.Graphics;
5.
6. public class First extends Applet{
7.
8. public void paint(Graphics g){g.drawString("Welcome",50, 50);}
9. }
Output:
By the help of java.lang.Class class and java.lang.reflect.Method class, we can call private
method from any other class.
File: A.java
1. public class A {
2. private void message(){System.out.println("hello java"); }
3. }
File: MethodCall.java
1. import java.lang.reflect.Method;
2. public class MethodCall{
3. public static void main(String[] args)throws Exception{
4.
5. Class c = Class.forName("A");
6. Object o= c.newInstance();
7. Method m =c.getDeclaredMethod("message", null);
8. m.setAccessible(true);
9. m.invoke(o, null);
10. }
11. }
Output:hello java
File: A.java
1. class A{
2. private void cube(int n){System.out.println(n*n*n);}
3. }
File: M.java
1. import java.lang.reflect.*;
2. class M{
3. public static void main(String args[])throws Exception{
4. Class c=A.class;
5. Object obj=c.newInstance();
6.
7. Method m=c.getDeclaredMethod("cube",new Class[]{int.class});
8. m.setAccessible(true);
9. m.invoke(obj,4);
10. }}
Output:64
Localization is also abbreviated as I10N because there are total 10 characters between the
first letter 'L' and last letter 'N'. Localization is the mechanism to create such an application
that can be adapted to a specific language and region by adding locale-specific text and
component.
Do You Know ?
• What is the use of Locale class ?
• How can we globalize the messages (or) What is the use of ResourceBundle
class?
• How can we internationalize the date, time, number, currency and
measurements?
Before starting the internationalization, Let's first understand what are the informations
that differ from one region to another. There is the list of culturally dependent data:
• Messages
• Dates
• Times
• Numbers
• Currencies
• Measurements
• Phone Numbers
• Postal Addresses
• Labels on GUI components etc.
1.
An object of Locale class represents a geographical or cultural region. This object can be
used to get the locale specific information such as country name, language, variant etc.
1. Locale(String language)
2. Locale(String language, String country)
3. Locale(String language, String country, String variant)
1. import java.util.*;
2. public class LocaleExample {
3. public static void main(String[] args) {
4. Locale locale=Locale.getDefault();
5. //Locale locale=new Locale("fr","fr");//for the specific locale
6.
7. System.out.println(locale.getDisplayCountry());
8. System.out.println(locale.getDisplayLanguage());
9. System.out.println(locale.getDisplayName());
10. System.out.println(locale.getISO3Country());
11. System.out.println(locale.getISO3Language());
12. System.out.println(locale.getLanguage());
13. System.out.println(locale.getCountry());
14.
15. }
16. }
Output:United States
English
English (United States)
USA
eng
1. import java.util.*;
2. public class LocaleExample2 {
3. public static void main(String[] args) {
4. Locale enLocale = new Locale("en", "US");
5. Locale frLocale = new Locale("fr", "FR");
6. Locale esLocale = new Locale("es", "ES");
7. System.out.println("English language name (default): " +
8. enLocale.getDisplayLanguage());
9.
10. System.out.println("English language name in French: " +
11. enLocale.getDisplayLanguage(frLocale));
12. System.out.println("English language name in spanish: " +
13. enLocale.getDisplayLanguage(esLocale));
14. }
15.
16. }
Output:English language name (default): English
English language name in French: anglais
English language name in spanish: ingl???s
1. import java.util.*;
2. public class LocaleEx {
3. public static void main(String[] args) {
4. Locale[] locales = { new Locale("en", "US"),
5. new Locale("es", "ES"), new Locale("it", "IT") };
6.
7. for (int i=0; i< locales.length; i++) {
8. String displayLanguage = locales[i].getDisplayLanguage(locales[i]);
9. System.out.println(locales[i].toString() + ": " + displayLanguage);
10. }
11. }
12.
13. }
Output:en_US: English
es_ES: espa???ol
it_IT: italiano
The hardcoded message is not considered good in terms of programming, because it differs
from one country to another. So we use the ResourceBundle class to globalize the massages.
The ResourceBundle class loads these informations from the properties file that contains the
messages.
MessageBundle_en_US.properties
MessageBundle_in_ID.properties
InternationalizationDemo.java
1. import java.util.Locale;
2. import java.util.ResourceBundle;
3. public class InternationalizationDemo {
4. public static void main(String[] args) {
5.
6. ResourceBundle bundle = ResourceBundle.getBundle("MessageBundle", Locale.US);
7. System.out.println("Message in "+Locale.US +":"+bundle.getString("greeting"));
8.
9. //changing the default locale to indonasian
10. Locale.setDefault(new Locale("in", "ID"));
11. bundle = ResourceBundle.getBundle("MessageBundle");
12. System.out.println("Message in "+Locale.getDefault()+":"+bundle.getString("greeting"));
13.
14. }
15. }
Output:Message in en_US : Hello, how r u?
Message in in_ID : halo, apa kabar?
1. import java.text.DateFormat;
2. import java.util.*;
3. public class InternationalizationDate {
4.
5. static void printDate(Locale locale){
6. DateFormat formatter=DateFormat.getDateInstance(DateFormat.DEFAULT,locale);
7. Date currentDate=new Date();
8. String date=formatter.format(currentDate);
9. System.out.println(date+" "+locale);
10. }
11.
12. public static void main(String[] args) {
13. printDate(Locale.UK);
14. printDate(Locale.US);
15. printDate(Locale.FRANCE);
16. }
17. }
Output:01-Mar-2012 en_GB
Mar 1, 2012 en_US
1 mars 2012 fr_FR
For internationalizing the time, the DateFormat class provides some useful methods.
The getTimeInstance() method of the DateFormat class returns the instance of the
DateFormat class for the specified style and locale.
1. import java.text.DateFormat;
2. import java.util.*;
3.
4. public class InternationalizingTime {
5.
6. static void printTime(Locale locale){
7. DateFormat formatter=DateFormat.getTimeInstance(DateFormat.DEFAULT,locale);
8. Date currentDate=new Date();
9. String time=formatter.format(currentDate);
10. System.out.println(time+" in locale "+locale);
11. }
12.
13. public static void main(String[] args) {
14. printTime(Locale.UK);
15. printTime(Locale.US);
16. printTime(Locale.FRANCE);
17. }
18. }
The NumberFormat class is used to format the number according to the specific locale. To
get the instance of the NumberFormat class, we need to call
either getInstance() or getNumberInstance()methods.
1. import java.text.NumberFormat;
2. import java.util.*;
3.
4. public class InternalizationNumber {
5.
6. static void printNumber(Locale locale){
7. double dbl=105000.3245;
8. NumberFormat formatter=NumberFormat.getNumberInstance(locale);
9. String number=formatter.format(dbl);
10. System.out.println(number+" for the locale "+locale);
11. }
12.
13. public static void main(String[] args) {
14. printNumber(Locale.UK);
15. printNumber(Locale.US);
16. printNumber(Locale.FRANCE);
17. printNumber(Locale.JAPAN);
18.
19. }
20. }
The NumberFormat class provides methods to format the currency according to the locale.
ThegetCurrencyInstance() method of the NumberFormat class returns the instance of the
NumberFormat class.
1. import java.text.NumberFormat;
2. import java.util.*;
3. public class InternalizationCurrency {
4.
5. static void printCurrency(Locale locale){
6. double dbl=10500.3245;
7. NumberFormat formatter=NumberFormat.getCurrencyInstance(locale);
8. String currency=formatter.format(dbl);
9. System.out.println(currency+" for the locale "+locale);
10. }
11.
12. public static void main(String[] args) {
13. printCurrency(Locale.UK);
14. printCurrency(Locale.US);
15. printCurrency(Locale.FRANCE);
16. }
17. }
Do You Know ?
J2SE 4 Features
• Assertion (Java 4)
J2SE 5 Features
The important features of J2SE 5 are generics and assertions. Others are auto-boxing,
enum, var-args, static import, for-each loop (enhanced for loop etc.
• For-each loop (Java 5)
• Varargs (Java 5)
• Static Import (Java 5)
• Autoboxing and Unboxing (Java 5)
• Enum (Java 5)
• Covariant Return Type (Java 5)
• Annotation (Java 5)
• Generics (Java 5)
JavaSE 7 Features
The important features of JavaSE 7 are try with resource, catching multiple exceptions etc.
Assertion:
Assertion is a statement in java. It can be used to test your assumptions about the program.
While executing assertion, it is believed to be true. If it fails, JVM will throw an error
named AssertionError. It is mainly used for testing purpose.
Advantage of Assertion:
It provides an effective way to detect and correct programming errors.
1. assert expression;
and second way is:
If you use assertion, It will not run simply because assertion is disabled by default. To
enable the assertion,-ea or -enableassertions switch of java must be used.
Advantage of Varargs:
We don't have to provide overloaded methods so less code.
Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:
Static Import:
The static import feature of Java 5 facilitate the java programmer to access any static
member of a class directly. There is no need to qualify it by the class name.
1.
2. class UnboxingExample1{
3. public static void main(String args[]){
4. Integer i=new Integer(50);
5. int a=i;
6.
7. System.out.println(a);
Kiran Sir 9866243099 Page 350
Core Java
8. }
9. }
10.
Output:50
1.
2. class UnboxingExample1{
3. public static void main(String args[]){
4. Integer i=new Integer(50);
5.
6. if(i<100){ //unboxing internally
7. System.out.println(i);
8. }
9. }
10. }
11.
Output:50
1.
2. class Boxing1{
3. static void m(int i){System.out.println("int");}
4. static void m(Integer i){System.out.println("Integer");}
5.
6. public static void main(String args[]){
7. short s=30;
8. m(s);
9. }
10. }
11.
Output:int
1.
2. class Boxing2{
3. static void m(int i, int i2){System.out.println("int int");}
4. static void m(Integer... i){System.out.println("Integer...");}
5.
6. public static void main(String args[]){
7. short s1=30,s2=40;
8. m(s1,s2);
9. }
10. }
11.
Output:int int
1.
2. class Boxing3{
3. static void m(Integer i){System.out.println("Integer");}
4. static void m(Integer... i){System.out.println("Integer...");}
5.
6. public static void main(String args[]){
7. int a=30;
8. m(a);
9. }
10. }
11.
Output:Integer
1.
2. class Boxing3{
3. static void m(Long l){System.out.println("Long");}
4.
5. public static void main(String args[]){
6. int a=30;
7. m(a);
8. }
9. }
10.
Output:Compile Time Error
Enum
An enum is a data type which contains fixed set of constants. It can be used for days of the
week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and
SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The enum constants
are static and final implicitely. It is available from Java 5. Enums can be thought of as
classes that have fixed set of constants.
Defining enum:
The enum can be defined within or outside the class because it is similar to a class.
Output:WINTER 5
SPRING 10
SUMMER 15
FALL 20
Output:monday
Java Annotation
Annotation is a tag that represents the metadata. It is attached with class, interface, methods
or fields to indicate some additional information that can be used by java compiler and JVM.
Built-In Annotations
There are several built-in annoations. Some annotations are applied to java code and some to
other annotations.
@Override
@Override annotation assures that the subclass method is overriding the parent class method.
If it is not so, compile time error occurs.
Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to mark
@Override annotation that provides assurity that method is overridden.
1. class Animal{
2. void eatSomething(){System.out.println("eating something");}
3. }
4.
5. class Dog extends Animal{
6. @Override
@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.
1. import java.util.*;
2. class Test{
3. @SuppressWarnings("unchecked")
4. public static void main(String args[]){
5.
6. ArrayList list=new ArrayList();
7. list.add("sonoo");
8. list.add("vimal");
9. list.add("ratan");
10.
11. for(Object obj:list)
12. System.out.println(obj);
13.
14. }}
Now no warning at compile time.
@Deprecated
@Deprecated annoation marks that this method is deprecated so compiler prints warning. It
informs user that it may be removed in the future versions. So, it is better not to use such
methods.
1. class A{
2. void m(){System.out.println("hello m");}
3.
4. @Deprecated
5. void n(){System.out.println("hello n");}
6. }
Custom Annotation
Creating, Applying and Accessing Custom Annotation
Custom Annotation
We can create the user-defined annotations also. The @interface element is used to declare an
annotation. For example:
1. @interface MyAnnotation{}
Points to remember for annotation signature
Types of Annotation
There are three types of annotations.
1. Marker Annotation
2. Single-Value Annotation
3. Multi-Value Annotation
1. @interface MyAnnotation{}
2) Single-Value Annotation
An annotation that has one method, is called Single-Value annotation. For example:
1. @interface MyAnnotation{
2. int value();
3. }
1. @interface MyAnnotation{
2. int value() default 0;
3. }
1. @MyAnnotation(value=10)
3) Mulit-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation. For example:
1. @interface MyAnnotation{
2. int value1();
3. String value2();
4. String value3();
5. }
6. }
1. @interface MyAnnotation{
2. int value1() default 1;
3. String value2() default "";
4. String value3() default "xyz";
1. @MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")
@Target
@Target tag is used to specify at which type, the annotation is used.
FIELD fields
METHOD methods
CONSTRUCTOR constructors
PARAMETER parameter
@Retention
@Retention annotation is used to specify to what level annotation will be available.
RetentionPolicy Availability
In real scenario, java programmer only need to apply annotation. He/She doesn't need to
create and access annotation. Creating and Accessing annotation is performed by the
implementation provider. On behalf of the annotation, java compiler or JVM performs some
additional operations.
@Inherited
By default, annotations are not inherited to subclasses. The @Inherited annotation marks the
annotation to be inherited to subclasses.
1. @Inherited
2. @interface ForEveryone { }//Now it will be available to subclass also
3.
4. @interface ForEveryone { }
5. class Superclass{}
6.
7. class Subclass extends Superclass{}
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
Before generics, we can store any type of objects in collection i.e. non-generic. Now
generics, forces the java programmer to store specific type of objects.
1) Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to
store other objects.
1. ClassOrInterface<Type>
Simple example to use Generics
1. ArrayList<String>
1. import java.util.*;
2. class Simple{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Output:element is: jai
rahul
jai
1. import java.util.*;
2. class Test{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(1,"vijay");
6. map.put(4,"umesh");
7. map.put(2,"ankit");
8.
9. //Now use Map.Entry for Set and Iterator
10. Set<Map.Entry<Integer,String>> set=map.entrySet();
11.
12. Iterator<Map.Entry<Integer,String>> itr=set.iterator();
13. while(itr.hasNext()){
14. Map.Entry e=itr.next();//no need to typecast
15. System.out.println(e.getKey()+" "+e.getValue());
16. }
Generic class
A class that can refer to any type is known as generic class. Here, we are using T type
parameter to create the generic class of specific type.
Let’s see the simple example to create and use the generic class.
1. class MyGen<T>{
2. T obj;
3. void add(T obj){this.obj=obj;}
4. T get(){return obj;}
5. }
The T type indicates that it can refer to any type (like String, Integer, Employee etc.). The
type you specify for the class, will be used to store and retrieve the data.
1. class UseGen{
2. public static void main(String args[]){
3. MyGen<Integer> m=new MyGen<Integer>();
4. m.add(2);
5. //m.add("vivek");//Compile time error
6. System.out.println(m.get());
7. }}
Output:2
1. T - Type
2. E - Element
3. K - Key
Generic Method
Like generic class, we can create generic method that can accept any type of argument.
Let’s see a simple example of java generic method to print array elements. We are using
here E to denote the element.