Java Complete Tutorial
Java Complete Tutorial
com/internal-details-of-hello-java-program
Java Tutorial
1. Java - What, Where and Why?
2. What is Java
3. Where Java is used
4. Java Applications
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.
Platform Any hardware or software environment in which a
program runs, known as a platform. Since Java has its own
Runtime Environment (JRE) and API, it is called 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. Desktop Applications such as acrobat reader, media player,
antivirus etc.
2. Web Applications such as irctc.co.in, javatpoint.com etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.
Do You Know ?
What is the difference between JRE and JVM ?
James Gosling
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.
Simple
2.
Object-Oriented
3.
Platform Independent
4.
secured
5.
Robust
6.
Architecture Neutral
7.
Portable
8.
High Performance
9.
Distributed
10.
Multi-threaded
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
6.Architecture neutral
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.
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.Windows,Linux,Sun Solaris,Mac/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.
class Simple{
public static void main(String args[]){
System.out.println("Hello Java")
}
}
save this file as Simple.java
To compile:
javac Simple.java
To execute:
java Simple
Output:Hello Java
Understanding first java program
Let's see what is the meaning of class, public, static, void, main,
String[], System.out.println().
class is used to declare a class in java.
public is an access modifier which represents visibility, it
means it is visible to all.
static is a keyword, if we declare any method as static, it is
known as static method. The core advantage of static
method is that there is no need to create object to invoke
the static method. The main method is executed by the JVM,
so it doesn't require to create object to invoke the main
method. So it saves memory.
void is the return type of the method, it means it doesn't
return any value.
main represents startup of the program.
String[] args is used for command line argument. We will
learn it later.
System.out.println() is used print statement.
javac Simple.java
To execute:
java Simple
need to set path. Path is not required in such a case if you save
your program inside the jdk/bin folder. But its good approach to
set path. Click here for How to set path in java.
Q)Can you save a java source file by other name than the class name?
Yes, like the figure given below illustrates:
To compile:
javac Hard.java
To execute:
java Simple
2.
8)click on ok button
9)click on ok button
export PATH=$PATH:/home/jdk1.6.01/bin/
Here, we have installed the JDK in the home directory under
Root (/home).
Understanding the difference between JDK, JRE and JVM is important in Jav
JVM
JVM (Java Virtual Machine) is an abstract machine.It is a specification that p
JVMs are available for many hardware and software platforms (i.e.JVM is pl
The JVM performs four main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runti
JDK
JDK is an acronym for Java Development Kit.It physically
exists.It contains JRE + development tools.
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.
4) Stack:
Java Stack stores frames.It holds local variables and partial
results, and plays a part in method invocation and return.
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.
5) Program Counter Regiser:
PC (program counter) register. It contains the address of the Java
virtual machine instruction currently being executed.
6) Native Method Stack:
It contains all the native methods used in the application.
7) Execution Engine:
It contains:
1) A virtual processor
2) Interpreter:Read bytecode stream then execute the
instructions.
3) Just-In-Time(JIT) compiler:It is used to improve the
performance.JIT compiles parts of the byte code that have
similar functionality at the same time, and hence reduces the
amount of time needed for compilation.Here the term ?
compiler? refers to a translator from the instruction set of a Java
virtual machine (JVM) to the instruction set of a specific CPU.
Variable and Datatype in Java
1. Variable
2. Types of Variable
Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called
Static variable
Data Type
Default
Value
Default
size
boolean
false
1 bit
char
'\u0000'
2 byte
byte
1 byte
short
2 byte
int
4 byte
long
0L
8 byte
float
0.0f
4 byte
double
0.0d
8 byte
Precedence of Operators
Operators
Precedence
postfix
expr++ expr--
unary
multiplicative
* / %
additive
+ -
shift
<<>>>>>
relational
equality
== !=
bitwise AND
&
bitwise exclusive
OR
bitwise inclusive
OR
logical AND
&&
logical OR
||
ternary
? :
assignment
= += -= *= /= %= &= ^= |=
<<= >>= >>>=
Useful Programs:
There is given some useful programs such as factorial number,
prime number, fibonacci series etc.
It is better for the freshers to skip this topic and come to it after OOPs
concepts.
1) Program of factorial number.
class Operation{
System.out.println("it is Palindrome");
else
System.out.println("it is not palinedrome");
}
}
5) Program of swapping two numbers without using third variable.
class SwapTwoNumbers{
public static void main(String args[]){
int a=40,b=5;
a=a*b;
b=a/b;
a=a/b;
System.out.println("a= "+a);
System.out.println("b= "+b);
}
}
6) Program of factorial number by recursion
class FactRecursion{
static int fact(int n){
if(n==1)
return 1;
return n*=fact(n-1);
}
public static void main(String args[]){
int f=fact(5);
System.out.println(f);
}
}
Java OOPs Concepts
1. Object Oriented Programming
2. Advantage of OOPs over Procedure-oriented programming
language
3. Difference between Objcet-oriented and Objcet-based
programming language.
In this page, we will learn about basics of OOPs. Object Oriented
Programming is a paradigm that provides many concepts such
as inheritance, data binding,polymorphism etc.
Simula is considered as the first object-oriented programming
language. The programming paradigm where everything is
represented as an object, is known as truly object-oriented
programming language.
Smalltalk is considered as the first truly object-oriented
programming language.
OOPs (Object Oriented Programming System)
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.
In java, we use method overloading and method overriding to
achieve polymorphism.
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.
Advantage of OOPs over Procedure-oriented programming language
1)OOPs makes development and maintenance easier where as
in Procedure-oriented programming language it is not easy to
manage if code grows as project size grows.
2)OOPs provides data hiding whereas in Procedure-oriented
prgramming language a global data can be accessed from
anywhere.
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.
Do You Know ?
Method Overriding
Covariant Return Type
super keyword
Instance Initializer block
final keyword
Abstract class
Interface
Runtime Polymorphism
Static and Dynamic Binding
Downcasting with instanceof operator
Package
Access Modifiers
Encapsulation
Object Cloning
Java Naming convention
A naming convention is a rule to follow as you decide what to
name your identifiers (e.g. class, package, variable, method,
etc.), but it is not mandatory to follow that is why it is known as
convention not rule.
Advantage of java naming convention
By using standard Java naming conventions they make their code
easier to read for themselves and for other programmers.
Name
Convention
class
name
Interface
name
method
name
variable
name
package
name
constant
s name
6. Annonymous Object
In this page, we will learn about the objects and classes. In
object-oriented programming, we design a program using
objects and classes. Object is the physical entity whereas class
is the logical entity. A class works as a template from which we
create the objects.
Object
Class
A class is a group of objects that have common property. It is a
template or blueprint from which objects are created.
A class in java can contain:
data member
method
constructor
block
Syntax to declare a class:
1.
2.
3.
4.
class <class_name>{
data member;
method;
}
Simple Example of Object and Class
In this example, we have created a Student class that have two
data members id and name. We are creating the object of the
Student class by new keyword and printing the objects value.
1.
2.
3.
4.
5.
6.
class Student{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
public static void main(String args[]){
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.
Method
In java, a method is like function i.e. used to expose behaviour
of an object.
Advantage of Method
Code Reusability
Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.
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.
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
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
What are the different ways to create an object in Java?
There are many ways to create an object in java. They are:
By new keyword
By newInstance() method
By clone() method
By factory method etc.
We will learn, these ways to create the object later.
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 annonymou
s object
13.
}
14.
}
Output:Factorial is 120
Creating multiple objects by one type only
We can create multiple objects by one type only as we do in
case of primitives.
1.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
public static void main(String args[]){
13.
Rectangle r1=new Rectangle(),r2=new Rectangle();//crea
ting two objects
14.
15.
r1.insert(11,5);
16.
r2.insert(3,15);
17.
18.
r1.calculateArea();
19.
r2.calculateArea();
20.
}
21.
}
Output:55
45
Method Overloading in Java
1. Different ways to overload the method
1.
2.
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
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
5.
6.
7.
8.
obj.sum(20,20,20);
9.
10.
}
11.
}
Output:40
60
Example of Method Overloading with TypePromotion if matching
found
If there are matching type arguments in the method, type
promotion is not performed.
1.
2.
class Calculation{
void sum(int a,int b){System.out.println("int arg method i
nvoked");}
3.
void sum(long a,long b){System.out.println("long arg me
thod invoked");}
4.
5.
public static void main(String args[]){
6.
Calculation obj=new Calculation();
7.
obj.sum(20,20);//now int arg sum() method gets invoked
8.
}
9.
}
Output:int arg method invoked
class Calculation{
2.
Default Constructor
2.
Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value
4. Copying the values of one object into another
5. Does constructor perform other task instead initialization
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
There are two types of constructors:
1. default constructor (no-arg constructor)
2. parameterized constructor
1) Default Constructor
A constructor that have no parameter is known as default
constructor.
Syntax of default constructor:
1.
<class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the
Bike class. It will be invoked at the time of object creation.
1.
2.
3.
4.
5.
6.
7.
8.
class Bike{
Bike(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike b=new Bike();
}
}
Output: Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a
default constructor.
3.
String name;
4.
5.
void display(){System.out.println(id+" "+name);}
6.
7.
public static void main(String args[]){
8.
Student s1=new Student();
9.
Student s2=new Student();
10.
s1.display();
11.
s2.display();
12.
}
13.
}
1.
Output:0 null
2.
0 null
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.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to
the distinct objects.
Example of parameterized constructor
In this example, we have created the constructor of Student
class that have two parameters. We can have any number of
parameters in the constructor.
1.
2.
3.
4.
5.
class Student{
int id;
String name;
Student(int i,String n){
6.
id = i;
7.
name = n;
8.
}
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(222,"Aryan");
14.
s1.display();
15.
s2.display();
16.
}
17.
}
Output:111 Karan
222 Aryan
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.
Example of Constructor Overloading
1.
class Student{
2.
int id;
3.
String name;
4.
int age;
5.
Student(int i,String n){
6.
id = i;
7.
name = n;
8.
}
9.
Student(int i,String n,int a){
10.
id = i;
11.
name = n;
12.
age=a;
13.
}
14.
void display(){System.out.println(id+" "+name+"
"+age);}
15.
16.
public static void main(String args[]){
17.
Student s1 = new Student(111,"Karan");
18.
Student s2 = new Student(222,"Aryan",25);
19.
s1.display();
20.
s2.display();
21.
}
22.
}
Output:111 Karan 0
222 Aryan 25
What is the difference between constructor and method ?
There are many differences between constructors and methods.
They are given below.
Constructor
Method
Constructor is used to
initialize the state of an
object.
Method is used to
expose behaviour
of an object.
Constructor is invoked
implicitly.
Method is invoked
explicitly.
Method is not
provided by
compiler in any
case.
or may not be
same as class
name.
Copying the values of one object to another like copy constructor in C++
There are many ways to copy the values of one object into
another. They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
In this example, we are going to copy the values of one object
into another using constructor.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
Student(Student s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(s1);
s1.display();
s2.display();
20.
}
21.
}
Output:111 Karan
111 Karan
Copying the values of one object to another without constructor
We can copy the values of one object into another by assigning
the objects values to another object. In this case, there is no
need to create the constructor.
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).
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.
Advantage of static variable
It makes your program memory efficient (i.e it saves
memory).
Understanding problem without static variable
1.
2.
3.
4.
5.
class Student{
int rollno;
String name;
String college="ITS";
}
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.
static property is shared to all objects.
6.
static String college ="ITS";
7.
8.
Student(int r,String n){
9.
rollno = r;
10.
name = n;
11.
}
12.
void display (){System.out.println(rollno+" "+name+"
"+college);}
13.
14.
public static void main(String args[]){
15.
Student s1 = new Student (111,"Karan");
16.
Student s2 = new Student (222,"Aryan");
17.
18.
s1.display();
19.
s2.display();
20.
}
21.
}
Output:111 Karan ITS
222 Aryan ITS
class Counter{
int count=0;//will get memory when instance is created
Counter(){
count++;
System.out.println(count);
}
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
1
1
Program of counter by static variable
As we have mentioned above, static variable will get the
memory only once, if any object changes the value of the static
variable, it will retain its value.
1.
2.
class Counter{
static int count=0;//will get memory only once and retain it
s 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.
A static method belongs to the class rather than object of a
class.
A static method can be invoked without the need for
creating an instance of a class.
static method can access static data member and can
change the value of it.
Example of static method
1.
//Program of changing the common property of all objects(st
atic field).
2.
3.
class Student{
4.
int rollno;
5.
String name;
6.
static String college = "ITS";
7.
8.
static void change(){
9.
college = "BBDIT";
10.
}
11.
12.
Student(int r, String n){
13.
rollno = r;
14.
name = n;
15.
}
16.
17.
void display (){System.out.println(rollno+" "+name+"
"+college);}
18.
19.
public static void main(String args[]){
20.
Student.change();
21.
22.
Student s1 = new Student (111,"Karan");
23.
Student s2 = new Student (222,"Aryan");
24.
Student s3 = new Student (333,"Sonoo");
25.
26.
s1.display();
27.
s2.display();
28.
s3.display();
29.
}
30.
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Another example of static method that performs normal
calculation
1.
//Program to get cube of a given number by static method
2.
3.
class Calculate{
4.
static int cube(int x){
5.
return x*x*x;
6.
}
7.
8.
public static void main(String args[]){
9.
int result=Calculate.cube(5);
10.
System.out.println(result);
11.
}
12.
}
Output:125
Restrictions for static method
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or
call non-static method directly.
2. this and super cannot be used in static context.
1.
class A{
2.
3.
4.
5.
6.
7.
3)static block
Is used to initialize the static data member.
It is executed before main method at the time of
classloading.
Example of static block
1.
class A{
2.
3.
static{System.out.println("static block is invoked");}
4.
5.
public static void main(String args[]){
6.
System.out.println("Hello main");
7.
}
8.
}
Output:static block is invoked
Hello main
Que)Can we execute a program without main() method?
Ans)Yes, one of the way is static block but in previous version of
JDK not in JDK 1.7.
1.
2.
3.
4.
5.
6.
class A{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
Output:static block is invoked (if not JDK7)
this keyword
1. this keyword
2. Usage of this keyword
1.
2.
3.
4.
5.
6.
1) The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and
parameter, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by
the example given below:
1.
2.
3.
4.
5.
6.
class student{
int id;
String name;
student(int id,String name){
id = id;
7.
name = name;
8.
}
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(321,"Aryan");
14.
s1.display();
15.
s2.display();
16.
}
17.
}
Output:0 null
0 null
In the above example, parameter (formal arguments) and
instance variables are same that is why we are using this
keyword to distinguish between local variable and instance
variable.
Solution of the above problem by this keyword
1.
//example of this keyword
2.
class Student{
3.
int id;
4.
String name;
5.
6.
student(int id,String name){
7.
this.id = id;
8.
this.name = name;
9.
}
10.
void display(){System.out.println(id+" "+name);}
11.
public static void main(String args[]){
12.
Student s1 = new Student(111,"Karan");
13.
Student s2 = new Student(222,"Aryan");
14.
s1.display();
15.
s2.display();
16.
}
17.
}
Output:111 Karan
222 Aryan
class Student{
int id;
String name;
student(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student e1 = new Student(111,"karan");
Student e2 = new Student(222,"Aryan");
13.
e1.display();
14.
e2.display();
15.
}
16.
}
Output:111 Karan
222 Aryan
2) this() can be used to invoked current class constructor.
The this() constructor call can be used to invoke the current class
constructor (constructor chaining). This approach is better if you
have many constructors in the class and want to reuse that
constructor.
1.
2.
3.
4.
5.
6.
7.
8.
Student(int id,String name){
9.
this ();//it is used to invoked current class constructor.
10.
this.id = id;
11.
this.name = name;
12.
}
13.
void display(){System.out.println(id+" "+name);}
14.
15.
public static void main(String args[]){
16.
Student e1 = new Student(111,"karan");
17.
Student e2 = new Student(222,"Aryan");
18.
e1.display();
19.
e2.display();
20.
}
21.
}
Output:
default constructor is invoked
1.
2.
3.
4.
class Student{
int id;
String name;
Student (){System.out.println("default constructor is invo
ked");}
5.
6.
Student(int id,String name){
7.
id = id;
8.
name = name;
9.
this ();//must be the first statement
10.
}
11.
void display(){System.out.println(id+" "+name);}
12.
13.
public static void main(String args[]){
14.
Student e1 = new Student(111,"karan");
15.
Student e2 = new Student(222,"Aryan");
16.
e1.display();
17.
e2.display();
18.
}
19.
}
Output:Compile Time Error
3)The this keyword can be used to invoke current class method (implicitly).
You may invoke the method of the current class by using the
this keyword. If you don't use the this keyword, compiler
automatically adds this keyword while invoking the method.
Let's see the example
1.
2.
3.
4.
5.
6.
7.
8.
9.
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
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
4) this keyword can be passed as an argument in the method.
The this keyword can also be passed as an argument in the
method. It is mainly used in the event handling. Let's see the
example:
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.
class B{
A obj;
B(A obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A cl
ass
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
6) The this keyword can be used to return current class instance.
We can return the this keyword as an statement from the
method. In such case, return type of the method must be the
class type (non-primitive). Let's see the example:
Syntax of this that can be returned as a statement
1.
2.
3.
return_type method_name(){
return this;
}
12.
}
Output:Hello java
Proving this keyword
Let's prove that this keyword refers to the current class instance
variable. In this program, we are printing the reference variable
and this, output of both variables are same.
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
1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in java in case of
class?
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.
Inheritance represents the IS-A relationship.
Why use Inheritance?
For Method Overriding (So Runtime Polymorphism).
For Code Reusability.
Syntax of Inheritance
1.
2.
3.
4.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Public Static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
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.
2.
3.
4.
5.
6.
class Employee{
int id;
String name;
Address address;//Address is a class
...
}
In such case, Employee has an entity reference address, so
relationship is Employee HAS-A address.
Why use Aggregation?
For Code Reusability.
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. dele
gates 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
When use Aggregation?
Code reuse is also best achieved by aggregation when there
is no is-a relationship.
Inheritance should be used only if the relationship is-a is
maintained throughout the lifetime of the objects involved;
otherwise, aggregation is the best choice.
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();
25.
e2.display();
26.
27.
}
28.
}
Output:111 varun
gzb UP india
112 arun
gno UP india
download this example
Method Overriding in Java
1. Understanding problem without method overriding
2. Can we override the static method
3. method overloading vs method overriding
Having the same method in the subclass as declared in the parent
class is known as method overriding.
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.
Advantage of Method Overriding
Method Overriding is used to provide specific implementation
of a method that is already provided by its super class.
Method Overriding is used for Runtime Polymorphism
Rules for Method Overriding:
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
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.
Why we cannot override static method?
because static method is bound with class whereas instance
method is bound with object. Static belongs to class area and
instance belongs to heap area.
Method Overriding
1) Method
overloading is used
to increase the
readability of the
program.
2) method
overloading is
performed within a
class.
3) In case of
method
overloading
parameter must be
different.
In case of method
overriding parameter must
be same.
int speed=100;
void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike b=new Bike();
b.display();
}
}
Output:50
2) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class
constructor as given below:
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.
13.
}
14.
}
Output:Vehicle is created
Bike is created
super() is added in each class constructor automatically by compiler.
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike extends Vehicle{
int speed;
Bike(int speed){
this.speed=speed;
System.out.println(speed);
}
11.
public static void main(String args[]){
12.
Bike b=new Bike(10);
13.
}
14.
}
Output:Vehicle is created
10
3) super can be used to invoke parent class method.
The super keyword can also be used to invoke parent class
method. It should be used in case subclass contains the same
method as parent class as in the example given below:
1.
class Person{
2.
void message(){System.out.println("welcome");}
3.
}
4.
5.
class Student extends Person{
6.
void message(){System.out.println("welcome to java");}
7.
8.
void display(){
9.
message();//will invoke current class message() method
10.
super.message();//will invoke parent class message() meth
od
11.
}
12.
13.
public static void main(String args[]){
14.
Student s=new Student();
15.
s.display();
16.
}
17.
}
Output:welcome to java
welcome
In the above example Student and Person both classes have
message() method if we call message() method from Student
class, it will call the message() method of Student class not of
Person class because priority is given to local.
class Bike{
int speed=100;
}
Why use instance initializer block?
Suppose I have to perform some operations while assigning
value to instance data member e.g. a for loop to fill a complex
array or error handling etc.
class Bike{
int speed;
Bike(){System.out.println("speed is "+speed);}
{speed=100;}
public static void main(String args[]){
Bike b1=new Bike();
Bike b2=new Bike();
}
}
Output:speed is 100
speed is 100
There are three places in java where you can perform
operations:
1. method
2. constructor
3. block
class Bike{
int speed;
Bike(){System.out.println("constructor is invoked");}
{System.out.println("instance initializer block invoked");}
7.
8.
public static void main(String args[]){
9.
Bike b1=new Bike();
10.
Bike b2=new Bike();
11.
}
12.
}
Output:instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked
In the above example, it seems that instance initializer block is
firstly invoked but NO. Instance intializer block is invoked at the
time of object creation. The java compiler copies the instance
initializer block in the constructor after the first statement
super(). So firstly, constructor is invoked. Let's understand it by
class A{
A(){
System.out.println("parent class constructor invoked");
}
}
class B extends A{
8.
B(){
9.
super();
10.
System.out.println("child class constructor invoked");
11.
}
12.
13.
B(int a){
14.
super();
15.
System.out.println("child class constructor invoked "+a);
16.
}
17.
18.
{System.out.println("instance initializer block is invoked");}
19.
20.
public static void main(String args[]){
21.
B b1=new B();
22.
B b2=new B(10);
23.
}
24.
}
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
parent class constructor invoked
instance initializer block is invoked
child class constructor invoked 10
Final Keyword In Java
1. Final variable
2. Final method
3. Final class
4. Is final method inherited ?
5. Blank final variable
6. Static blank final variable
7. Final parameter
1) final variable
If you make any variable as final, you cannot change the value of
final variable(It will be constant).
Example of final variable
There is a final variable speedlimit, we are going to change the
value of this variable, but It can't be changed because final
variable once assigned a value can never be changed.
1.
2.
class Bike{
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.
Example of final method
1.
class Bike{
2.
final void run(){System.out.println("running");}
3.
}
4.
5.
class Honda extends Bike{
6.
void run(){System.out.println("running safely with 100km
ph");}
7.
8.
public static void main(String args[]){
9.
Honda honda= new Honda();
10.
honda.run();
11.
}
12.
}
Output:Compile Time Error
3) final class
If you make any class as final, you cannot extend it.
Example of final class
1.
final class Bike{}
2.
3.
class Honda extends Bike{
4.
5.
6.
public static void main(String args[]){
7.
Honda honda= new Honda();
8.
honda.run();
9.
}
10.
}
Output:Compile Time Error
Q) Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For
Example:
1.
2.
3.
4.
5.
6.
7.
8.
class Bike{
final void run(){System.out.println("running...");}
}
class Honda extends Bike{
public static void main(String args[]){
new Honda().run();
}
}
Output:running...
Q) What is blank or uninitialized final variable?
A final variable that is not initialized 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.
It can be initialized only in constructor.
3.
4.
5.
6.
String name;
final String PAN_CARD_NUMBER;
...
}
Que) Can we initialize blank final variable?
Yes, but only in constructor. For example:
1.
class Bike{
2.
final int speedlimit;//blank final variable
3.
4.
Bike(){
5.
speedlimit=70;
6.
System.out.println(speedlimit);
7.
}
8.
9.
public static void main(String args[]){
10.
new Bike();
11.
}
12.
}
Output:70
static blank final variable
A static final variable that is not initialized at the time of
declaration is known as static blank final variable. It can be
initialized only in static block.
Example of static blank final variable
1.
class A{
2.
static final int data;//static blank final variable
3.
static{ data=50;}
4.
public static void main(String args[]){
5.
System.out.println(A.data);
6.
}
7.
}
1.
2.
1.
class A{}
class B extends A{}
A a=new B();//upcasting
Example of Runtime Polymorphism
In this example, we are creating two classes Bike and Splendar.
Splendar class extends Bike class and overrides its run() method.
We are calling the run method by the reference variable of Parent
class. Since it refers to the subclass object and subclass method
overrides the Parent class method, subclass method is invoked at
runtime.
Since method invocation is determined by the JVM not compiler, it
is known as runtime polymorphism.
1.
2.
3.
4.
5.
class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km
");}
6.
7.
8.
Bike b = new Splender();//upcasting
9.
b.run();
10.
}
11.
}
Output: running safely with 60km.
Runtime Polymorphism with data member
Method is overriden not the datamembers, so runtime
polymorphism can't be achieved by data members.
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.
Rule: Runtime polymorphism can't be achieved by data members.
1.
class Bike{
2.
int speedlimit=90;
3.
}
4.
class Honda extends Bike{
5.
int speedlimit=150;
6.
7.
public static void main(String args[]){
8.
Bike obj=new Honda();
9.
System.out.println(obj.speedlimit);//90
10.
}
Output: 90
Runtime Polymorphism with Multilevel Inheritance
Let's see the simple example of Runtime Polymorphism with
multilevel inheritance.
1.
2.
class Animal{
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.
}
22.
}
Output: eating
eating fruits
drinking Milk
Try for Output
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
}
class BabyDog extends Dog{
public static void main(String args[]){
Animal a=new BabyDog();
a.eat();
13.
}}
Output: Dog is eating
Since, BabyDog is not overriding the eat() method, so eat()
method of Dog class is invoked.
Static Binding and Dynamic Binding
int data=30;
Here data variable is a type of int.
2) References have a type
1.
2.
3.
4.
5.
class Dog{
public static void main(String args[]){
Dog d1;//Here d1 is a type of Dog
}
}
class Animal{}
class Dog extends Animal{
public static void main(String args[]){
Dog d1=new Dog();
}
}
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.
Example of static binding
1.
class Dog{
2.
private void eat(){System.out.println("dog is eating...");}
3.
4.
public static void main(String args[]){
5.
Dog d1=new Dog();
6.
d1.eat();
7.
}
8.
}
Dynamic binding
When type of the object is determined at run-time, it is known as
dynamic binding.
class Simple{
public static void main(String args[]){
Simple s=new Simple();
System.out.println(s instanceof Simple);//true
}
}
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.
Another example of instanceof operator
1.
2.
3.
4.
5.
6.
7.
8.
class Animal{}
class Dog extends Animal{//Dog inherits Animal
public static void main(String args[]){
Dog d=new Dog();
System.out.println(d instanceof Animal);//true
}
}
Output:true
instanceof operator with a variable that have null value
If we apply instanceof operator with a variable that have null
value, it ruturns false. Let's see the example given below where
we apply instanceof operator with the variable that have null
value.
1.
2.
3.
class Dog{
public static void main(String args[]){
Dog d=null;
4.
5.
6.
1.
1.
2.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
class Animal { }
class Dog extends Animal {
static void method(Animal a) {
if(a instanceof Dog){
Dog d=(Dog)a;//downcasting
System.out.println("ok downcasting performed");
}
}
public static void main (String [] args) {
Animal a=new Dog();
Dog.method(a);
14.
}
15.
16.
}
Output:ok downcasting performed
Downcasting without the use of instanceof operator
Downcasting can also be performed without the use of instanceof
operator as displayed in the following example:
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.
2.
3.
1.
2.
3.
interface Printable{}
class A implements Printable{
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.
}
19.
20.
}
21.
}//end of Call class
22.
23.
class Test{
24.
public static void main(String args[]){
25.
Printable p=new B();
26.
Call c=new Call();
27.
c.invoke(p);
28.
}
29.
}
Output: b method
Abstract class in Java
A class that is declared with abstract keyword, is known as
abstract class. Before learning abstract class, let's understand the
abstraction first.
Abstraction
Abstraction is a process of hiding the implementation details
and showing only functionality to the user.
Another way, it shows only important things to the user and hides
the internal details for example sending sms, you just type the
text and send the message. You don't know the internal
processing about the message delivery.
Abstraction lets you focus on what the object does instead of how
it does it.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
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.
Syntax to declare the abstract class
1.
1.
1.
2.
abstract void run();
3.
}
4.
5.
class Honda extends Bike{
6.
void run(){System.out.println("running safely..");}
7.
8.
public static void main(String args[]){
9.
Bike obj = new Honda();
10.
obj.run();
11.
}
12.
}
Output:running safely..
Understanding the real scenario of abstract class
In this example, Shape is the abstract class, its implementation is
provided by the Rectangle and Circle classes. Mostly, we don't
know about the implementation class (i.e. hidden to the end
user) and object of the implementation class is provided by
the factory method.
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.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
class Test{
14.
public static void main(String args[]){
15.
Shape s=new Circle();
16.
//In real scenario, Object is provided through factory metho
d
17.
s.draw();
18.
}
19.
}
Output:drawing circle
Abstract class having constructor, data member, methods etc.
Note: An abstract class can have data member, abstract method, method
body, constructor and even main() method.
1.
//example of abstract class that have method body
2.
abstract class Bike{
3.
abstract void run();
4.
void changeGear(){System.out.println("gear changed");}
5.
}
6.
7.
class Honda extends Bike{
8.
void run(){System.out.println("running safely..");}
9.
10.
public static void main(String args[]){
11.
Bike obj = new Honda();
12.
obj.run();
13.
obj.changeGear();
14.
}
15.
}
Output:running safely..
gear changed
1.
//example of abstract class having constructor, field and met
hod
2.
abstract class Bike
3.
{
4.
int limit=30;
5.
6.
Bike(){System.out.println("constructor is invoked");}
void getDetails(){System.out.println("it has two wheels");}
7.
abstract void run();
8.
}
9.
10.
class Honda extends Bike{
11.
void run(){System.out.println("running safely..");}
12.
13.
public static void main(String args[]){
14.
Bike obj = new Honda();
15.
obj.run();
16.
obj.getDetails();
17.
System.out.println(obj.limit);
18.
}
19.
}
Output:constructor is invoked
running safely..
it has two wheels
30
Rule: If there is any abstract method in a class, that class must be
abstract.
1.
2.
3.
class Bike{
abstract void run();
}
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.
Another real scenario of abstract class
The abstract class can also be used to provide some
implementation of the interface. In such case, the end user may
not be forced to override all the methods of the interface.
Note: If you are beginner to java, learn interface first and skip this
example.
1.
interface A{
2.
void a();
3.
void b();
4.
void c();
5.
void d();
6.
}
7.
8.
abstract class B implements A{
9.
public void c(){System.out.println("I am C");}
10.
}
11.
12.
class M extends B{
13.
public void a(){System.out.println("I am a");}
14.
public void b(){System.out.println("I am b");}
15.
public void d(){System.out.println("I am d");}
16.
}
17.
18.
class Test{
19.
public static void main(String args[]){
20.
A a=new M();
21.
a.a();
22.
a.b();
23.
a.c();
24.
a.d();
25.
}}
Output:I am a
I am b
I am c
I am d
Interface in Java
1. Interface
2. Example of Interface
1.
2.
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
Multiple inheritance in Java by interface
1.
interface Printable{
2.
void print();
3.
}
4.
5.
interface Showable{
6.
void show();
7.
}
8.
9.
class A implements Printable,Showable{
10.
11.
public void print(){System.out.println("Hello");}
12.
public void show(){System.out.println("Welcome");}
13.
14.
public static void main(String args[]){
15.
A obj = new A();
16.
obj.print();
17.
obj.show();
18.
}
19.
}
Output:Hello
Welcome
Q) Multiple inheritance is not supported in case of class but it is
supported in case of interface, why?
1.
2.
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.
2.
3.
4.
5.
6.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
7.
}
8.
9.
class A implements Showable{
10.
11.
public void print(){System.out.println("Hello");}
12.
public void show(){System.out.println("Welcome");}
13.
14.
public static void main(String args[]){
15.
A obj = new A();
16.
obj.print();
17.
obj.show();
18.
}
19.
}
Output:Hello
Welcome
Que) What is marker or tagged interface ?
1.
2.
3.
4.
1.
2.
3.
interface printable{
void print();
interface MessagePrintable{
4.
5.
6.
void msg();
}
}
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.
Points to remember for nested interfaces
There are given some points that should be remembered by the
java programmer.
Nested interface must be public if it is declared inside the
interface but it can have any access modifier if declared
within the class.
Nested interfaces are declared static implicitely.
Syntax of nested interface which is declared within the interface
1.
2.
3.
4.
5.
6.
7.
interface interface_name{
...
interface nested_interface_name{
...
}
}
Syntax of nested interface which is declared within the class
1.
2.
3.
4.
class class_name{
...
interface nested_interface_name{
...
5.
6.
7.
}
}
interface Showable{
void show();
interface Message{
void msg();
}
}
Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface
as displayed below:.
1.
2.
3.
4.
1.
2.
3.
4.
5.
6.
7.
8.
class A{
interface Message{
void msg();
}
}
class Test implements A.Message{
public void msg(){System.out.println("Hello nested interfa
ce");}
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
Can we define a class inside the interface ?
Yes, Ofcourse! If we define a class inside the interface, java
compiler creates a static nested class. Let's see how can we
define a class within the interface:
1.
interface M{
2.
3.
class A{}
}
Multithreading in Java
1. Multithreading
2. Multitasking
3. Process-based multitasking
4. Thread-based multitasking
5. What is Thread
Multithreading is a process of executing multiple threads
simultaneously.
Thread is basically a lightweight subprocess, a smallest unit of
processing. Multiprocessing and multithreading, both are used
to achieve multitasking. But we use multithreading than
mulitprocessing because threads share a common memory
area. They don't allocate separate memory area so save
memory, and context-switching between the threads takes less
time than processes.
Multithreading is mostly used in games, animation etc.
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.
Do You Know ?
Multithreading
Life Cycle of a Thread
Two ways to create a Thread
How to perform multiple tasks by multiple threads
Thread Schedular
Sleeping a thread
Can we start a thread twice ?
What happens if we call the run() method instead of start()
method ?
Joining a thread
Naming a thread
Priority of a thread
Daemon Thread
ShutdownHook
Garbage collection
Synchronization with synchronized method
Synchronized block
Static synchronization
Deadlock
Inter-thread communication
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.
4)Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently
not eligible to run.
5)Terminated
A thread is in terminated or dead state when its run() method
exits.
How to create thread:
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
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.
Commonly used Constructors of Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
thread(depricated).
16. public void resume(): is used to resume the
suspended thread(depricated).
17. public void stop(): is used to stop the
thread(depricated).
18. public boolean isDaemon(): tests if the thread is a
daemon thread.
19. public void setDaemon(boolean b): marks the
thread as daemon or user thread.
20.
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().
1. public void run(): is used to perform action for a thread.
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).
9.
t1.start();
10.
}
11.
}
Output:thread is running...
If you are not extending the Thread class,your class object
would not be treated as a thread object.So you need to
explicitely create Thread class object.We are passing the object
of your class that implements Runnable so that your class run()
method may execute.
The Thread Schedular:
The thread scheduler is the part of the JVM that decides
which thread should run.
There is no guarantee that which runnable thread will be
chosen to run by the thread schedular.
Only one thread at a time can run in a single process.
The thread schedular mainly uses preemptive or time slicing
scheduling to schedule the threads.
What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes
until it enters the waiting or dead states or a higher priority
task comes into existence. Under time slicing, a task executes
for a predefined slice of time and then reenters the pool of
ready tasks. The scheduler then determines which task should
execute next, based on priority and other factors.
Sleeping a thread (sleep() method):
The sleep() method of Thread class is used to sleep a thread for
the specified time.Syntax:
1.
2.
3.
4.
5.
6.
7.
8.
<strong>Output:</strong>1
1
2
2
3
3
4
4
9.
10.
5
5
As you know well that at a time only one thread is executed. If
you sleep a thread for the specified time,the thread shedular
picks up another thread and so on.
<strong>Output:</strong>running
Exception in thread "main" java.lang.IllegalThreadState
Exception
What if we call run() method directly instead start() method?
Each thread starts in a separate call stack.
Invoking the run() method from main thread, the run()
method goes onto the current call stack rather than at the
beginning of a new call stack.
1.
2.
3.
4.
5.
6.
7.
8.
9.
1.
<strong>Output:</strong>running...
1.
2.
3.
4.
5.
6.
5
1
2
3
4
5
As you can see in the above program that there is no contextswitching because here t1 and t2 will be treated as normal
object not thread object.
The join() method:
The join() method waits for a thread to die. In other words, it
causes the currently running threads to stop executing until the
thread it joins with completes its task.
Syntax:
public void join()throws InterruptedException
public void join(long miliseconds)throws InterruptedException
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
try{
18.
t1.join();
19.
}catch(Exception e){System.out.println(e);}
20.
21.
t2.start();
22.
t3.start();
23.
}
24.
}
Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
As you can see in the above example,when t1 completes its
task then t2 and t3 starts executing.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
}
12.
public static void main(String args[]){
13.
Multi t1=new Multi();
14.
Multi t2=new Multi();
15.
Multi t3=new Multi();
16.
t1.start();
17.
try{
18.
t1.join(1500);
19.
}catch(Exception e){System.out.println(e);}
20.
21.
t2.start();
22.
t3.start();
23.
}
24.
}
Output:1
2
3
1
4
1
2
5
2
3
3
4
4
5
5
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()
1.
//<b><i>Example of currentThread() method</i></b>
2.
3.
class Multi6 extends Thread{
4.
public void run(){
5.
System.out.println(Thread.currentThread().getName());
6.
}
7.
}
8.
public static void main(String args[]){
9.
Multi6 t1=new Multi6();
10.
Multi6 t2=new Multi6();
11.
12.
t1.start();
13.
t2.start();
14.
}
15.
}
Output:Thread-0
Thread-1
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.
Example of naming a thread:
1.
2.
3.
4.
5.
public static void main(String args[]){
6.
Multi6 t1=new Multi6();
7.
Multi6 t2=new Multi6();
8.
System.out.println("Name of t1:"+t1.getName());
9.
System.out.println("Name of t2:"+t2.getName());
10.
11.
t1.start();
12.
t2.start();
13.
14.
t1.setName("Sonoo Jaiswal");
15.
System.out.println("After changing name of t1:"+t1.getNa
me());
16.
}
17.
}
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...
2.
public void run(){
3.
System.out.println(Thread.currentThread().getName());
4.
}
5.
}
6.
public static void main(String args[]){
7.
Multi6 t1=new Multi6();
8.
Multi6 t2=new Multi6();
9.
10.
t1.start();
11.
t2.start();
12.
}
13.
}
Output:Thread-0
Thread-1
Priority of a Thread (Thread Priority):
Each thread have a priority. Priorities are represented by a
number between 1 and 10. In most cases, thread schedular
schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it
depends on JVM specifification that which sheduling it chooses.
3 constants defiend in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of
MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Example of priority of a Thread:
1.
2.
3.
12.
t1.start();
13.
t2.start();
14.
}
15.
}
Output:Name: thread-0
Daemon: true
Name: thread-1
Daemon: false
Note: If you want to make a user thread as Daemon, it must not be started
otherwise it will throw IllegalThreadStateException.
1.
2.
3.
16.
try { Thread.sleep(2000); } catch (InterruptedExcep
tion e) { e.printStackTrace(); }
17.
}
18.
}
19.
20.
public class SimpleThreadPool {
21.
public static void main(String[] args) {
22.
ExecutorService executor = Executors.newFixedThread
Pool(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.
}
download this example
Output:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-5
pool-1-thread-4
pool-1-thread-2
pool-1-thread-2
pool-1-thread-1
pool-1-thread-1
pool-1-thread-3
pool-1-thread-3
pool-1-thread-4
pool-1-thread-4
(Start)
(Start)
(Start)
(Start)
(Start)
(End)
(Start)
(End)
(Start)
(End)
(Start)
(End)
(Start)
message
message
message
message
message
=
=
=
=
=
0
1
2
4
3
message = 5
message = 6
message = 7
message = 8
14.
15.
16.
17.
18.
19.
20.
21.
pool-1-thread-5 (End)
pool-1-thread-5 (Start) message = 9
pool-1-thread-2 (End)
pool-1-thread-1 (End)
pool-1-thread-4 (End)
pool-1-thread-3 (End)
pool-1-thread-5 (End)
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.
When does the JVM shut down?
The JVM shuts down when:
user presses ctrl+c on the command prompt
System.exit(int) method is invoked
user logoff
user shutdown etc.
4.
}
5.
}
6.
7.
public class Shutdown {
8.
public static void main(String[] args)throws Exception {
9.
10.
Runtime r=Runtime.getRuntime();
11.
r.addShutdownHook(new MyThread());
12.
13.
System.out.println("Now main sleeping... press ctrl+c to exit
");
14.
try{Thread.sleep(3000);}catch (Exception e) {}
15.
}
16.
}
Output:Now main sleeping... press ctrl+c to exit
shut down hook task completed..
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
t1.start();
13.
t2.start();
14.
t3.start();
15.
}
16.
}
Output:task one
task one
task one
1.
//<b><i>Program of performing single task by multiple thre
ads</i></b>
2.
3.
class Multi3 implements Runnable{
4.
public void run(){
5.
System.out.println("task one");
6.
}
7.
8.
public static void main(String args[]){
9.
Thread t1 =new Thread(new Multi3());//passing annonymo
us object of Multi3 class
10.
Thread t2 =new Thread(new Multi3());
11.
12.
t1.start();
13.
t2.start();
14.
15.
}
16.
}
Output:task one
task one
Note: Each thread run in a separate callstack.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
}
14.
15.
class Test{
16.
public static void main(String args[]){
17.
Simple1 t1=new Simple1();
18.
Simple2 t2=new Simple2();
19.
20.
t1.start();
21.
t2.start();
22.
}
23.
}
Output:task one
task two
Same example as above by annonymous class that extends Thread class:
1.
//<b><i>Program of performing two tasks by two threads</
i></b>
2.
3.
class Test{
4.
public static void main(String args[]){
5.
Thread t1=new Thread(){
6.
public void run(){
7.
System.out.println("task one");
8.
}
9.
};
10.
Thread t2=new Thread(){
11.
public void run(){
12.
System.out.println("task two");
13.
}
14.
};
15.
16.
17.
t1.start();
18.
t2.start();
19.
}
20.
}
Output:task one
task two
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.
1.
class Simple{
public void finalize(){System.out.println("object is garbage
collected");}
4.
5.
public static void main(String args[]){
6.
Simple s1=new Simple();
7.
Simple s2=new Simple();
8.
s1=null;
9.
s2=null;
10.
System.gc();
11.
}
12.
}
Output:object is garbage collected
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only 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.
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
Understanding the concept of Lock
Synchronization is built around an internal entity known as the
lock or monitor.Every object has an lock associated with it. By
convention, a thread that needs consistent access to an object's
fields has to acquire the object's lock before accessing them,
and then release the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains
several lock implementations.
Understanding the problem without Synchronization
In this example, there is no synchronization, so output is
inconsistent. Let's see the example:
1.
2.
3.
4.
5.
6.
7.
8.
Class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}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.
34.
class Use{
35.
public static void main(String args[]){
36.
Table obj = new Table();//only one object
37.
MyThread1 t1=new MyThread1(obj);
38.
MyThread2 t2=new MyThread2(obj);
39.
t1.start();
40.
t2.start();
41.
}
42.
}
Output: 5
100
10
200
15
300
20
400
25
500
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
18.
MyThread1(Table t){
19.
this.t=t;
20.
}
21.
public void run(){
22.
t.printTable(5);
23.
}
24.
25.
}
26.
class MyThread2 extends Thread{
27.
Table t;
28.
MyThread2(Table t){
29.
this.t=t;
30.
}
31.
public void run(){
32.
t.printTable(100);
33.
}
34.
}
35.
36.
class Use{
37.
public static void main(String args[]){
38.
Table obj = new Table();//only one object
39.
MyThread1 t1=new MyThread1(obj);
40.
MyThread2 t2=new MyThread2(obj);
41.
t1.start();
42.
t2.start();
43.
}
44.
}
Output: 5
10
15
20
25
100
200
300
400
500
2.
3.
4.
5.
Class Table{
synchronized void printTable(int n){//synchronized meth
od
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class Use{
public static void main(String args[]){
final Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(){
public void run(){
obj.printTable(5);
}
};
MyThread1 t2=new MyThread1(){
public void run(){
obj.printTable(100);
}
};
t1.start();
32.
t2.start();
33.
}
34.
}
Output: 5
10
15
20
25
100
200
300
400
500
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.
Points to remember for Synchronized block
Synchronized block is used to lock an object for any shared
resource.
Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
1.
2.
3.
36.
37.
class Use{
38.
public static void main(String args[]){
39.
Table obj = new Table();//only one object
40.
MyThread1 t1=new MyThread1(obj);
41.
MyThread2 t2=new MyThread2(obj);
42.
t1.start();
43.
t2.start();
44.
}
45.
}
Output:5
10
15
20
25
100
200
300
400
500
15.
}
16.
17.
class Use{
18.
public static void main(String args[]){
19.
final Table obj = new Table();//only one object
20.
21.
Thread t1=new Thread(){
22.
public void run(){
23.
obj.printTable(5);
24.
}
25.
};
26.
Thread t2=new Thread(){
27.
public void run(){
28.
obj.printTable(100);
29.
}
30.
};
31.
32.
t1.start();
33.
t2.start();
34.
}
35.
}
Output:5
10
15
20
25
100
200
300
400
500
Static synchronization
If you make any static method as synchronized, the lock will be
on the class not on object.
class Table{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
}catch(Exception e){}
}
}
}
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
}
}
class MyThread2 extends Thread{
public void run(){
Table.printTable(10);
}
}
class MyThread3 extends Thread{
public void run(){
Table.printTable(100);
}
}
46.
t1.start();
47.
t2.start();
48.
t3.start();
49.
t4.start();
50.
}
51.
}
Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
class Table{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
public class Test {
public static void main(String[] args) {
Thread t1=new Thread(){
public void run(){
Table.printTable(1);
}
};
Thread t2=new Thread(){
public void run(){
Table.printTable(10);
}
};
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.
}
45.
}
Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
// Synchronized block
Deadlock:
Deadlock can occur in a situation when a thread is waiting for
an object lock, that is acquired by another thread and second
25.
26.
try { Thread.sleep(100);} catch (Exception e) {}
27.
28.
synchronized (resource1) {
29.
System.out.println("Thread 2: locked resource 1");
30.
}
31.
}
32.
}
33.
};
34.
35.
36.
t1.start();
37.
t2.start();
38.
}
39.
}
40.
Output: Thread 1: locked resource 1
Thread 2: locked resource 2
Inter-thread communication in Java
Inter-thread communication or Co-operation is all about
allowing synchronized threads to communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in
which a thread is paused running in its critical section and
another thread is allowed to enter (or lock) in the same critical
section to be executed.It is implemented by following methods
of Object class:
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
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:
public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()
Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?
It is because they are related to lock and object has a lock.
sleep()
wait() method
releases the lock
is the method of
Object class
is the non-static
method
is the non-static
method
should be notified by
notify() or notifyAll()
methods
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
11.
this.amount-=amount;
12.
System.out.println("withdraw completed...");
13.
}
14.
15.
synchronized void deposit(int amount){
16.
System.out.println("going to deposit...");
17.
this.amount+=amount;
18.
System.out.println("deposit completed... ");
19.
notify();
20.
}
21.
}
22.
23.
class Test{
24.
public static void main(String args[]){
25.
final Customer c=new Customer();
26.
new Thread(){
27.
public void run(){c.withdraw(15000);}
28.
}.start();
29.
new Thread(){
30.
public void run(){c.deposit(10000);}
31.
}.start();
32.
33.
}}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
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.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
}
11.
12.
public static void main(String args[]){
13.
A t1=new A();
14.
t1.start();
15.
try{
16.
t1.interrupt();
17.
}catch(Exception e){System.out.println("Exception handled
"+e);}
18.
19.
}
20.
}
download this example
1.
<strong>Output:</strong>Exception in thread-0
2.
java.lang.RuntimeException: Thread interrupted...
3.
java.lang.InterruptedException: sleep interrupted
4.
at A.run(A.java:7)
Example of interrupting a thread that doesn't stop working
In this example, after interrupting the thread, we handle the
exception, so it will break out the sleeping but will not stop
working.
1.
class A extends Thread{
2.
public void run(){
3.
try{
4.
Thread.sleep(1000);
5.
System.out.println("task");
6.
}catch(InterruptedException e){
7.
System.out.println("Exception handled "+e);
8.
}
9.
System.out.println("thread is running...");
10.
}
11.
12.
public static void main(String args[]){
13.
A t1=new A();
14.
t1.start();
15.
16.
t1.interrupt();
17.
18.
}
19.
}
download this example
1.
<strong>Output:</strong>Exception handled
2.
java.lang.InterruptedException: sleep interrupted
3.
thread is running...
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
1.
2.
3.
4.
5.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
if(Thread.interrupted()){
System.out.println("code for interrupted thread");
}
else{
System.out.println("code for normal thread");
}
1.
2.
3.
4.
5.
class Reentrant {
public synchronized void m() {
n();
System.out.println("this is m() method");
}
public synchronized void n() {
System.out.println("this is n() method");
}
}
In this class, m and n are the synchronized methods. The m()
method internally calls the n() method.
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
Input and Output in Java
Do You Know ?
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.
Commonly used methods of OutputStream class
Method
Description
1) public void
write(int)throws
IOException:
is used to write a
byte to the current
output stream.
2) public void
write(byte[])throws
is used to write an
array of byte to
IOException:
3) public void
flush()throws
IOException:
4) public void
close()throws
IOException:
InputStream class
InputStream class ia an abstract class.It is the superclass of all
classes representing an input stream of bytes.
Commonly used methods of InputStream class
Method
1) public abstract int
read()throws
IOException:
Description
reads the next byte of
data from the input
stream.It returns -1
returns an estimate of
the number of bytes
that can be read from
the current input
stream.
3) public void
close()throws
IOException:
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 characteroriented data.
Example of FileOutputStream class:
1.
//<b><i>Simple program of writing data into the file</i></
b>
2.
3.
import java.io.*;
class Test{
public static void main(String args[]){
try{
FileOutputstream fout=new FileOutputStream("abc.txt");
String s="Sachin Tendulkar is my favourite player";
byte b[]=s.getBytes();
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){system.out.println(e);}
}
}
Output:success...
FileInputStream class:
A FileInputStream obtains input bytes from a file.It is used for
reading streams of raw bytes such as image data. For reading
streams of characters, consider using FileReader.
It should be used to read byte-oriented data.For example, to
read image etc.
Example of FileInputStream class:
1.
//<b><i>Simple program of reading data from the file</i></b
>
2.
import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("abc.txt");
int i;
while((i=fr.read())!=-1)
System.out.println((char)i);
fin.close();
}catch(Exception e){system.out.println(e);}
}
}
1.
Example of Reading the data of current java file and writing it into
another file
We can read the data of any file using the FileInputStream class
whether it is java file, image file, video file etc. In this example,
we are reading the data of C.java file and writing it into another
file M.java.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
import java.io.*;
class C{
public static void main(String args[])throws Exception{
FileInputStream fin=new FileInputStream("C.java");
FileOutputStream fout=new FileOutputStream("M.java");
int i=0;
while((i=fin.read())!=-1){
fout.write((byte)i);
}
fin.close();
}
16.
}
download this example
ByteArrayOutputStream class:
In this stream, the data is written into a byte array. The buffer
automatically grows as data is written to it.
Closing a ByteArrayOutputStream has no effect.
Commonly used Constructors of ByteArrayOutputStream class:
1) ByteArrayOutputStream():creates a new byte array
output stream with the initial capacity of 32 bytes, though its
size increases if necessary.
2) ByteArrayOutputStream(int size):creates a new byte
array output stream, with a buffer capacity of the specified size,
in bytes.
Commonly used Methods of ByteArrayOutputStream class:
1) public synchronized void writeTo(OutputStream out)
throws IOException: writes the complete contents of this
byte array output stream to the specified output stream.
10.
11.
ByteArrayOutputStream bout=new ByteArrayOutputStrea
m();
12.
bout.write(239);
13.
14.
bout.writeTo(fout1);
15.
bout.writeTo(fout2);
16.
17.
bout.flush();
18.
19.
bout.close();//has no effect
20.
System.out.println("success...");
21.
}
22.
}
Output:success...
SequenceInputStream class:
SequenceInputStream class is used to read data from multipule
streams.
Constructors of SequenceInputStream class:
1) SequenceInputStream(InputStream s1, InputStream
2.
3.
import java.io.*;
4.
class Simple{
5.
public static void main(String args[])throws Exception{
6.
7.
FileinputStream fin1=new FileinputStream("f1.txt");
8.
FileinputStream fin2=new FileinputStream("f2.txt");
9.
10.
SequenceinputStream sis=new SequenceinputStream(fin1
,fin2);
11.
int i;
12.
while((i=sis.read())!=-1)
13.
{
14.
System.out.println((char)i);
15.
}
16.
}
17.
}
Example of SequenceInputStream class that reads the data from
two files and write it into another
In this example, we are writing the data of two files f1.txt and
f2.txt into another file named f3.txt.
1.
//reading data of 2 files and writing it into one file
2.
3.
import java.io.*;
4.
class Simple{
5.
public static void main(String args[])throws Exception{
6.
7.
FileinputStream fin1=new FileinputStream("f1.txt");
8.
FileinputStream fin2=new FileinputStream("f2.txt");
9.
10.
FileOutputStream fout=new FileOutputStream("f3.txt");
11.
12.
SequenceinputStream sis=new SequenceinputStream(fin1
,fin2);
13.
int i;
14.
while((i.sisread())!=-1)
15.
{
16.
fout.write(i);
17.
}
18.
sis.close();
19.
fout.close();
20.
fin.close();
21.
fin.close();
22.
23.
}
24.
}
Example of SequenceInputStream class that reads the data from
multiple files using enumeration
If we need to read the data from more than two files, we need
to have these information in the Enumeration object.
Enumeration object can be get by calling elements method of
the Vector class. Let's see the simple example where we are
reading the data from the 4 files.
1.
2.
3.
import java.io.*;
import java.util.*;
4.
5.
class B{
public static void main(String args[])throws IOException{
6.
7.
//creating the FileInputStream objects for all the files
8.
FileInputStream fin=new FileInputStream("A.java");
9.
FileInputStream fin2=new FileInputStream("abc2.txt");
10.
FileInputStream fin3=new FileInputStream("abc.txt");
11.
FileInputStream fin4=new FileInputStream("B.java");
12.
13.
//creating Vector object to all the stream
14.
Vector v=new Vector();
15.
v.add(fin);
16.
v.add(fin2);
17.
v.add(fin3);
18.
v.add(fin4);
19.
20.
//creating enumeration object by calling the elements metho
d
21.
Enumeration e=v.elements();
22.
23.
//passing the enumeration object in the constructor
24.
SequenceInputStream bin=new SequenceInputStream(e);
25.
int i=0;
26.
27.
while((i=bin.read())!=-1){
28.
System.out.print((char)i);
29.
}
30.
31.
bin.close();
32.
fin.close();
33.
fin2.close();
34.
}
35.
}
download this example of SequenceInputStream
BufferedOutputStream class:
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("f1.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1)
System.out.println((char)i);
fin.close();
}catch(Exception e){system.out.println(e);}
}
}
<strong>Output:</strong>Sachin is my favourite player
1.
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.
Example of FileWriter class:
In this example, we are writing the data in the file abc.txt.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
import java.io.*;
class Simple{
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("abc.txt");
fw.write("my name is sachin");
fw.flush();
fw.close();
}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.
Example of FileReader class:
In this example, we are reading the data from the file abc.txt
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.
Example of CharArrayWriter class:
In this example, we are writing a common data to 4 files a.txt,
b.txt, c.txt and d.txt.
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.
}
Reading data from keyboard:
There are many ways to read data from the keyboard. For
example:
InputStreamReader
Console
Scanner
DataInputStream etc.
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.
Example of reading data from keyboard by
InputStreamReader and BufferdReader class:
In this example, we are connecting the BufferedReader stream
with the InputStreamReader stream for reading the line by line
data from the keyboard.
//Program of reading data
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter ur name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Output:Enter ur name
Amit
Welcome Amit
}
Output:Enter data: Amit
data is: Amit
Enter data: 10
data is: 10
Enter data: stop
data is: stop
Console class (I/O)
The Console class can be used to get input from the keyboard.
primitive values.
Commonly used methods of Scanner class:
There is a list of commonly used Scanner class methods:
public String next(): it returns the next token from the
scanner.
public String nextLine(): it moves the scanner position to
the next line and returns the value as a string.
public byte nextByte(): it scans the next token as a byte.
public short nextShort(): it scans the next token as a
short value.
public int nextInt(): it scans the next token as an int
value.
public long nextLong(): it scans the next token as a long
value.
public float nextFloat(): it scans the next token as a float
value.
public double nextDouble(): it scans the next token as a
double value.
Example of java.util.Scanner class:
Let's see the simple example of the Scanner class which reads
the int, string and double value as an input:
1.
2.
3.
4.
5.
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
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+" fe
e:"+fee);
15.
16.
}
17.
}
download this scanner example
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.
Commonly used methods of PrintStream class:
There are many methods in PrintStream class. Let's see
commonly used methods of PrintStream class:
public void print(boolean b): it prints the specified
boolean value.
public void print(char c): it prints the specified char
value.
public void print(char[] c): it prints the specified
character array values.
public void print(int i): it prints the specified int value.
public void print(long l): it prints the specified long value.
public void print(float f): it prints the specified float
value.
public void print(double d): it prints the specified double
value.
public void print(String s): it prints the specified string
value.
public void print(Object obj): it prints the specified object
value.
public void println(boolean b): it prints the specified
boolean value and terminates the line.
public void println(char c): it prints the specified char
value and terminates the line.
public void println(char[] c): it prints the specified
character array values and terminates the line.
public void println(int i): it prints the specified int value
and terminates the line.
public void println(long l): it prints the specified long
value and terminates the line.
public void println(float f): it prints the specified float
value and terminates the line.
import java.io.*;
class PrintStreamTest{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("mfile.txt")
;
6.
7.
8.
pout.println("Hello Java");
9.
pout.println("Welcome to Java");
10.
pout.close();
11.
fout.close();
12.
13.
}
14.
}
download this PrintStream example
Example of printf() method of java.io.PrintStream class:
Let's see the simple example of printing integer value by format
specifier.
1.
2.
3.
4.
5.
6.
7.
class PrintStreamTest{
public static void main(String args[]){
int a=10;
System.out.printf("%d",a);//Note, out is the object of Prin
tStream class
}
}
Output:10
Compressing and Uncompressing File
The DeflaterOutputStream and InflaterInputStream classes
provide mechanism to compress and uncompress the data in
the deflate compression format.
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.
import java.io.*;
import java.util.zip.*;
class UnCompress{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("def.txt");
InflaterInputStream in=new InflaterInputStream(fin);
FileOutputStream fout=new FileOutputStream("D.java");
int i;
while((i=in.read())!=-1){
fout.write((byte)i);
fout.flush();
}
fin.close();
fout.close();
in.close();
}catch(Exception e){System.out.println(e);}
System.out.println("rest of the code");
}
}
import java.io.*;
class PipedWR{
public static void main(String args[])throws Exception{
final PipedOutputStream pout=new PipedOutputStream();
final PipedInputStream pin=new PipedInputStream();
pout.connect(pin);//connecting the streams
//creating one thread t1 which writes the data
Thread t1=new Thread(){
public void run(){
for(int i=65;i<=90;i++){
try{
pout.write(i);
Thread.sleep(1000);
}catch(Exception e){}
}
}
};
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
Serialization
1. Serialization
2. Serializable Interface
3. ObjectOutputStream class
4. Example of Serialization
5. Deserialization
6. ObjectInputStream class
7. Example of Deserialization
8. Serialization with Inheritance
9. Externalizable interface
10.
11.
12.
Serializing the object of a class that has non-serialzable
object
13.
Deserializing the class object that have parameterized
constructor only
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.
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
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.
Commonly used Constructors:
1) public ObjectOutputStream(OutputStream out) throws
IOException {}creates an ObjectOutputStream that writes to
the specified OutputStream.
Commonly used Methods:
1) public final void writeObject(Object obj) throws
IOException {}write the specified object to the
ObjectOutputStream.
2) public void flush() throws IOException {}flushes the
current output stream.
Example of Serialization
In this example, we are going to serialize the object of Student
class. The writeObject() method of ObjectOutputStream class
provides the functionality to serialize the object. We are saving
the state of the object in the file named f.txt.
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
download this example of serialization
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.
Commonly used Constructors:
1) public ObjectInputStream(InputStream in) throws
IOException {}creates an ObjectInputStream that reads from
the specified InputStream.
Commonly used Methods:
1) public final Object readObject() throws IOException,
ClassNotFoundException{}reads an object from the input
stream.
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 FileIn
putStream("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
download this example of deserialization
Serialization with Inheritance
If a class implements Serilizable then all its subclasses will also be
serilizable. Let's see the example given below:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
1.
2.
3.
4.
{
5.
6.
7.
8.
9.
import java.io.Serializable;
class Person implements Serializable{
int id;
String name;
Person(int id, String name) {
this.id = id;
this.name = name;
}
}
class Student extends Person{
String course;
int fee;
public Student(int id, String name, String course, int fee)
super(id,name);
this.course=course;
this.fee=fee;
}
}
Now you can serialize the Student class object that extends the
Person class which is Serializable.Parent class properties are
inherited to subclasses so if parent class is Serializable, subclass
would also be.
Externalizable interface:
The Externalizable interface provides the facility of writing the
state of an object into a byte stream in compress format. It is
not a marker interface.
The Externalizable interface provides two methods:
public void writeExternal(ObjectOutput out) throws
IOException
11.
12.
Serializing the object of a class that has non-serialzable
object
13.
Deserializing the class object that have parameterized
constructor only
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.
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
8.
9.
10.
this.name = name;
}
}
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.
Commonly used Constructors:
1) public ObjectOutputStream(OutputStream out) throws
IOException {}creates an ObjectOutputStream that writes to
the specified OutputStream.
Commonly used Methods:
1) public final void writeObject(Object obj) throws
IOException {}write the specified object to the
ObjectOutputStream.
2) public void flush() throws IOException {}flushes the
current output stream.
Example of Serialization
In this example, we are going to serialize the object of Student
class. The writeObject() method of ObjectOutputStream class
provides the functionality to serialize the object. We are saving
the state of the object in the file named f.txt.
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
download this example of serialization
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.
Commonly used Constructors:
1) public ObjectInputStream(InputStream in) throws
IOException {}creates an ObjectInputStream that reads from
the specified InputStream.
Commonly used Methods:
1) public final Object readObject() throws IOException,
ClassNotFoundException{}reads an object from the input
stream.
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 FileIn
putStream("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
download this example of deserialization
Serialization with Inheritance
If a class implements Serilizable then all its subclasses will also be
serilizable. Let's see the example given below:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
1.
2.
3.
4.
{
5.
6.
7.
8.
9.
import java.io.Serializable;
class Person implements Serializable{
int id;
String name;
Person(int id, String name) {
this.id = id;
this.name = name;
}
}
class Student extends Person{
String course;
int fee;
public Student(int id, String name, String course, int fee)
super(id,name);
this.course=course;
this.fee=fee;
}
}
Now you can serialize the Student class object that extends the
Person class which is Serializable.Parent class properties are
inherited to subclasses so if parent class is Serializable, subclass
would also be.
Externalizable interface:
The Externalizable interface provides the facility of writing the
state of an object into a byte stream in compress format. It is
not a marker interface.
The Externalizable interface provides two methods:
public void writeExternal(ObjectOutput out) throws
IOException
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
transient int age;//Now it will not be serialized
public Student(int id, String name,int age) {
this.id = id;
this.name = name;
this.age=age;
}
}
import java.io.*;
class Persist{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi",22);
FileOutputStream f=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(f);
out.writeObject(s1);
out.flush();
System.out.println("success");
}
}
<strong>Output:</strong>succss
Networking:
Networking is a concept of connecting two or more computing devices together so
that we can share resources.
Advantage:
sharing resources
Do You Know ?
URL class
InetAddress class
Networking Terminology:
There are some networking terminologies given below:
IP Address
Protocol
Port Number
MAC Address
Socket
IP Address:
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It
is composed of octets that range from 0 to 255.
Protocol:
A protocol is a set of rules basically that is followed for communication. For
example:
TCP
FTP
Telnet
SMTP
POP etc.
Socket Programming:
Socket programming is performed for communication between the machines.
Socket programming can be connection-oriented or connectionless. Socket and
ServerSocket classes are used for connection-oriented socket programming. The
client in socket programming must know two information:
1. IPaddress of Server, and
2. Port number.
Socket class:
A socket is simply an endpoint for communications between the machines. The
Socket class can be used to create a socket.
Commonly used methods of Socket class:
1) public InputStream getInputStream()
2) public OutputStream getOutputStream()
3) public synchronized void close()
ServerSocket class:
The ServerSocket class can be used to create a server socket. This object is used to
establish communication with the clients.
Commonly used methods of ServerSocket class:
1) public Socket accept()
1) public InputStream getInputStream()
2) public OutputStream getOutputStream()
3) public synchronized void close()
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
//MyClient.java
import java.io.*;
import java.net.*;
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
download this example
To execute this program open two command prompts and execute each program at
each command prompt as displayed in the below figure.
URL class:
The URL class represents a URL. URL is an acronym for Uniform Resource Locator. It
points to a resource on the World Wide Web. For example:
1. http://www.javatpoint.com/sonoojaiswal/index.jsp
A URL contains many informations:
File Name or directory name: In this case, index.jsp is the file name.
System.out.print("Protocol: "+url.getProtocol());
}catch(Exception e){System.out.println(e);}
}
}
Output:Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /sonoojaiswal/index.jsp
InetAddress ip=InetAddress.getByName("www.javatpoint.com");
}catch(Exception e){System.out.println(e);}
}
}
Output:Host Name: www.javatpoint.com
IP Address: 206.51.231.148
DatagramSocket class
The DatagramSocket class represents a connection-less socket for sending and
receiving datagram packets. Datagram is basically an information but there is no
gurantee of its content, arrival or arrival time. The DatagramSocket and
DatagramPacket classes are used for connection-less socket programming.
Commonly used Constructors of DatagramSocket class
DatagramPacket class:
The DatagramPacket is message that can be sent or received. If you send multiple
packet, it may arrive in any order. Moreover, packet delivery is not guaranteed.
Commonly used Constructors of DatagramPacket class
packets.
7.
8.
9.
InetAddress ip = InetAddress.getByName("127.0.0.1");
10.
11.
12.
ds.send(dp);
13.
ds.close();
14. }
15.}
Example of Receiving DatagramPacket by DatagramSocket
1. //DReceiver.java
2.
3. import java.net.*;
4.
7.
8.
9.
10.
11.
12.
ds.receive(dp);
13.
14.
15.
System.out.println(str);
16.
ds.close();
17. }
18.}
download this example
Abstract Windowing Toolkit (AWT):
Abstract Windowing Toolkit (AWT) is used for GUI programming in java.
Container:
The Container is a component in AWT that can contain another components like
buttons, textfields, labels etc. The classes that extends Container class are known
as container.
Window:
The window is the container that have no borders and menubars. You must use
frame, dialog or another window for creating a window.
Panel:
The Panel is the container that doesn't contain title bar and MenuBars. It can have
other components like button, textfield etc.
Frame:
The Frame is the container that contain title bar and can have MenuBars. It can
have other components like button, textfield etc.
Commonly used Methods of Component class:
1)public void add(Component c)
2)public void setSize(int width,int height)
3)public void setLayout(LayoutManager m)
4)public void setVisible(boolean)
Creating a Frame:
There are two ways to create a frame:
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
}
public static void main(String args[]){
}
}
download this example
public void setBounds(int xaxis, int yaxis, int width, int height); have been
used in the above example that sets the position of the button.
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
}
}
download this example
Event and Listener (Event Handling):
Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc. The java.awt.event package provides many event classes and
Listener interfaces for event handling.
Event classes and Listener interfaces:
Event Classes
Listener Interfaces
ActionEvent
ActionListener
MouseEvent
MouseWheelEvent
MouseWheelListener
KeyEvent
KeyListener
ItemEvent
ItemListener
TextEvent
TextListener
AdjustmentEvent
AdjustmentListener
WindowEvent
WindowListener
ComponentEvent
ComponentListener
ContainerEvent
ContainerListener
FocusEvent
FocusListener
For registering the component with the Listener, many classes provide the
registration methods. For example:
Button
o
MenuItem
o
TextArea
Choice
o
Checkbox
o
TextField
List
o
EventHandling Codes:
We can put the event handling code into one of the following places:
1. Same class
2. Other class
3. Annonymous class
tf=new TextField();
tf.setBounds(60,50,170,20);
b.addActionListener(this);
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
2. import java.awt.event.*;
3.
4. class AEvent2 extends Frame implements ActionListener{
5. TextField tf;
6. AEvent2(){
7.
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10.
11.Button b=new Button("click me");
12.b.setBounds(100,120,80,30);
13.
14.b.addActionListener(this);
15.
16.add(b);add(tf);
17.
18.setSize(300,300);
19.setLayout(null);
20.setVisible(true);
21.
22.}
23.
24.public void actionPerformed(ActionEvent e){
25.tf.setText("Welcome");
26.}
27.
28.public static void main(String args[]){
29.new AEvent2();
30.}
31.}
import java.awt.event.*;
tf=new TextField();
tf.setBounds(60,50,170,20);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}
It is lightweight.
It has more powerful componenets like tables, lists, scroll panes, color
chooser, tabbed pane etc.
What is JFC ?
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Do You Know ?
Hierarchy of swing:
Creating a Frame:
There are two ways to create a frame:
17.
18.public static void main(String[] args) {
19.new Simple();
20.}
21.}
download this example
public void setBounds(int xaxis, int yaxis, int width, int height); have been
used in the above example that sets the position of the button.
1. import javax.swing.*;
2. public class Simple2 extends JFrame{
3. JFrame f;
4. Simple2(){
5.
6. JButton b=new JButton("click");
7. b.setBounds(130,100,100, 40);
8.
9. add(b);
10.
11.setSize(400,500);
12.setLayout(null);
13.setVisible(true);
14.}
15.
16.public static void main(String[] args) {
17.new Simple2();
18.}
19.}
download this example
Next TopicJButton Class
prev
next>>
32
11
Share
11
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
JRadioButton class:
The JRadioButton class is used to create a radio button.
Commonly used Constructors of JRadioButton class:
6. f=new JFrame();
7.
8. JRadioButton r1=new JRadioButton("A) Male");
9. JRadioButton r2=new JRadioButton("B) FeMale");
10.r1.setBounds(50,100,70,30);
11.r2.setBounds(50,150,70,30);
12.
13.ButtonGroup bg=new ButtonGroup();
14.bg.add(r1);bg.add(r2);
15.
16.f.add(r1);f.add(r2);
17.
18.f.setSize(300,300);
19.f.setLayout(null);
20.f.setVisible(true);
21.}
22.public static void main(String[] args) {
23.
new Radio();
24.}
25.}
download this example
ButtonGroup class:
The ButtonGroup class can be used to group multiple buttons so that at a time only
one button can be selected.
JTextArea class (Swing Tutorial):
The JTextArea class is used to create a text area. It is a multiline area that displays
the plain text only.
Commonly used Constructors:
JTextArea(String s): creates a text area that displays specified text initally.
JTextArea(int row, int column): creates a text area with the specified
number of rows and columns that displays no text initally..
JTextArea(String s, int row, int column): creates a text area with the
specified number of rows and columns that displays specified text.
JTextArea area;
6.
JFrame f;
7.
TArea(){
8.
f=new JFrame();
9.
10.
area=new JTextArea(300,300);
11.
area.setBounds(10,30,300,300);
12.
13.
area.setBackground(Color.black);
14.
area.setForeground(Color.white);
15.
16.
f.add(area);
17.
18.
f.setSize(400,400);
19.
f.setLayout(null);
20.
f.setVisible(true);
21.}
22.
23.
24.
new TArea();
}
25.}
JComboBox class:
The JComboBox class is used to create the combobox (drop-down list). At a time
only one item can be selected from the item list.
Commonly used Constructors of JComboBox class:
JComboBox()
JComboBox(Object[] items)
JComboBox(Vector<?> items)
6.
7.
String country[]={"India","Aus","U.S.A","England","Newzeland"};
8.
9.
10.
cb.setBounds(50, 50,90,20);
11.
f.add(cb);
12.
13.
f.setLayout(null);
14.
f.setSize(400,500);
15.
f.setVisible(true);
16.
17.}
18.public static void main(String[] args) {
19.
new Combo();
20.
21.}
22.}
JTable class (Swing Tutorial):
The JTable class is used to display the data on two dimentional tables of cells.
Commonly used Constructors of JTable class:
JFrame f;
4. MyTable(){
5.
f=new JFrame();
6.
7.
8.
9.
10.
String column[]={"ID","NAME","SALARY"};
11.
12.
13.
jt.setBounds(30,40,200,300);
14.
15.
16.
f.add(sp);
17.
18.
f.setSize(300,400);
19.// f.setLayout(null);
20.
f.setVisible(true);
21.}
22.public static void main(String[] args) {
23.
new MyTable();
24.}
25.}
JColorChooser class:
The JColorChooser class is used to create a color chooser dialog box so that user
can select any color.
Commonly used Constructors of JColorChooser class:
1. import java.awt.event.*;
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class JColorChooserExample extends JFrame implements ActionListener
{
6. JButton b;
7. Container c;
8.
9. JColorChooserExample(){
10.
c=getContentPane();
11.
c.setLayout(new FlowLayout());
12.
13.
b=new JButton("color");
14.
b.addActionListener(this);
15.
16.
c.add(b);
17.}
18.
19.public void actionPerformed(ActionEvent e) {
20.Color initialcolor=Color.RED;
21.Color color=JColorChooser.showDialog(this,"Select a color",initialcolor);
22.c.setBackground(color);
23.}
24.
25.public static void main(String[] args) {
26.
27.
ch.setSize(400,400);
28.
ch.setVisible(true);
29.
ch.setDefaultCloseOperation(EXIT_ON_CLOSE);
30.}
31.}
JProgressBar class:
The JProgressBar class is used to display the progress of the task.
Commonly used Constructors of JProgressBar class:
5.
6. MyProgress(){
7. jb=new JProgressBar(0,2000);
8. jb.setBounds(40,40,200,30);
9.
10.jb.setValue(0);
11.jb.setStringPainted(true);
12.
13.add(jb);
14.setSize(400,400);
15.setLayout(null);
16.}
17.
18.public void iterate(){
19.while(i<=2000){
20. jb.setValue(i);
21. i=i+20;
22. try{Thread.sleep(150);}catch(Exception e){}
23.}
24.}
25.public static void main(String[] args) {
26.
27.
m.setVisible(true);
28.
m.iterate();
29.}
30.}
JSlider class:
The JSlider is used to create the slider. By using JSlider a user can select a value
from a specific range.
Commonly used Constructors of JSlider class:
JSlider(): creates a slider with the initial value of 50 and range of 0 to 100.
JSlider(int min, int max): creates a horizontal slider using the given min
and max.
JSlider(int min, int max, int value): creates a horizontal slider using the
given min, max and value.
JSlider(int orientation, int min, int max, int value): creates a slider
using the given orientation, min, max and value.
1. import javax.swing.*;
2.
3. public class SliderExample1 extends JFrame{
4.
5. public SliderExample1() {
6. JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
7. JPanel panel=new JPanel();
8. panel.add(slider);
9.
10.add(panel);
11.}
12.
13.public static void main(String s[]) {
14.SliderExample1 frame=new SliderExample1();
15.frame.pack();
16.frame.setVisible(true);
17.}
18.}
download this example
1. import javax.swing.*;
2.
3. public class SliderExample extends JFrame{
4.
5. public SliderExample() {
6.
7. JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
8. slider.setMinorTickSpacing(2);
9. slider.setMajorTickSpacing(10);
10.
11.slider.setPaintTicks(true);
12.slider.setPaintLabels(true);
13.
14.JPanel panel=new JPanel();
15.panel.add(slider);
16.add(panel);
17.}
18.
19.public static void main(String s[]) {
20.SliderExample frame=new SliderExample();
21.frame.pack();
22.frame.setVisible(true);
23.
24.}
25.}
1. import javax.swing.*;
2. import java.awt.*;
3. import java.text.*;
4. import java.util.*;
5. public class DigitalWatch implements Runnable{
6. JFrame f;
7. Thread t=null;
8. int hours=0, minutes=0, seconds=0;
9. String timeString = "";
10. JButton b;
11.
12. DigitalWatch(){
13.
f=new JFrame();
14.
15.
16.
t = new Thread(this);
t.start();
17.
18.
19.
b=new JButton();
b.setBounds(100,100,100,50);
20.
21.
f.add(b);
22.
f.setSize(300,400);
23.
f.setLayout(null);
24.
f.setVisible(true);
25. }
26.
27. public void run() {
28.
try {
29.
while (true) {
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
printTime();
42.
43.
44.
45.
46.
catch (Exception e) { }
47. }
48.
49. public void printTime(){
50. b.setText(timeString);
51. }
52.
53. public static void main(String[] args) {
54.
new DigitalWatch();
55.
56.
57. }
58. }
Displaying graphics in swing:
java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to draw
the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a
rectangle with the specifed width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used
to fill rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is
used to draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used
to fill oval with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to
draw line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used to fill a circular or elliptical arc.
10.public abstract void setColor(Color c): is used to set the graphics current
color to the specified color.
11.public abstract void setFont(Font font): is used to set the graphics
current font to the specified font.
1. import java.awt.*;
2. import javax.swing.JFrame;
3.
4. public class DisplayGraphics extends Canvas{
5.
6.
7.
g.drawString("Hello",40,40);
8.
setBackground(Color.WHITE);
9.
10.
g.drawOval(30,130,50, 60);
11.
setForeground(Color.RED);
12.
g.fillOval(130,130,50, 60);
13.
14.
15.
16.
17.
18.
19.
20.
f.add(m);
21.
f.setSize(400,400);
22.
//f.setLayout(null);
23.
f.setVisible(true);
24.
25.
26.}
Displaying image in swing:
For displaying image, we can use the method drawImage() of Graphics class.
Syntax of drawImage() method:
1. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
1. import java.awt.*;
2. import javax.swing.JFrame;
3.
4. public class MyCanvas extends Canvas{
5.
6.
7.
8.
Toolkit t=Toolkit.getDefaultToolkit();
9.
Image i=t.getImage("p3.gif");
10.
g.drawImage(i, 120,100,this);
11.
12.
13.
14.
15.
16.
f.add(m);
17.
f.setSize(400,400);
18.
f.setVisible(true);
19.
20.
21.}
39. f.add(mb);f.add(ta);
40.
41. f.setLayout(null);
42. f.setSize(500,500);
43. f.setVisible(true);
44. }
45.
46. public void actionPerformed(ActionEvent e) {
47. if(e.getSource()==cut)
48. ta.cut();
49. if(e.getSource()==paste)
50. ta.paste();
51. if(e.getSource()==copy)
52. ta.copy();
53. if(e.getSource()==selectAll)
54. ta.selectAll();
55. }
56.
57. public static void main(String[] args) {
58.
new Notepad();
59. }
60. }
1. import java.awt.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. import java.io.*;
5.
6. public class OpenMenu extends JFrame implements ActionListener{
7. JMenuBar mb;
8. JMenu file;
9. JMenuItem open;
10. JTextArea ta;
11. OpenMenu(){
12. open=new JMenuItem("Open File");
13. open.addActionListener(this);
14.
15. file=new JMenu("File");
16. file.add(open);
17.
18. mb=new JMenuBar();
19. mb.setBounds(0,0,800,20);
20. mb.add(file);
21.
22. ta=new JTextArea(800,800);
23. ta.setBounds(0,20,800,800);
24.
25. add(mb);
26. add(ta);
27.
28. }
29. public void actionPerformed(ActionEvent e) {
30. if(e.getSource()==open){
31. openFile();
32. }
33. }
34.
35. void openFile(){
36. JFileChooser fc=new JFileChooser();
37. int i=fc.showOpenDialog(this);
38.
39. if(i==JFileChooser.APPROVE_OPTION){
40. File f=fc.getSelectedFile();
41. String filepath=f.getPath();
42.
43. displayContent(filepath);
44.
45. }
46.
47. }
48.
49. void displayContent(String fpath){
50. try{
51. BufferedReader br=new BufferedReader(new FileReader(fpath));
52. String s1="",s2="";
53.
54. while((s1=br.readLine())!=null){
55. s2+=s1+"\n";
56. }
57. ta.setText(s2);
58. br.close();
59. }catch (Exception e) {e.printStackTrace(); }
60. }
61.
62. public static void main(String[] args) {
63.
64.
om.setSize(800,800);
65.
om.setLayout(null);
66.
om.setVisible(true);
67.
om.setDefaultCloseOperation(EXIT_ON_CLOSE);
68. }
69. }
Example of Notepad
1. import java.io.*;
2. import java.util.Date;
3. import java.awt.*;
4. import java.awt.event.*;
5. import javax.swing.*;
6. import javax.swing.event.*;
7.
8. /************************************/
9. class FileOperation
10. {
11. Notepad npd;
12.
13. boolean saved;
14. boolean newFileFlag;
15. String fileName;
16. String applicationTitle="Javapad";
17.
18. File fileRef;
19. JFileChooser chooser;
20. /////////////////////////////
21. boolean isSave(){return saved;}
22. void setSave(boolean saved){this.saved=saved;}
{return saveFile(fileRef);}
64.
65. return saveAsFile();
66. }
67. ////////////////////////////////////
68. boolean saveAsFile()
69. {
70. File temp=null;
71. chooser.setDialogTitle("Save As...");
72. chooser.setApproveButtonText("Save Now");
73. chooser.setApproveButtonMnemonic(KeyEvent.VK_S);
74. chooser.setApproveButtonToolTipText("Click me to save!");
75.
76. do
77. {
78. if(chooser.showSaveDialog(this.npd.f)!=JFileChooser.APPROVE_OPTION)
79.
return false;
80. temp=chooser.getSelectedFile();
81. if(!temp.exists()) break;
82. if( JOptionPane.showConfirmDialog(
83.
84.
"Save As",JOptionPane.YES_NO_OPTION
85.
86.
)==JOptionPane.YES_OPTION)
break;
87. }while(true);
88.
89.
90. return saveFile(temp);
91. }
92.
93. ////////////////////////
94. boolean openFile(File temp)
95. {
96. FileInputStream fin=null;
97. BufferedReader din=null;
98.
99. try
100.
101.
fin=new FileInputStream(temp);
102.
103.
104.
while(str!=null)
105.
106.
str=din.readLine();
107.
if(str==null)
108.
break;
109.
this.npd.ta.append(str+"\n");
110.
111.
112.
113.
114.
finally
115.
{try{din.close();fin.close();}catch(IOException excp){}}
116.
updateStatus(temp,true);
117.
this.npd.ta.setCaretPosition(0);
118.
return true;
119.
120.
///////////////////////
121.
void openFile()
122.
123.
if(!confirmSave()) return;
124.
chooser.setDialogTitle("Open File...");
125.
chooser.setApproveButtonText("Open this");
126.
chooser.setApproveButtonMnemonic(KeyEvent.VK_O);
127.
128.
129.
File temp=null;
130.
do
131.
132.
if(chooser.showOpenDialog(this.npd.f)!=JFileChooser.APPROVE_OPTION)
133.
134.
return;
temp=chooser.getSelectedFile();
135.
136.
137.
if(temp.exists()) break;
138.
JOptionPane.showMessageDialog(this.npd.f,
139.
140.
141.
"Open", JOptionPane.INFORMATION_MESSAGE);
142.
143.
} while(true);
144.
145.
this.npd.ta.setText("");
146.
147.
if(!openFile(temp))
148.
149.
fileName="Untitled"; saved=true;
150.
this.npd.f.setTitle(fileName+" - "+applicationTitle);
151.
152.
if(!temp.canWrite())
153.
newFileFlag=true;
154.
155.
156.
////////////////////////
157.
158.
159.
if(saved)
160.
161.
this.saved=true;
162.
fileName=new String(temp.getName());
163.
if(!temp.canWrite())
164.
165.
fileRef=temp;
166.
167.
168.
newFileFlag=false;
169.
170.
else
171.
172.
173.
174.
175.
///////////////////////
176.
boolean confirmSave()
177.
178.
179.
180.
if(!saved)
181.
182.
int x=JOptionPane.showConfirmDialog(this.npd.f,strMsg,applicationTitle,
183.
JOptionPane.YES_NO_CANCEL_OPTION);
184.
185.
186.
187.
188.
return true;
189.
190.
///////////////////////////////////////
191.
void newFile()
192.
193.
if(!confirmSave()) return;
194.
195.
this.npd.ta.setText("");
196.
fileName=new String("Untitled");
197.
fileRef=new File(fileName);
198.
saved=true;
199.
newFileFlag=true;
200.
this.npd.f.setTitle(fileName+" - "+applicationTitle);
201.
202.
//////////////////////////////////////
203.
204.
/************************************/
205.
206.
207.
208.
JFrame f;
209.
JTextArea ta;
210.
JLabel statusBar;
211.
212.
213.
214.
String applicationName="Javapad";
215.
216.
217.
int lastSearchIndex;
218.
219.
FileOperation fileHandler;
220.
FontChooser fontDialog=null;
221.
FindDialog findReplaceDialog=null;
222.
JColorChooser bcolorChooser=null;
223.
JColorChooser fcolorChooser=null;
224.
JDialog backgroundDialog=null;
225.
JDialog foregroundDialog=null;
226.
227.
228.
/****************************/
229.
Notepad()
230.
231.
232.
ta=new JTextArea(30,60);
233.
statusBar=new JLabel("||
234.
f.add(new JScrollPane(ta),BorderLayout.CENTER);
235.
f.add(statusBar,BorderLayout.SOUTH);
236.
237.
238.
createMenuBar(f);
239.
//f.setSize(350,350);
240.
f.pack();
241.
f.setLocation(100,50);
242.
f.setVisible(true);
243.
f.setLocation(150,50);
244.
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Ln 1, Col 1 ",JLabel.RIGHT);
245.
246.
fileHandler=new FileOperation(this);
247.
248.
/////////////////////
249.
250.
ta.addCaretListener(
251.
new CaretListener()
252.
253.
254.
255.
256.
257.
try
258.
259.
pos=ta.getCaretPosition();
260.
lineNumber=ta.getLineOfOffset(pos);
261.
column=pos-ta.getLineStartOffset(lineNumber);
262.
}catch(Exception excp){}
263.
if(ta.getText().length()==0){lineNumber=0; column=0;}
264.
statusBar.setText("||
265.
266.
});
267.
//////////////////
268.
269.
270.
271.
272.
273.
};
274.
ta.getDocument().addDocumentListener(myListener);
275.
/////////
276.
277.
278.
279.
280.
if(fileHandler.confirmSave())System.exit(0);
281.
282.
};
283.
f.addWindowListener(frameClose);
284.
//////////////////
285.
/*
286.
287.
288.
289.
ta.append("\nHello");
290.
291.
fileHandler.saved=true;
292.
*/
293.
294.
////////////////////////////////////
295.
void goTo()
296.
297.
int lineNumber=0;
298.
try
299.
300.
lineNumber=ta.getLineOfOffset(ta.getCaretPosition())+1;
301.
String tempStr=JOptionPane.showInputDialog(f,"Enter Line Number:",""+lineNu
mber);
302.
if(tempStr==null)
303.
{return;}
304.
lineNumber=Integer.parseInt(tempStr);
305.
ta.setCaretPosition(ta.getLineStartOffset(lineNumber-1));
306.
}catch(Exception e){}
307.
308.
///////////////////////////////////
309.
310.
311.
String cmdText=ev.getActionCommand();
312.
////////////////////////////////////
313.
if(cmdText.equals(fileNew))
314.
fileHandler.newFile();
315.
else if(cmdText.equals(fileOpen))
316.
fileHandler.openFile();
317.
////////////////////////////////////
318.
else if(cmdText.equals(fileSave))
319.
fileHandler.saveThisFile();
320.
////////////////////////////////////
321.
else if(cmdText.equals(fileSaveAs))
322.
fileHandler.saveAsFile();
323.
////////////////////////////////////
324.
else if(cmdText.equals(fileExit))
325.
{if(fileHandler.confirmSave())System.exit(0);}
326.
////////////////////////////////////
327.
else if(cmdText.equals(filePrint))
328.
JOptionPane.showMessageDialog(
329.
Notepad.this.f,
330.
331.
"Bad Printer",
332.
JOptionPane.INFORMATION_MESSAGE
333.
);
334.
////////////////////////////////////
335.
else if(cmdText.equals(editCut))
336.
ta.cut();
337.
////////////////////////////////////
338.
else if(cmdText.equals(editCopy))
339.
ta.copy();
340.
////////////////////////////////////
341.
else if(cmdText.equals(editPaste))
342.
ta.paste();
343.
////////////////////////////////////
344.
else if(cmdText.equals(editDelete))
345.
ta.replaceSelection("");
346.
////////////////////////////////////
347.
else if(cmdText.equals(editFind))
348.
349.
if(Notepad.this.ta.getText().length()==0)
350.
351.
352.
findReplaceDialog=new FindDialog(Notepad.this.ta);
353.
findReplaceDialog.showDialog(Notepad.this.f,true);//find
354.
355.
////////////////////////////////////
356.
else if(cmdText.equals(editFindNext))
357.
358.
if(Notepad.this.ta.getText().length()==0)
359.
360.
361.
if(findReplaceDialog==null)
362.
363.
364.
findReplaceDialog.findNextWithSelection();
365.
366.
////////////////////////////////////
367.
else if(cmdText.equals(editReplace))
368.
369.
if(Notepad.this.ta.getText().length()==0)
370.
371.
372.
if(findReplaceDialog==null)
373.
findReplaceDialog=new FindDialog(Notepad.this.ta);
374.
findReplaceDialog.showDialog(Notepad.this.f,false);//replace
375.
376.
////////////////////////////////////
377.
else if(cmdText.equals(editGoTo))
378.
379.
if(Notepad.this.ta.getText().length()==0)
380.
381.
goTo();
382.
383.
////////////////////////////////////
384.
else if(cmdText.equals(editSelectAll))
385.
ta.selectAll();
386.
////////////////////////////////////
387.
else if(cmdText.equals(editTimeDate))
388.
ta.insert(new Date().toString(),ta.getSelectionStart());
389.
////////////////////////////////////
390.
else if(cmdText.equals(formatWordWrap))
391.
392.
JCheckBoxMenuItem temp=(JCheckBoxMenuItem)ev.getSource();
393.
ta.setLineWrap(temp.isSelected());
394.
395.
////////////////////////////////////
396.
else if(cmdText.equals(formatFont))
397.
398.
if(fontDialog==null)
399.
fontDialog=new FontChooser(ta.getFont());
400.
401.
if(fontDialog.showDialog(Notepad.this.f,"Choose a font"))
402.
Notepad.this.ta.setFont(fontDialog.createFont());
403.
404.
////////////////////////////////////
405.
else if(cmdText.equals(formatForeground))
406.
showForegroundColorDialog();
407.
////////////////////////////////////
408.
else if(cmdText.equals(formatBackground))
409.
410.
showBackgroundColorDialog();
////////////////////////////////////
411.
412.
else if(cmdText.equals(viewStatusBar))
413.
414.
JCheckBoxMenuItem temp=(JCheckBoxMenuItem)ev.getSource();
415.
statusBar.setVisible(temp.isSelected());
416.
417.
////////////////////////////////////
418.
else if(cmdText.equals(helpAboutNotepad))
419.
420.
JOptionPane.showMessageDialog(Notepad.this.f,aboutText,"Dedicated 2 u!",
421.
JOptionPane.INFORMATION_MESSAGE);
422.
423.
else
424.
425.
}//action Performed
426.
////////////////////////////////////
427.
void showBackgroundColorDialog()
428.
429.
if(bcolorChooser==null)
430.
431.
432.
bcolorChooser=new JColorChooser();
if(backgroundDialog==null)
backgroundDialog=JColorChooser.createDialog
433.
(Notepad.this.f,
434.
formatBackground,
435.
false,
436.
bcolorChooser,
437.
new ActionListener()
438.
439.
Notepad.this.ta.setBackground(bcolorChooser.getColor());}},
440.
null);
441.
442.
backgroundDialog.setVisible(true);
443.
444.
////////////////////////////////////
445.
void showForegroundColorDialog()
446.
447.
if(fcolorChooser==null)
448.
449.
450.
fcolorChooser=new JColorChooser();
if(foregroundDialog==null)
foregroundDialog=JColorChooser.createDialog
451.
(Notepad.this.f,
452.
formatForeground,
453.
false,
454.
fcolorChooser,
455.
new ActionListener()
456.
457.
458.
459.
Notepad.this.ta.setForeground(fcolorChooser.getColor());}},
null);
460.
foregroundDialog.setVisible(true);
461.
462.
463.
///////////////////////////////////
464.
465.
466.
467.
temp.addActionListener(al);
468.
toMenu.add(temp);
469.
470.
return temp;
471.
472.
////////////////////////////////////
473.
JMenuItem createMenuItem(String s, int key,JMenu toMenu,int aclKey,ActionLis
tener al)
474.
475.
476.
temp.addActionListener(al);
477.
));
temp.setAccelerator(KeyStroke.getKeyStroke(aclKey,ActionEvent.CTRL_MASK
478.
toMenu.add(temp);
479.
480.
return temp;
481.
482.
////////////////////////////////////
483.
JCheckBoxMenuItem createCheckBoxMenuItem(String s,
484.
485.
486.
487.
temp.setMnemonic(key);
488.
temp.addActionListener(al);
489.
temp.setSelected(false);
490.
toMenu.add(temp);
491.
492.
return temp;
493.
494.
////////////////////////////////////
495.
496.
497.
498.
temp.setMnemonic(key);
499.
toMenuBar.add(temp);
500.
return temp;
501.
502.
/*********************************/
503.
void createMenuBar(JFrame f)
504.
505.
506.
JMenuItem temp;
507.
508.
JMenu fileMenu=createMenu(fileText,KeyEvent.VK_F,mb);
509.
JMenu editMenu=createMenu(editText,KeyEvent.VK_E,mb);
510.
JMenu formatMenu=createMenu(formatText,KeyEvent.VK_O,mb);
511.
JMenu viewMenu=createMenu(viewText,KeyEvent.VK_V,mb);
512.
JMenu helpMenu=createMenu(helpText,KeyEvent.VK_H,mb);
513.
514.
createMenuItem(fileNew,KeyEvent.VK_N,fileMenu,KeyEvent.VK_N,this);
515.
createMenuItem(fileOpen,KeyEvent.VK_O,fileMenu,KeyEvent.VK_O,this);
516.
createMenuItem(fileSave,KeyEvent.VK_S,fileMenu,KeyEvent.VK_S,this);
517.
createMenuItem(fileSaveAs,KeyEvent.VK_A,fileMenu,this);
518.
fileMenu.addSeparator();
519.
temp=createMenuItem(filePageSetup,KeyEvent.VK_U,fileMenu,this);
520.
temp.setEnabled(false);
521.
createMenuItem(filePrint,KeyEvent.VK_P,fileMenu,KeyEvent.VK_P,this);
522.
fileMenu.addSeparator();
523.
createMenuItem(fileExit,KeyEvent.VK_X,fileMenu,this);
524.
525.
s);
temp=createMenuItem(editUndo,KeyEvent.VK_U,editMenu,KeyEvent.VK_Z,thi
526.
temp.setEnabled(false);
527.
editMenu.addSeparator();
528.
s);
cutItem=createMenuItem(editCut,KeyEvent.VK_T,editMenu,KeyEvent.VK_X,thi
529.
copyItem=createMenuItem(editCopy,KeyEvent.VK_C,editMenu,KeyEvent.VK_
C,this);
530.
createMenuItem(editPaste,KeyEvent.VK_P,editMenu,KeyEvent.VK_V,this);
531.
deleteItem=createMenuItem(editDelete,KeyEvent.VK_L,editMenu,this);
532.
deleteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));
533.
editMenu.addSeparator();
534.
his);
findItem=createMenuItem(editFind,KeyEvent.VK_F,editMenu,KeyEvent.VK_F,t
535.
findNextItem=createMenuItem(editFindNext,KeyEvent.VK_N,editMenu,this);
536.
findNextItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3,0));
537.
replaceItem=createMenuItem(editReplace,KeyEvent.VK_R,editMenu,KeyEvent.
VK_H,this);
538.
gotoItem=createMenuItem(editGoTo,KeyEvent.VK_G,editMenu,KeyEvent.VK_
G,this);
539.
editMenu.addSeparator();
540.
selectAllItem=createMenuItem(editSelectAll,KeyEvent.VK_A,editMenu,KeyEve
nt.VK_A,this);
541.
createMenuItem(editTimeDate,KeyEvent.VK_D,editMenu,this)
542.
.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5,0));
543.
544.
createCheckBoxMenuItem(formatWordWrap,KeyEvent.VK_W,formatMenu,this);
545.
546.
createMenuItem(formatFont,KeyEvent.VK_F,formatMenu,this);
547.
formatMenu.addSeparator();
548.
createMenuItem(formatForeground,KeyEvent.VK_T,formatMenu,this);
549.
createMenuItem(formatBackground,KeyEvent.VK_P,formatMenu,this);
550.
551.
createCheckBoxMenuItem(viewStatusBar,KeyEvent.VK_S,viewMenu,this).setSe
lected(true);
552.
553.
LookAndFeelMenu.createLookAndFeelMenuItem(viewMenu,this.f);
554.
555.
556.
temp=createMenuItem(helpHelpTopic,KeyEvent.VK_H,helpMenu,this);
557.
temp.setEnabled(false);
558.
helpMenu.addSeparator();
559.
createMenuItem(helpAboutNotepad,KeyEvent.VK_A,helpMenu,this);
560.
561.
562.
563.
564.
565.
if(Notepad.this.ta.getText().length()==0)
566.
567.
findItem.setEnabled(false);
568.
findNextItem.setEnabled(false);
569.
replaceItem.setEnabled(false);
570.
selectAllItem.setEnabled(false);
571.
gotoItem.setEnabled(false);
572.
573.
else
574.
575.
findItem.setEnabled(true);
576.
findNextItem.setEnabled(true);
577.
replaceItem.setEnabled(true);
578.
selectAllItem.setEnabled(true);
579.
gotoItem.setEnabled(true);
580.
581.
if(Notepad.this.ta.getSelectionStart()==ta.getSelectionEnd())
582.
583.
cutItem.setEnabled(false);
584.
copyItem.setEnabled(false);
585.
deleteItem.setEnabled(false);
586.
587.
else
588.
589.
cutItem.setEnabled(true);
590.
copyItem.setEnabled(true);
591.
deleteItem.setEnabled(true);
592.
593.
594.
595.
596.
};
597.
editMenu.addMenuListener(editMenuListener);
598.
f.setJMenuBar(mb);
599.
600.
/*************Constructor**************/
601.
////////////////////////////////////
602.
603.
604.
new Notepad();
605.
606.
607.
/**************************************/
608.
//public
609.
interface MenuConstants
610.
611.
612.
613.
614.
615.
616.
617.
618.
619.
620.
621.
622.
623.
624.
625.
626.
627.
628.
629.
630.
631.
632.
633.
634.
635.
636.
637.
638.
639.
640.
641.
642.
643.
644.
645.
646.
647.
648.
1. import java.awt.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class puzzle extends JFrame implements ActionListener{
5. JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,next;
6. puzzle(){
7. super("puzzle");
8.
b1=new JButton("1");
9.
26. b8.setBounds(70,130,50,40);
27. b9.setBounds(130,130,50,40);
28. next.setBounds(70,200,100,40);
29.
30. add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);add(b9); add(next);
31. b1.addActionListener(this);
32. b2.addActionListener(this);
33. b3.addActionListener(this);
34. b4.addActionListener(this);
35. b5.addActionListener(this);
36. b6.addActionListener(this);
37. b7.addActionListener(this);
38. b8.addActionListener(this);
39. b9.addActionListener(this);
40. next.addActionListener(this);
41.
42. next.setBackground(Color.black);
43. next.setForeground(Color.green);
44. setSize(250,300);
45. setLayout(null);
46. setVisible(true);
47. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
48. }//end of constuctor
49.
50. public void actionPerformed(ActionEvent e){
51. if(e.getSource()==next){
52. String s=b4.getLabel();
53. b4.setLabel(b9.getLabel());
54. b9.setLabel(s);
55. s=b1.getLabel();
56. b1.setLabel(b5.getLabel());
57. b5.setLabel(s);
58. s=b2.getLabel();
59. b2.setLabel(b7.getLabel());
60. b7.setLabel(s);
61. }
62. if(e.getSource()==b1){
63. String s=b1.getLabel();
64. if(b2.getLabel().equals(" ")){ b2.setLabel(s); b1.setLabel(" ");}
65. else if(b4.getLabel().equals(" ")){ b4.setLabel(s); b1.setLabel(" ");}
66. }//end of if
67.
68. if(e.getSource()==b3){
69. String s=b3.getLabel();
70. if(b2.getLabel().equals(" ")){ b2.setLabel(s); b3.setLabel(" ");}
71. else if(b6.getLabel().equals(" ")){ b6.setLabel(s); b3.setLabel(" ");}
72. }//end of if
73.
74. if(e.getSource()==b2){
75. String s=b2.getLabel();
76. if(b1.getLabel().equals(" ")){ b1.setLabel(s); b2.setLabel(" ");}
77. else if(b3.getLabel().equals(" ")){ b3.setLabel(s); b2.setLabel(" ");}
78. else if(b5.getLabel().equals(" ")){ b5.setLabel(s); b2.setLabel(" ");}
79. }//end of if
80.
81. if(e.getSource()==b4){
82. String s=b4.getLabel();
83. if(b1.getLabel().equals(" ")){ b1.setLabel(s); b4.setLabel(" ");}
84. else if(b7.getLabel().equals(" ")){ b7.setLabel(s); b4.setLabel(" ");}
85. else if(b5.getLabel().equals(" ")){ b5.setLabel(s); b4.setLabel(" ");}
86. }//end of if
87.
88. if(e.getSource()==b5){
89. String s=b5.getLabel();
90. if(b2.getLabel().equals(" ")){ b2.setLabel(s); b5.setLabel(" ");}
91. else if(b4.getLabel().equals(" ")){ b4.setLabel(s); b5.setLabel(" ");}
92. else if(b6.getLabel().equals(" ")){ b6.setLabel(s); b5.setLabel(" ");}
93. else if(b8.getLabel().equals(" ")){ b8.setLabel(s); b5.setLabel(" ");}
94. }//end of if
95.
96. if(e.getSource()==b6){
97.
98. String s=b6.getLabel();
99. if(b9.getLabel().equals(" ")){ b9.setLabel(s); b6.setLabel(" ");}
100.
101.
102.
103.
}//end of if
104.
105.
if(e.getSource()==b7){
106.
String s=b7.getLabel();
107.
108.
109.
110.
}//end of if
111.
112.
if(e.getSource()==b8){
113.
String s=b8.getLabel();
114.
115.
116.
117.
118.
}//end of if
119.
120.
if(e.getSource()==b9){
121.
String s=b9.getLabel();
122.
123.
124.
if(b1.getLabel().equals("1")&&b2.getLabel().equals("2")&&b3.getLabel()
125.
.equals("3")&&b4.getLabel().equals("4")&&b5.getLabel().equals("5")
126.
&&b6.getLabel().equals("6")&&b7.getLabel().equals("7")&&b8.getLabel()
127.
.equals("8")&&b9.getLabel().equals(" ")){
128.
JOptionPane.showMessageDialog(puzzle.this,"!!!you won!!!");
129.
130.
}//end of if
131.
132.
}//end of actionPerformed
133.
134.
135.
136.
new puzzle();
137.
}//end of main
138.
139.
}//end of class
1. import java.awt.event.*;
2. import java.awt.*;
3. import javax.swing.*;
4. class picpuzzle2 extends JFrame implements ActionListener{
5. JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,sample,starB;
6. Icon star;
7. Icon ic0=new ImageIcon("pic/starB0.jpg");
8. Icon ic10=new ImageIcon("pic/starB10.jpg");
9. Icon ic20=new ImageIcon("pic/starB20.jpg");
56. b5.setBounds(110,180,100,100);
57. b6=new JButton(ic6);
58. b6.setBounds(210,180,100,100);
59. b7=new JButton(ic7);
60. b7.setBounds(10,280,100,100);
61. b8=new JButton(ic8);
62. b8.setBounds(110,280,100,100);
63. b9=new JButton(ic9);
64. b9.setBounds(210,280,100,100);
65. sample=new JButton(samicon1);
66. sample.setBounds(380,100,200,200);
67.
68. JLabel l1=new JLabel("Sample:");
69. l1.setBounds(330,200,70,20);
70. JLabel l2=new JLabel("NOTE:
71. icon has power to swap with neighbour icon=");
72. l2.setBounds(5,15,500,20);
73. JLabel l3=new JLabel("click sample picture to next puzzle");
74. l3.setBounds(380,320,200,20);
75. l3.setForeground(Color.red);
76.
77. starB=new JButton(ic0);
78. starB.setBounds(330,5,50,50);
79. star=b9.getIcon();
80.
81. add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);
82. add(b9);add(sample);add(l1);add(l2);add(starB);add(l3);
83. b1.addActionListener(this); b2.addActionListener(this);
84. b3.addActionListener(this); b4.addActionListener(this);
85. b5.addActionListener(this); b6.addActionListener(this);
86. b7.addActionListener(this); b8.addActionListener(this);
87. b9.addActionListener(this);
88.
89. sample.addActionListener(this);
90. setLayout(null);
91. setSize(600,500);
92. setVisible(true);
93. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
94. }
95.
96. public void actionPerformed(ActionEvent e){
97. if(e.getSource()==b1){
98.
99.
Icon s1=b1.getIcon();
if(b2.getIcon()==star){
100.
b2.setIcon(s1);
101.
b1.setIcon(star);
102.
} else if(b4.getIcon()==star){
103.
b4.setIcon(s1);
104.
b1.setIcon(star);
105.
106.
}//end of if
107.
108.
109.
110.
if(e.getSource()==b2){
Icon s1=b2.getIcon();
if(b1.getIcon()==star){
111.
b1.setIcon(s1);
112.
b2.setIcon(star);
113.
} else if(b5.getIcon()==star){
114.
b5.setIcon(s1);
115.
b2.setIcon(star);
116.
117.
else if(b3.getIcon()==star){
118.
b3.setIcon(s1);
119.
b2.setIcon(star);
120.
121.
}//end of if
122.
123.
124.
if(e.getSource()==b3){
Icon s1=b3.getIcon();
125.
if(b2.getIcon()==star){
126.
b2.setIcon(s1);
127.
b3.setIcon(star);
128.
} else if(b6.getIcon()==star){
129.
b6.setIcon(s1);
130.
b3.setIcon(star);
131.
132.
}//end of if
133.
134.
135.
136.
if(e.getSource()==b4){
Icon s1=b4.getIcon();
if(b1.getIcon()==star){
137.
b1.setIcon(s1);
138.
b4.setIcon(star);
139.
} else if(b5.getIcon()==star){
140.
b5.setIcon(s1);
141.
b4.setIcon(star);
142.
143.
else if(b7.getIcon()==star){
144.
b7.setIcon(s1);
145.
b4.setIcon(star);
146.
147.
}//end of if
148.
149.
150.
151.
if(e.getSource()==b5){
Icon s1=b5.getIcon();
if(b2.getIcon()==star){
152.
b2.setIcon(s1);
153.
b5.setIcon(star);
154.
} else if(b4.getIcon()==star){
155.
b4.setIcon(s1);
156.
b5.setIcon(star);
157.
158.
else if(b6.getIcon()==star){
159.
b6.setIcon(s1);
160.
b5.setIcon(star);
161.
162.
else if(b8.getIcon()==star){
163.
b8.setIcon(s1);
164.
b5.setIcon(star);
165.
166.
}//end of if
167.
168.
169.
170.
if(e.getSource()==b6){
Icon s1=b6.getIcon();
if(b3.getIcon()==star){
171.
b3.setIcon(s1);
172.
b6.setIcon(star);
173.
} else if(b5.getIcon()==star){
174.
b5.setIcon(s1);
175.
b6.setIcon(star);
176.
177.
else if(b9.getIcon()==star){
178.
b9.setIcon(s1);
179.
b6.setIcon(star);
180.
181.
}//end of if
182.
183.
184.
185.
if(e.getSource()==b7){
Icon s1=b7.getIcon();
if(b4.getIcon()==star){
186.
b4.setIcon(s1);
187.
b7.setIcon(star);
188.
} else if(b8.getIcon()==star){
189.
b8.setIcon(s1);
190.
b7.setIcon(star);
191.
192.
193.
}//end of if
194.
if(e.getSource()==b8){
195.
Icon s1=b8.getIcon();
196.
if(b7.getIcon()==star){
197.
b7.setIcon(s1);
198.
b8.setIcon(star);
199.
} else if(b5.getIcon()==star){
200.
b5.setIcon(s1);
201.
b8.setIcon(star);
202.
203.
else if(b9.getIcon()==star){
204.
b9.setIcon(s1);
205.
b8.setIcon(star);
206.
207.
208.
}//end of if
209.
210.
if(e.getSource()==b9){
211.
Icon s1=b9.getIcon();
212.
if(b8.getIcon()==star){
213.
b8.setIcon(s1);
214.
b9.setIcon(star);
215.
216.
} else if(b6.getIcon()==star){
b6.setIcon(s1);
217.
b9.setIcon(star);
218.
219.
}//end of if
220.
221.
if(e.getSource()==sample){
222.
Icon s1=sample.getIcon();
223.
if(s1==samicon3){
224.
sample.setIcon(samicon1);
225.
b1.setIcon(ic1);
226.
b2.setIcon(ic2);
227.
b3.setIcon(ic3);
228.
b4.setIcon(ic4);
229.
b5.setIcon(ic5);
230.
b6.setIcon(ic6);
231.
b7.setIcon(ic7);
232.
b8.setIcon(ic8);
233.
b9.setIcon(ic9);
234.
star=b9.getIcon();
235.
starB.setIcon(ic0);
236.
}//eof if
237.
else if(s1==samicon1){
238.
sample.setIcon(samicon2);
239.
b1.setIcon(ic11);
240.
b2.setIcon(ic12);
241.
b3.setIcon(ic13);
242.
b4.setIcon(ic14);
243.
b5.setIcon(ic15);
244.
b6.setIcon(ic16);
245.
b7.setIcon(ic17);
246.
b8.setIcon(ic18);
247.
b9.setIcon(ic19);
248.
star=b6.getIcon();
249.
starB.setIcon(ic10);
250.
}//eof else
251.
else{
252.
sample.setIcon(samicon3);
253.
b1.setIcon(ic21);
254.
b2.setIcon(ic22);
255.
b3.setIcon(ic23);
256.
b4.setIcon(ic24);
257.
b5.setIcon(ic25);
258.
b6.setIcon(ic26);
259.
b7.setIcon(ic27);
260.
b8.setIcon(ic28);
261.
b9.setIcon(ic29);
262.
star=b6.getIcon();
263.
starB.setIcon(ic20);
264.
}//eof else
265.
266.
267.
}//end of actionPerformed
268.
269.
270.
new picpuzzle2();
271.
}//end of main
272.
}//end of class
{10,3,5,7,11},{10,3,6,9,11},{10,4,5,6,11},
{10,7,8,9,11} };
9. int a1[][]={{10,1,2,3,11},{10,1,4,7,11},{10,1,5,9,11},{10,2,5,8,11},
10.
{10,3,5,7,11},{10,3,6,9,11},{10,4,5,6,11},{10,7,8,9,11} };
11.
12. boolean state,type,set;
13.
14. Icon ic1,ic2,icon,ic11,ic22;
15. Checkbox c1,c2;
16. JLabel l1,l2;
17. JButton b[]=new JButton[9];
18. JButton reset;
19.
20. public void showButton(){
21.
22. x=10; y=10;j=0;
23. for(i=0;i<=8;i++,x+=100,j++){
24. b[i]=new JButton();
25. if(j==3)
26. {j=0; y+=100; x=10;}
27. b[i].setBounds(x,y,100,100);
28. add(b[i]);
29. b[i].addActionListener(this);
30. }//eof for
31.
32. reset=new JButton("RESET");
33. reset.setBounds(100,350,100,50);
34. add(reset);
35. reset.addActionListener(this);
36.
37. }//eof showButton
38.
39. /*********************************************************/
40. public void check(int num1){
41. for(ii=0;ii<=7;ii++){
42.
43.
for(jj=1;jj<=3;jj++){
if(a[ii][jj]==num1){ a[ii][4]=11; }
44.
45.
}//eof for jj
46.
47. }//eof for ii
48. }//eof check
49. /**********************************************************/
50.
51. /*********************************************************/
52.
53. public void complogic(int num){
54.
55. for(i=0;i<=7;i++){
56.
for(j=1;j<=3;j++){
57.
58.
59. }
60.
61.
for(i=0;i<=7;i++){
set=true;
62.
if(a[i][4]==10){
63.
int count=0;
64.
for(j=1;j<=3;j++){
65.
//if 1
//for 2
if(b[(a[i][j]-1)].getIcon()!=null){ //if 2
66.
count++;
67.
68.
//eof if 2
else{ yesnull=a[i][j]; }
69.
70.
// for 1
//eof for 2
if(count==2){
//if 2
71.
b[yesnull-1].setIcon(ic2);
72.
this.check(yesnull); set=false;break;
73.
//eof if 2
74.
75.
else
76.
if(a[i][0]==10){
77.
78.
//eof if 1
for(j=1;j<=3;j++){
//for2
if(b[(a[i][j]-1)].getIcon()==null){ //if 1
79.
b[(a[i][j]-1)].setIcon(ic2);
80.
this.check(a[i][j]);
81.
set=false;
82.
break;
83.
//eof if1
84.
//eof for 2
85.
if(set==false)
86.
break;
87.
}//eof elseif
88.
89.
if(set==false)
90.
break;
102.
103.
104.
105.
c1.setBounds(120,80,100,40);
106.
c2.setBounds(120,150,100,40);
107.
add(c1); add(c2);
108.
c1.addItemListener(this);
109.
c2.addItemListener(this);
110.
111.
112.
state=true;type=true;set=true;
113.
ic1=new ImageIcon("ic1.jpg");
114.
ic2=new ImageIcon("ic2.jpg");
115.
ic11=new ImageIcon("ic11.jpg");
116.
ic22=new ImageIcon("ic22.jpg");
117.
118.
setLayout(null);
119.
setSize(330,450);
120.
setVisible(true);
121.
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
122.
}//eof constructor
123.
124.
/*************************************************************/
125.
126.
if(c1.getState())
127.
128.
type=false;
129.
130.
131.
else if(c2.getState())
132.
{ type=true;
133.
134.
remove(c1);remove(c2);
135.
repaint(0,0,330,450);
136.
showButton();
137.
}//eof itemstate
138.
/************************************************************/
139.
140.
141.
/********************************/
142.
if(type==true)//logicfriend
143.
144.
if(e.getSource()==reset){
145.
for(i=0;i<=8;i++){
146.
b[i].setIcon(null);
147.
}//eof for
148.
149.
else{
150.
151.
for(i=0;i<=8;i++){
if(e.getSource()==b[i]){
152.
153.
if(b[i].getIcon()==null){
154.
if(state==true){ icon=ic2;
155.
156.
b[i].setIcon(icon);
157.
158.
159.
}//eof for
160.
}//eof else
161.
}//eof logicfriend
162.
else if(type==false){
163.
// complogic
if(e.getSource()==reset){
164.
for(i=0;i<=8;i++){
165.
b[i].setIcon(null);
166.
}//eof for
167.
for(i=0;i<=7;i++)
168.
for(j=0;j<=4;j++)
169.
170.
171.
else{ //complogic
172.
for(i=0;i<=8;i++){
173.
if(e.getSource()==b[i]){
174.
if(b[i].getIcon()==null){
175.
b[i].setIcon(ic1);
176.
if(b[4].getIcon()==null){
177.
b[4].setIcon(ic2);
178.
this.check(5);
179.
} else{
180.
this.complogic(i);
181.
182.
183.
184.
185.
186.
}//eof for
}
}//eof complogic
187.
188.
for(i=0;i<=7;i++){
189.
190.
Icon icon1=b[(a[i][1]-1)].getIcon();
191.
Icon icon2=b[(a[i][2]-1)].getIcon();
192.
Icon icon3=b[(a[i][3]-1)].getIcon();
193.
if((icon1==icon2)&&(icon2==icon3)&&(icon1!=null)){
194.
if(icon1==ic1){
195.
b[(a[i][1]-1)].setIcon(ic11);
196.
b[(a[i][2]-1)].setIcon(ic11);
197.
b[(a[i][3]-1)].setIcon(ic11);
198.
199.
break;
200.
201.
else if(icon1==ic2){
202.
b[(a[i][1]-1)].setIcon(ic22);
203.
b[(a[i][2]-1)].setIcon(ic22);
204.
b[(a[i][3]-1)].setIcon(ic22);
205.
206.
break;
207.
208.
209.
}
}
210.
211.
212.
}//eof actionperformed
213.
/************************************************************/
214.
215.
216.
new TTT1();
217.
}//eof main
218.
}//eof class
In this project, there are given 10 questions to play. User can bookmark any question for the
reconsideration while going to result.
We are using here java array to store the questions, options and answers not database. You can
use collection framework or database in place of array.
1. /*Online Java Paper Test*/
2.
3. import java.awt.*;
4. import java.awt.event.*;
5. import javax.swing.*;
6.
7. class OnlineTest extends JFrame implements ActionListener
8. {
9.
JLabel l;
10.
11.
JButton b1,b2;
12.
ButtonGroup bg;
13.
int count=0,current=0,x=1,y=1,now=0;
14.
15.
OnlineTest(String s)
16.
17.
super(s);
18.
l=new JLabel();
19.
add(l);
20.
bg=new ButtonGroup();
21.
for(int i=0;i<5;i++)
22.
23.
jb[i]=new JRadioButton();
24.
add(jb[i]);
25.
bg.add(jb[i]);
26.
27.
b1=new JButton("Next");
28.
b2=new JButton("Bookmark");
29.
b1.addActionListener(this);
30.
b2.addActionListener(this);
31.
add(b1);add(b2);
32.
set();
33.
l.setBounds(30,40,450,20);
34.
jb[0].setBounds(50,80,100,20);
35.
jb[1].setBounds(50,110,100,20);
36.
jb[2].setBounds(50,140,100,20);
37.
jb[3].setBounds(50,170,100,20);
38.
b1.setBounds(100,240,100,30);
39.
b2.setBounds(270,240,100,30);
40.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
41.
setLayout(null);
42.
setLocation(250,100);
43.
setVisible(true);
44.
setSize(600,350);
45.
46.
47.
48.
if(e.getSource()==b1)
49.
50.
if(check())
51.
count=count+1;
52.
current++;
53.
set();
54.
if(current==9)
55.
56.
b1.setEnabled(false);
57.
b2.setText("Result");
58.
59.
60.
if(e.getActionCommand().equals("Bookmark"))
61.
62.
63.
bk.setBounds(480,20+30*x,100,30);
64.
add(bk);
65.
bk.addActionListener(this);
66.
m[x]=current;
67.
x++;
68.
current++;
69.
set();
70.
if(current==9)
71.
b2.setText("Result");
72.
setVisible(false);
73.
setVisible(true);
74.
75.
for(int i=0,y=1;i<x;i++,y++)
76.
77.
if(e.getActionCommand().equals("Bookmark"+y))
78.
79.
if(check())
80.
count=count+1;
81.
now=current;
82.
current=m[y];
83.
set();
84.
((JButton)e.getSource()).setEnabled(false);
85.
current=now;
86.
87.
88.
89.
if(e.getActionCommand().equals("Result"))
90.
91.
if(check())
92.
count=count+1;
93.
current++;
94.
//System.out.println("correct ans="+count);
95.
JOptionPane.showMessageDialog(this,"correct ans="+count);
96.
System.exit(0);
97.
98.
99.
void set()
100.
101.
jb[4].setSelected(true);
102.
if(current==0)
103.
104.
type?");
105.
jb[0].setText("int");jb[1].setText("Float");jb[2].setText("boolean")
;jb[3].setText("char");
106.
107.
if(current==1)
108.
109.
tically?");
110.
jb[0].setText("Swing");jb[1].setText("Applet");jb[2].setText("Obje
ct");jb[3].setText("ActionEvent");
111.
112.
if(current==2)
113.
114.
l.setText("Que3: Which package is directly available to our class
without importing it?");
115.
jb[0].setText("swing");jb[1].setText("applet");jb[2].setText("net")
;jb[3].setText("lang");
116.
117.
if(current==3)
118.
119.
120.
jb[0].setText("lang");jb[1].setText("Swing");jb[2].setText("Applet
");jb[3].setText("awt");
121.
122.
if(current==4)
123.
124.
125.
jb[0].setText("Utek");jb[1].setText("Aptech");jb[2].setText("SSS I
T");jb[3].setText("jtek");
126.
127.
if(current==5)
128.
129.
130.
jb[0].setText("class");jb[1].setText("int");jb[2].setText("get");jb[3
].setText("if");
131.
132.
if(current==6)
133.
134.
135.
jb[0].setText("Swing");jb[1].setText("Actionperformed");jb[2].set
Text("ActionEvent");
136.
jb[3].setText("Button");
137.
138.
if(current==7)
139.
140.
ect class?");
141.
quals");
jb[0].setText("toString");jb[1].setText("finalize");jb[2].setText("e
142.
jb[3].setText("getDocumentBase");
143.
144.
if(current==8)
145.
146.
147.
jb[0].setText("init");jb[1].setText("main");jb[2].setText("start");jb
[3].setText("destroy");
148.
149.
if(current==9)
150.
151.
ent?");
152.
onGroup");
jb[0].setText("JButton");jb[1].setText("JList");jb[2].setText("JButt
153.
jb[3].setText("JTextArea");
154.
155.
l.setBounds(30,40,450,20);
156.
for(int i=0,j=0;i<=90;i+=30,j++)
157.
jb[j].setBounds(50,80+i,200,20);
158.
159.
boolean check()
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
if(current==0)
return(jb[1].isSelected());
if(current==1)
return(jb[2].isSelected());
if(current==2)
return(jb[3].isSelected());
if(current==3)
return(jb[0].isSelected());
if(current==4)
return(jb[2].isSelected());
if(current==5)
return(jb[2].isSelected());
if(current==6)
return(jb[1].isSelected());
if(current==7)
return(jb[3].isSelected());
if(current==8)
return(jb[1].isSelected());
if(current==9)
180.
return(jb[2].isSelected());
181.
return false;
182.
183.
184.
185.
186.
187.
}
}
BorderLayout (LayoutManagers):
LayoutManagers:
The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout
managers. There are following classes that represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south,
east, west and center. Each region (area) may contain one component only. It is the
default layout of frame or window. The BorderLayout provides five constants for
each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
JBorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border {
5. JFrame f;
6. Border(){
7.
8.
f=new JFrame();
9.
10.
11.
12.
13.
14.
15.
f.add(b1,BorderLayout.NORTH);
16.
f.add(b2,BorderLayout.SOUTH);
17.
f.add(b3,BorderLayout.EAST);
18.
f.add(b4,BorderLayout.WEST);
19.
f.add(b5,BorderLayout.CENTER);
20.
21.
f.setSize(300,300);
22.
f.setVisible(true);
23.}
24.public static void main(String[] args) {
25.
new Border();
26.}
27.}
GridLayout
The GridLayout is used to arrange the components in rectangular grid. One
component is dispalyed in each rectangle.
Constructors of GridLayout class:
1. GridLayout(): creates a grid layout with one column per component in a
row.
2. GridLayout(int rows, int columns): creates a grid layout with the given
rows and columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid
layout with the given rows and columns alongwith given horizontal and
vertical gaps.
Example of GridLayout class:
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyGridLayout{
5. JFrame f;
6. MyGridLayout(){
7.
8.
f=new JFrame();
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
20.
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
21.
22.
f.setLayout(new GridLayout(3,3));
23.
24.
25.
f.setSize(300,300);
26.
f.setVisible(true);
27.}
28.public static void main(String[] args) {
29.
new MyGridLayout();
30.}
31.}
FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a
flow). It is the default layout of applet or panel.
Fields of FlowLayout class:
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class:
1. FlowLayout(): creates a flow layout with centered alignment and a default 5
unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and
a default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the
given alignment and the given horizontal and vertical gap.
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyFlowLayout{
5. JFrame f;
6. MyFlowLayout(){
7.
f=new JFrame();
8.
9.
10.
11.
12.
13.
14.
15.
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
16.
17.
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
18.
19.
20.
f.setSize(300,300);
21.
f.setVisible(true);
22.}
23.public static void main(String[] args) {
24.
new MyFlowLayout();
25.}
26.}
download this example
Next TopicBoxLayout
BoxLayout class:
The BoxLayout is used to arrange the components either vertically or horizontally.
For this purpose, BoxLayout provides four constants. They are as follows:
Note: BoxLayout class is found in javax.swing package.
Fields of BoxLayout class:
1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS
Constructor of BoxLayout class:
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample1 extends Frame {
5.
Button buttons[];
6.
7.
public BoxLayoutExample1 () {
8.
9.
10.
11.
12.
add (buttons[i]);
13.
14.
15.setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
16.setSize(400,400);
17.setVisible(true);
18.}
19.
20.public static void main(String args[]){
21.BoxLayoutExample1 b=new BoxLayoutExample1();
22.}
23.}
download this example
Example of BoxLayout class with X-AXIS:
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample2 extends Frame {
5.
Button buttons[];
6.
7.
8.
public BoxLayoutExample2() {
buttons = new Button [5];
9.
10.
11.
12.
13.
add (buttons[i]);
}
14.
15.setLayout (new BoxLayout(this, BoxLayout.X_AXIS));
16.setSize(400,400);
17.setVisible(true);
18.}
19.
20.public static void main(String args[]){
21.BoxLayoutExample2 b=new BoxLayoutExample2();
22.}
23.}
download this example
Next TopicCardLayout
prev
next>>
CardLayout class
The CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is
known as CardLayout.
Constructors of CardLayout class:
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.
public void next(Container parent): is used to flip to the next card of the
given container.
public void first(Container parent): is used to flip to the first card of the
given container.
public void last(Container parent): is used to flip to the last card of the
given container.
1. import java.awt.*;
2. import java.awt.event.*;
3.
4. import javax.swing.*;
5.
6. public class CardLayoutExample extends JFrame implements ActionListener{
7. CardLayout card;
8. JButton b1,b2,b3;
9. Container c;
10.
CardLayoutExample(){
11.
12.
c=getContentPane();
13.
card=new CardLayout(40,30);
c.setLayout(card);
16.
17.
b1=new JButton("Apple");
18.
b2=new JButton("Boy");
19.
b3=new JButton("Cat");
20.
b1.addActionListener(this);
21.
b2.addActionListener(this);
22.
b3.addActionListener(this);
23.
24.
25.
c.add("a",b1);c.add("b",b2);c.add("c",b3);
26.
27.
28.
card.next(c);
29.
30.
31.
32.
33.
cl.setSize(400,400);
34.
cl.setVisible(true);
35.
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
36.
37.}
Applet
Applet is a special type of program that is embedded in the webpage to generate
the dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
Secured
Drawback of Applet
Do You Know ?
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends
Container which is the subclass of Component.
Lifecycle of an Applet:
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
6. </html>
Live Demo:
1. public abstract void drawString(String str, int x, int y): is used to draw
the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a
rectangle with the specifed width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used
to fill rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is
used to draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used
to fill oval with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to
draw line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used to fill a circular or elliptical arc.
10.public abstract void setColor(Color c): is used to set the graphics current
color to the specified color.
11.public abstract void setFont(Font font): is used to set the graphics
current font to the specified font.
Example of Graphics in applet:
1. import java.applet.Applet;
2. import java.awt.*;
3.
4. public class GraphicsDemo extends Applet{
5.
the image.
Syntax of drawImage() method:
1. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
How to get the object of Image:
The java.applet.Applet class provides getImage() method that returns the object of
Image. Syntax:
1. public Image getImage(URL u, String image){}
Other required methods of Applet class to display image:
1. public URL getDocumentBase(): is used to return the URL of the
document in which applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.
1. import java.awt.*;
2. import java.applet.*;
3.
4.
5. public class DisplayImage extends Applet {
6.
7.
Image picture;
8.
9.
10.
11. }
12.
13. public void paint(Graphics g) {
14.
15. }
16.
17. }
In the above example, drawImage() method of Graphics class is used to display the
image. The 4th argument of drawImage() method of is ImageObserver object. The
Component class implements ImageObserver interface. So current class object
would also be treated as ImageObserver because Applet class indirectly extends
the Component class.
myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to
be moved.
4.
5.
Image picture;
6.
7.
8.
9.
picture =getImage(getDocumentBase(),"bike_1.gif");
}
10.
11. public void paint(Graphics g) {
12.
for(int i=0;i<500;i++){
13.
14.
15.
16.
try{Thread.sleep(100);}catch(Exception e){}
}
17. }
18.}
In the above example, drawImage() method of Graphics class is used to display the
image. The 4th argument of drawImage() method of is ImageObserver object. The
Component class implements ImageObserver interface. So current class object
would also be treated as ImageObserver because Applet class indirectly extends
the Component class.
myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also.
Let's see the simple example of event handling in applet that prints a message by
click on the button.
Example of EventHandling in applet:
1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class EventApplet extends Applet implements ActionListener{
5. Button b;
6. TextField tf;
7.
8. public void init(){
9. tf=new TextField();
10.tf.setBounds(30,40,150,20);
11.
12.b=new Button("Click");
13.b.setBounds(80,150,60,50);
14.
15.add(b);add(tf);
16.b.addActionListener(this);
17.
18.setLayout(null);
19.}
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24.}
In the above example, we have created all the controls in init() method because it is
invoked only once.
myapplet.html
1. <html>
2. <body>
3. <applet code="EventApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
JApplet class in Applet
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of
swing. The JApplet class extends the Applet class.
Example of EventHandling in JApplet:
1. import java.applet.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class EventJApplet extends JApplet implements ActionListener{
5. JButton b;
6. JTextField tf;
7. public void init(){
8.
9. tf=new JTextField();
10.tf.setBounds(30,40,150,20);
11.
12.b=new JButton("Click");
13.b.setBounds(80,150,70,40);
14.
15.add(b);add(tf);
16.b.addActionListener(this);
17.
18.setLayout(null);
19.}
20.
21.public void actionPerformed(ActionEvent e){
22.tf.setText("Welcome");
23.}
24.}
In the above example, we have created all the controls in init() method because it is
invoked only once.
myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.
Example of Painting in Applet:
1. import java.awt.*;
2. import java.awt.event.*;
3. import java.applet.*;
4. public class MouseDrag extends Applet implements MouseMotionListener{
5.
6. public void init(){
7. addMouseMotionListener(this);
8. setBackground(Color.red);
9. }
10.
11.public void mouseDragged(MouseEvent me){
12.Graphics g=getGraphics();
13.g.setColor(Color.white);
14.g.fillOval(me.getX(),me.getY(),5,5);
15.}
16.public void mouseMoved(MouseEvent me){}
17.
18.}
In the above example, getX() and getY() method of MouseEvent is used to get the
current x-axis and y-axis. The getGraphics() method of Component class returns the
object of Graphics.
myapplet.html
1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Digital clock in Applet
Digital clock can be created by using the Calendar and SimpleDateFormat class.
Let's see the simple example:
Example of Digital clock in Applet:
1. import java.applet.*;
2. import java.awt.*;
3. import java.util.*;
4. import java.text.*;
5.
6. public class DigitalClock extends Applet implements Runnable {
7.
8.
Thread t = null;
9.
10.
11.
12.
13.
14.
setBackground( Color.green);
}
15.
16.
17.
18.
t.start();
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
repaint();
37.
38.
39.
40.
catch (Exception e) { }
41.
42.
43.
44. public void paint( Graphics g ) {
45.
g.setColor( Color.blue );
46.
47.
48.}
In the above example, getX() and getY() method of MouseEvent is used to get the
current x-axis and y-axis. The getGraphics() method of Component class returns the
object of Graphics.
myapplet.html
1. <html>
2. <body>
3. <applet code="DigitalClock.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Analog clock in Applet
Analog clock can be created by using the Math class. Let's see the simple example:
Example of Analog clock in Applet:
1. import java.applet.*;
2. import java.awt.*;
3. import java.util.*;
4. import java.text.*;
5.
6. public class MyClock extends Applet implements Runnable {
7.
8.
9.
Thread t = null;
10.
boolean threadSuspended;
11.
12.
13.
14.
15.
width = getSize().width;
16.
height = getSize().height;
17.
setBackground( Color.black );
18.
19.
20.
21.
if ( t == null ) {
22.
23.
t.setPriority( Thread.MIN_PRIORITY );
24.
threadSuspended = false;
25.
t.start();
26.
27.
else {
28.
if ( threadSuspended ) {
29.
threadSuspended = false;
30.
synchronized( this ) {
31.
notify();
32.
33.
34.
35.
}
}
36.
37.
38.
39.
threadSuspended = true;
}
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
SimpleDateFormat formatter
52.
53.
54.
55.
56.
57.
if ( threadSuspended ) {
58.
synchronized( this ) {
59.
while ( threadSuspended ) {
60.
wait();
61.
62.
63.
64.
repaint();
65.
66.
67.
68.
catch (Exception e) { }
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
angle += 2*Math.PI/3;
83.
84.
85.
angle += 2*Math.PI/3;
86.
87.
88.
89.
90.
91.
92.
93.
94.
g.setColor( Color.gray );
95.
96.
97.
98.
g.setColor( Color.white );
99.
100.
101.
}
}
myapplet.html
1. <html>
2. <body>
3. <applet code="MyClock.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose,
Applet class provides a method named getParameter(). Syntax:
1. public String getParameter(String parameterName)
Example of using parameter in Applet:
1. import java.applet.Applet;
2. import java.awt.Graphics;
3.
1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class ContextApplet extends Applet implements ActionListener{
5. Button b;
6.
7. public void init(){
8. b=new Button("Click");
9. b.setBounds(50,50,60,50);
10.
11.add(b);
12.b.addActionListener(this);
13.}
14.
15.public void actionPerformed(ActionEvent e){
16.
17.AppletContext ctx=getAppletContext();
18.Applet a=ctx.getApplet("app2");
19.a.setBackground(Color.yellow);
20.}
21.}
myapplet.html
1. <html>
2. <body>
3. <applet code="ContextApplet.class" width="150" height="150" name="app
1">
4. </applet>
5.
6. <applet code="First.class" width="150" height="150" name="app2">
7. </applet>
8. </body>
9. </html>
Applet Communication
java.applet.AppletContext class provides the facility of communication between
applets. We provide the name of applet through the HTML file. It provides
getApplet() method that returns the object of Applet. Syntax:
1. public Applet getApplet(String name){}
Example of Applet Communication
1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class ContextApplet extends Applet implements ActionListener{
5. Button b;
6.
7. public void init(){
8. b=new Button("Click");
9. b.setBounds(50,50,60,50);
10.
11.add(b);
12.b.addActionListener(this);
13.}
14.
15.public void actionPerformed(ActionEvent e){
16.
17.AppletContext ctx=getAppletContext();
18.Applet a=ctx.getApplet("app2");
19.a.setBackground(Color.yellow);
20.}
21.}
myapplet.html
1. <html>
2. <body>
3. <applet code="ContextApplet.class" width="150" height="150" name="app
1">
4. </applet>
5.
6. <applet code="First.class" width="150" height="150" name="app2">
7. </applet>
8. </body>
9. </html>
Java Reflection API
Reflection is the process of examining or modifying the runtime behaviour of a class at runtime.
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:
Debugger
Do You Know ?
java.lang.Class class
The java.lang.Class class performs mainly two tasks:
Description
checks if it is
interface.
5) public boolean isArray()
checks if it is array.
checks if it is
primitive.
There are 3 ways to get the instance of Class class. They are as follows:
It should be used if you know the fully qualified name of class.This cannot be
used for primitive types.
1. class Simple{}
2.
3. class Test{
4.
5.
Class c=Class.forName("Simple");
6.
System.out.println(c.getName());
7.
8. }
Output:Simple
It returns the instance of Class class. It should be used if you know the type. Moreover, it can be
used with primitives.
1. class Simple{}
2.
3. class Test{
4.
5.
Class c=obj.getClass();
6.
System.out.println(c.getName());
7.
8.
9.
10.
11.
12.
t.printName(s);
13. }
14.}
15.
Output:Simple
If a type is available but there is no instance then it is possible to obtain a Class by appending
".class" to the name of the type.It can be used for primitive data type also.
1. class Test{
2.
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
Test
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.
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
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.
3. }
4.
5. class Test{
6.
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
The javap command disassembles a class file. The javap command displays information about
the fields,constructors and methods present in a class file.
Syntax to use javap tool
public java.lang.Object();
4.
5.
6.
7.
8.
9.
Now let's use the javap tool to disassemble the class file.
1. javap Simple
Output:
1. Compiled from ".java"
2. class Simple {
3.
Simple();
4.
5. }
javap -c command
You can use the javap -c command to see disassembled code. The code that reflects the java
bytecode.
1. javap -c Simple
Output:
1. Compiled from ".java"
2. class Simple {
3.
Simple();
4.
Code:
5.
0: aload_0
6.
1: invokespecial #1
7.
4: return
// Method java/lang/Object."<init>":()V
8.
9.
10.
11.
Code:
0: getstatic
eam;
12.
13.
3: ldc
#2
#3
// Field java/lang/System.out:Ljava/io/PrintStr
// String hello java
5: invokevirtual #4
(Ljava/lang/String;)V
14.
// Method java/io/PrintStream.println:
8: return
15.}
Description
-help
-l
-c
-s
-sysinfo
-constants
-version
Next Topiccreating-javap-tool
Creating a program that works as javap tool
Following methods of java.lang.Class class can be used to display the metadata of a class.
Method
Description
public Field[]
getDeclaredFields()throws
SecurityException
public Constructor[]
getDeclaredConstructors()throws
SecurityException
public Method[]
getDeclaredMethods()throws
SecurityException
6.
7.
System.out.println("Fields........");
8.
Field f[]=c.getDeclaredFields();
9.
for(int i=0;i<f.length;i++)
10.
11.
System.out.println(f[i]);
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.
Output:
As you know well that appletviewer tool creates a frame and displays the output of applet in the
frame.You can also create your frame and display the applet output.
Example that works like appletviewer tool
Let's see the simple example that works like appletviewer tool. This example displays applet on
the frame.
1. import java.applet.Applet;
2. import java.awt.Frame;
3. import java.awt.Graphics;
4.
5. public class MyViewer extends Frame{
6.
7.
8.
9.
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.
9. }
Output:
You can call the private method from outside the class by changing the runtime behaviour of the
class.
By the help of java.lang.Class class and java.lang.reflect.Method class, we can call private
method from any other class.
Let's see the simple example to call private method from another class.
File: A.java
1. public class A {
2.
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.
8.
m.setAccessible(true);
9.
m.invoke(o, null);
10.}
11.}
Output:hello java
Let's see the example to call parameterized private method from another class
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
Collection Framework provides an architecture to store and manipulate the group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, deletion etc.
can be performed by Java Collection Framework.
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>
is optional.
Collection framework
Collection framework represents a unified architecture for storing and manipulating group of
object. It has:
1. Interfaces and its implementations i.e. classes
2. Algorithm
Do You Know ?
collection framework ?
How can we sort the elements of an object. What is the difference between
Comparable and Comparator interfaces ?
Let us see the hierarchy of collection framework.The java.util package contains all the classes
and interfaces for Collection framework.
There are many methods declared in the Collection interface. They are as follows:
Method
Description
public boolean
remove(object element)
public boolean
removeAll(Collection c)
public boolean
retainAll(Collection c)
public boolean
is used to search an element.
contains(object element)
public boolean
containsAll(collection c)
returns an iterator.
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
1. public boolean hasNext() it returns true if iterator has more elements.
2. public object next() it returns the element and moves the cursor pointer to
the next element.
3. public void remove() it removes the last elements returned by the iterator.
It is rarely used.
ArrayList class
LinkedList class
ListIterator interface
HashSet class
LinkedHashSet class
TreeSet class
PriorityQueue class
Map interface
HashMap class
LinkedHashMap class
TreeMap class
Hashtable class
Sorting
Comparable interface
Comparator interface
uses a dynamic array for storing the elements.It extends AbstractList class
and implements List interface.
not synchronized.
Example of ArrayList:
1. import java.util.*;
2. class Simple{
3.
4.
5.
6.
al.add("Ravi");
7.
al.add("Vijay");
8.
al.add("Ravi");
9.
al.add("Ajay");
10.
11. Iterator itr=al.iterator();
12. while(itr.hasNext()){
13.
System.out.println(itr.next());
14. }
15. }
16.}
Output:Ravi
Vijay
Ravi
Ajay
4.
5.
6.
al.add("Ravi");
7.
al.add("Vijay");
8.
al.add("Ravi");
9.
al.add("Ajay");
10.
System.out.println(obj);
13. }
14.}
Output:Ravi
Vijay
Ravi
Ajay
int rollno;
3.
String name;
4.
int age;
5.
6.
this.rollno=rollno;
7.
this.name=name;
8.
this.age=age;
9.
10.}
1. import java.util.*;
2. class Simple{
3.
4.
5.
6.
7.
8.
9.
10. al.add(s1);
11. al.add(s2);
12. al.add(s3);
13.
14. Iterator itr=al.iterator();
15. while(itr.hasNext()){
16.
Student st=(Student)itr.next();
17.
18. }
19. }
20.}
Output:101 Sonoo 23
102 Ravi 21
103 Hanumat 25
4.
5.
6.
al.add("Ravi");
7.
al.add("Vijay");
8.
al.add("Ajay");
9.
10. ArrayList al2=new ArrayList();
11. al2.add("Sonoo");
12. al2.add("Hanumat");
13.
14. al.addAll(al2);
15.
16. Iterator itr=al.iterator();
17. while(itr.hasNext()){
18.
System.out.println(itr.next());
19. }
20. }
21.}
Output:Ravi
Vijay
Ajay
Sonoo
Hanumat
4.
5.
6.
al.add("Ravi");
7.
al.add("Vijay");
8.
al.add("Ajay");
9.
10. ArrayList al2=new ArrayList();
11. al2.add("Ravi");
12. al2.add("Hanumat");
13.
14. al.removeAll(al2);
15.
16. System.out.println("iterating the elements after removing the elements of al
2...");
17. Iterator itr=al.iterator();
18. while(itr.hasNext()){
19.
System.out.println(itr.next());
20. }
21.
22. }
23.}
Output:iterating the elements after removing the elements of al2...
Vijay
Ajay
5.
6.
al.add("Ravi");
7.
al.add("Vijay");
8.
al.add("Ajay");
9.
10. ArrayList al2=new ArrayList();
11. al2.add("Ravi");
12. al2.add("Hanumat");
13.
14. al.retainAll(al2);
15.
16. System.out.println("iterating the elements after retaining the elements of al
2...");
17. Iterator itr=al.iterator();
18. while(itr.hasNext()){
19.
System.out.println(itr.next());
20. }
21. }
22.}
Output:iterating the elements after retaining the elements of al2...
Ravi
LinkedList class:
uses doubly linked list to store the elements. It extends the AbstractList class
and implements List and Deque interfaces.
not synchronized.
No random access.
Example of LinkedList:
1. import java.util.*;
2. class Simple{
3.
4.
5.
6.
al.add("Ravi");
7.
al.add("Vijay");
8.
al.add("Ravi");
9.
al.add("Ajay");
10.
11. Iterator itr=al.iterator();
12. while(itr.hasNext()){
13.
System.out.println(itr.next());
14. }
15. }
16.}
Output:Ravi
Vijay
Ravi
Ajay
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.
Commonly used mehtods of List Interface:
1. public void add(int index,Object element);
2. public boolean addAll(int index,Collection c);
3. public object get(int Index position);
4. public object set(int index,Object element);
5. public object remove(int index);
6. public ListIterator listIterator();
7. public ListIterator listIterator(int i);
ListIterator Interface:
ListIterator Interface is used to traverse the element in backward and forward
direction.
Commonly used mehtods of ListIterator Interface:
1. public boolean hasNext();
2. public Object next();
3. public boolean hasPrevious();
4. public Object previous();
24. }
25.}
26.}
Output:element at 2nd position: Vijay
traversing elements in forward direction...
Amit
Sachin
Vijay
Kumar
traversing elements in backward direction...
Kumar
Vijay
Sachin
Amit
1.
2.
al.add("Ajay");
3.
4.
Iterator itr=al.iterator();
5.
while(itr.hasNext()){
6.
System.out.println(itr.next());
7.
8.
9. }
Output:Ajay
Vijay
Ravi
LinkedHashSet class:
contains unique elements only like HashSet. It extends HashSet class and
implements Set interface.
4.
5.
6.
al.add("Ravi");
7.
al.add("Vijay");
8.
al.add("Ravi");
9.
al.add("Ajay");
10.
11. Iterator itr=al.iterator();
12. while(itr.hasNext()){
13.
System.out.println(itr.next());
14. }
15. }
16.}
Output:Ravi
Vijay
Ajay
TreeSet class:
contains unique elements only like HashSet. The TreeSet class implements
NavigableSet interface that extends the SortedSet interface.
4.
5.
6.
al.add("Ravi");
7.
al.add("Vijay");
8.
al.add("Ravi");
9.
al.add("Ajay");
10.
11. Iterator itr=al.iterator();
12. while(itr.hasNext()){
13.
System.out.println(itr.next());
14. }
15. }
16.}
Output:Ajay
Ravi
Vijay
Queue Interface:
The Queue interface basically orders the element in FIFO(First In First Out)manner.
Methods of Queue Interface :
1. public boolean add(object);
2. public boolean offer(object);
3. public remove();
4. public poll();
5. public element();
6. public peek();
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{
27.System.out.println(itr2.next());
28.}
29.
30.}
31.}
Output:head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay
ERROR
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.
Commonly used methods of Map interface:
1. public Object put(object key,Object value): is used to insert an entry in
this map.
2. public void putAll(Map map):is used to insert the specifed map in this
map.
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
Entry
Entry is the subinterface of Map.So we will access it by Map.Entry name.It provides
methods to get key and value.
Methods of Entry interface:
1. public Object getKey(): is used to obtain key.
2. public Object getValue():is used to obtain value.
Next TopicHashMap Class In Collection Framework
HashMap class:
It maintains no order.
4.
5.
6.
7.
hm.put(100,"Amit");
8.
hm.put(101,"Vijay");
9.
hm.put(102,"Rahul");
10.
11. Set set=hm.entrySet();
12. Iterator itr=set.iterator();
13.
14. while(itr.hasNext()){
15.
Map.Entry m=(Map.Entry)itr.next();
16.
System.out.println(m.getKey()+" "+m.getValue());
17. }
18. }
19.}
Output:102 Rahul
100 Amit
101 Vijay
4.
5.
6.
7.
hm.put(100,"Amit");
8.
hm.put(101,"Vijay");
9.
hm.put(102,"Rahul");
10.
11. Set set=hm.entrySet();
12. Iterator itr=set.iterator();
13.
14. while(itr.hasNext()){
15.
Map.Entry m=(Map.Entry)itr.next();
16.
System.out.println(m.getKey()+" "+m.getValue());
17. }
18. }
19.}
Output:100 Amit
101 Vijay
103 Rahul
TreeMap class
It cannot have null key but can have multiple null values.
4.
5.
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.}
Output:100
101
102
103
Amit
Vijay
Ravi
Rahul
It is synchronized.
Example of Hashtable:
1. import java.util.*;
2. class Simple{
3.
4.
5.
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.}
Output:103
102
101
100
Rahul
Ravi
Vijay
Amit
Hashtable is synchronized.
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.
Method of Collections class for sorting List elements
public void sort(List list): is used to sort the elements of List.List elements must
be of Comparable type.
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.
Example of Sorting the elements of List that contains string objects
1. import java.util.*;
2. class Simple12{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. al.add("Viru");
7. al.add("Saurav");
8. al.add("Mukesh");
9. al.add("Tahir");
10.
11.Collections.sort(al);
12.Iterator itr=al.iterator();
13.while(itr.hasNext()){
14.System.out.println(itr.next());
15. }
16.}
17.}
Output:Mukesh
Saurav
Tahir
Viru
16.}
17.}
Output:101
201
230
Example of Sorting the elements of List that contains user-defined class objects on
age basis
Student.java
1. class Student implements Comparable{
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.
11.public int compareTo(Object obj){
12.Student st=(Student)obj;
13.if(age==st.age)
14.return 0;
15.else if(age>st.age)
16.return 1;
17.else
18.return -1;
19.}
20.
21.}
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
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.
Syntax of compare method
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.
Method of Collections class for sorting List elements
public void sort(List list,Comparator c): is used to sort the elements of List by the given
comparator.
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)
10.return 1;
11.else
12.return -1;
13.}
14.}
NameComparator.java
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.*;
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();
27.System.out.println(st.rollno+" "+st.name+" "+st.age);
28.}
29.
30.
31.}
32.}
Output:Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27
The properties object contains key and value pair both as a string. It is the subclass of
Hashtable.
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.
Advantage of properties file
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.
Methods of Properties class
Description
To get information from the properties file, create the properties file first.
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.
6.
7.
8.
p.load(reader);
9.
10.
System.out.println(p.getProperty("user"));
11.
System.out.println(p.getProperty("password"));
12.}
13.}
Output:system
oracle
Now if you change the value of the properties file, you don't need to compile the java class again.
That means no maintenance problem.
By System.getProperties() method we can get all the properties of system. Let's create the class
that gets information from the system properties.
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.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=new Properties();
7. p.setProperty("name","Sonoo Jaiswal");
8. p.setProperty("email","sonoojaiswal@javatpoint.com");
9.
10.p.store(new FileWriter("info.properties"),"Javatpoint Properties Example");
11.
12.}
13.}
ERROR
JDBC Tutorial
1. JDBC
2. Why use JDBC?
3. What is API?
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?
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
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.
9) Statement interface
In this JDBC tutorial, we will learn what is Statement interface and what are its
methods.
Advantages:
easy to use.
Disadvantages:
Performance degraded because JDBC method call is converted into the ODBC
funcion calls.
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:
Disadvantage:
Advantage:
Disadvantages:
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:
Disadvantage:
Creating connection
Creating statement
Executing queries
Closing connection
5. }
To connect java application with the Oracle database ojdbc14.jar file is required to
be loaded.
download the jar file ojdbc14.jar
Two ways to load the jar file:
1. paste the ojdbc14.jar file in jre/lib/ext folder
2. set classpath
1) paste the ojdbc14.jar file in JRE/lib/ext folder:
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file
here.
2) set classpath:
There are two ways to set the classpath:
temporary
permament
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 is
jdbc: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. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
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.}
download this example
The above example will fetch all the records of emp table.
temporary
permament
There are two ways to connect java application with the access database.
1. Without DSN (Data Source Name)
2. With DSN
Java is mostly used with Oracle, mysql, or DB2 database. So you can learn this topic
only for knowledge.
try{
String database="student.mdb";//Here database exists in the current direct
ory
6.
7.
8.
9.
10.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
11.
Connection c=DriverManager.getConnection(url);
12.
Statement st=c.createStatement();
13.
14.
15.
16.
17.
while(rs.next()){
System.out.println(rs.getString(1));
}
18.
19.}catch(Exception ee){System.out.println(ee);}
20.
21.}}
download this example
Example to Connect Java Application with access with DSN
Connectivity with type1 driver is not considered good. To connect java application
with type1 driver, create DSN first, here we are assuming your dsn name is mydsn.
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.
10.
11.
while(rs.next()){
12.
13.
System.out.println(rs.getString(1));
}
14.
15.}catch(Exception ee){System.out.println(ee);}
16.
17.}}
Next TopicDriverManager Class
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().
Commonly used methods of DriverManager class:
1) public static void registerDriver(Driver
driver):
commit/rollback permanent.
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.
Next TopicStatement Interface
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.
Commonly used methods of Statement interface:
Lets see the simple example of Statement interface to insert, update and delete the record.
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:1
521:xe","system","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=1
0000 where id=33");
11.int result=stmt.executeUpdate("delete from emp765 where id=33");
12.
13.System.out.println(result+" records affected");
14.con.close();
15.}}
Next TopicResultSet Interface
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. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
2.
ResultSet.CONCUR_UPDATABLE);
object.
5) public boolean
absolute(int row):
6) public boolean
relative(int row):
8) public int getInt(String is used to return the data of specified column name of
columnName):
the current row as int.
9) public String
getString(int
columnIndex):
Lets see the simple example of ResultSet interface to retrieve the data of 3rd row.
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:1
521:xe","system","oracle");
7. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Re
sultSet.CONCUR_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.}}
<<prev
Next TopicPreparedStatement Interface
PreparedStatement:
The PreparedStatement interface is a subinterface of Statement. It is used to
exeucte parameterized query.
Why use PreparedStatement?
The performance of the application will be faster if you use PreparedStatement
interface because query is compiled only once.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10.PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)"
);
11.stmt.setInt(1,101);//1 specifies the first parameter in the query
12.stmt.setInt(2,"Ratan");
13.
14.int i=stmt.executeUpdate();
15.System.out.println(i+" records inserted");
16.
17.con.close();
18.
19.}catch(Exception e){ System.out.println(e);}
20.
21.}
22.}
download this example
Example of PreparedStatement interface that updates the record:
1. import java.sql.*;
2. class UpdatePrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10.PreparedStatement stmt=con.prepareStatement("update emp set name=? w
here id=?");
11.stmt.setString(1,"Sonoo");//1 specifies the first parameter in the query i.e. na
me
12.stmt.setInt(2,101);
13.
14.int i=stmt.executeUpdate();
15.System.out.println(i+" records updated");
16.
17.con.close();
18.
19.}catch(Exception e){ System.out.println(e);}
20.
21.}
22.}
download this example
Example of PreparedStatement interface that deletes the record:
1. import java.sql.*;
2. class DeletePrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10.PreparedStatement stmt=con.prepareStatement("delete from emp where id=
?");
11.stmt.setInt(1,101);
12.
13.int i=stmt.executeUpdate();
14.System.out.println(i+" records deleted");
15.
16.con.close();
17.
18.}catch(Exception e){ System.out.println(e);}
19.
20.}
21.}
download this example
Example of PreparedStatement interface that retrieve the records of a
table:
1. import java.sql.*;
2. class RetrievePrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10.PreparedStatement stmt=con.prepareStatement("select * from emp");
11.ResultSet rs=stmt.executeQuery();
12.while(rs.next()){
13.System.out.println(rs.getInt(1)+" "+rs.getString(2));
14.}
15.
16.con.close();
17.
18.}catch(Exception e){ System.out.println(e);}
19.
20.}
21.}
download this example
Next TopicResultSetMetaData Interface
<<prev
next>>
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.
Commonly used methods of DatabaseMetaData interface
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10.DatabaseMetaData dbmd=con.getMetaData();
11.
12.System.out.println("Driver Name: "+dbmd.getDriverName());
13.System.out.println("Driver Version: "+dbmd.getDriverVersion());
14.System.out.println("UserName: "+dbmd.getUserName());
15.System.out.println("Database Product Name: "+dbmd.getDatabaseProductNa
me());
16.System.out.println("Database Product Version: "+dbmd.getDatabaseProductV
ersion());
17.
18.con.close();
19.
20.}catch(Exception e){ System.out.println(e);}
21.
22.}
23.}
Output:Driver Name: Oracle JDBC Driver
Driver Version: 10.2.0.1.0XE
Database Product Name: Oracle
Database Product Version: Oracle Database 10g Express Edition
Release 10.2.0.1.0 -Production
22.}
23.}
download this example
Next TopicStoring Image In Oracle Database
Example to store image in Oracle database
You can store images in the database in java by the help of PreparedStatement interface.
The setBinaryStream() method of PreparedStatement is used to set Binary information into the
parameterIndex.
Signature of setBinaryStream method
For storing image into the database, BLOB (Binary Large Object) datatype is used in the table.
For example:
1. CREATE TABLE "IMGTABLE"
2.
3.
4.
"NAME" VARCHAR2(4000),
"PHOTO" BLOB
)
5. /
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.*;
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.
download this example
Next TopicRetrieving image From Oracle Database
Example to retrieve image from Oracle database
By the help of PreparedStatement we can retrieve and store the image in the database.
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.
Signature of getBlob() method of PreparedStatement
1. public Blob getBlob()throws SQLException
Signature of getBytes() method of Blob interface
1. public byte[] getBytes(long pos, int length)throws SQLException
"NAME" VARCHAR2(4000),
"PHOTO" BLOB
)
5. /
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.
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.}
"ID" NUMBER,
"NAME" CLOB
)
5. /
1. import java.io.*;
2. import java.sql.*;
3.
4. public class StoreFile {
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(
12."insert into filetable values(?,?)");
13.
14.File f=new File("d:\\myfile.txt");
15.FileReader fr=new FileReader(f);
16.
17.ps.setInt(1,101);
18.ps.setCharacterStream(2,fr,(int)f.length());
19.int i=ps.executeUpdate();
20.System.out.println(i+" records affected");
21.
22.con.close();
23.
24.}catch (Exception e) {e.printStackTrace();}
25.}
26.}
download this example
Next TopicRetrieving File From Oracle Database
Example to retrieve file from Oracle database:
The getClob() method of PreparedStatement is used to get file information from the
database.
Syntax of getClob method
1. public Clob getClob(int columnIndex){}
Let's see the table structure of this example to retrieve the file.
1. CREATE TABLE "FILETABLE"
2.
3.
"ID" NUMBER,
"NAME" CLOB
4.
5. /
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);
16.Reader r=c.getCharacterStream();
17.
18.FileWriter fw=new FileWriter("d:\\retrivefile.txt");
19.
20.int i;
21.while((i=r.read())!=-1)
22.fw.write((char)i);
23.
24.fw.close();
25.con.close();
26.
27.System.out.println("success");
28.}catch (Exception e) {e.printStackTrace(); }
29.}
30.}
download this example
Next TopicCallableStatement Interface
CallableStatement Interface
The differences between stored procedures and functions are given below:
Stored Procedure
Function
We can call functions from the procedure. Procedure cannot be called from function.
To call the stored procedure, you need to create it in the database. Here, we are assuming that
stored procedure looks like this.
1. create or replace procedure "INSERTR"
2. (id IN NUMBER,
3. name IN VARCHAR2)
4. is
5. begin
6. insert into user420 values(id,name);
7. end;
8. /
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");
6. Connection con=DriverManager.getConnection(
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8.
9. CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
10.stmt.setInt(1,1011);
11.stmt.setString(2,"Amit");
12.stmt.execute();
13.
14.System.out.println("success");
15.}
16.}
Now check the table in the database, value is inserted in the user420 table.
In this example, we are calling the sum4 function that receives two input and returns the sum of
the given number. Here, we have used the registerOutParameter method of CallableStatement
interface, that registers the output parameter with its corresponding type. It provides information
to the CallableStatement about the type of result being displayed.
The Types class defines many constants such as INTEGER, VARCHAR, FLOAT, DOUBLE,
BLOB, CLOB etc.
Let's create the simple function in the database first.
1. create or replace function sum4
2. (n1 in number,n2 in number)
3. return number
4. is
5. temp number(8);
6. begin
7. temp :=n1+n2;
8. return temp;
9. end;
10./
11.stmt.setInt(2,10);
12.stmt.setInt(3,43);
13.stmt.registerOutParameter(1,Types.INTEGER);
14.stmt.execute();
15.
16.System.out.println(stmt.getInt(1));
17.
18.}
19.}
1. Output: 53
Next TopicTransaction Management in JDBC
Transaction Management in JDBC
fast performance It makes the performance fast because database is hit at the time of commit.
Description
void rollback()
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.
12.con.commit();
13.con.close();
14.}}
If you see the table emp400, you will see that 2 records has been added.
Example of transaction management in jdbc using PreparedStatement
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();
39.}
40.
41.
42.System.out.println("Want to add more records y/n");
43.String ans=br.readLine();
44.if(ans.equals("n")){
45.break;
46.}
47.
48.}
49.con.commit();
50.System.out.println("record successfully saved");
51.
52.con.close();//before closing connection commit() is called
53.}catch(Exception e){System.out.println(e);}
54.
55.}}
It will ask to add more records until you press n. If you press n, transaction is commited.
Instead of executing a single query, we can execute a batch (group) of queries. It makes the
performance fast.
Fast Performance
Description
int[] executeBatch()
Let's see the simple example of batch processing in jdbc. It follows following steps:
Create Connection
Create Statement
Execute Batch
Close Connection
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:1
521:xe","system","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.
Example of batch processing using PreparedStatement
1. import java.sql.*;
2. import java.io.*;
3. class BP{
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:1
521:xe","system","oracle");
9.
10.PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?
,?)");
11.
36.
37.}
38.ps.executeBatch();
39.
40.System.out.println("record successfully saved");
41.
42.con.close();
43.}catch(Exception e){System.out.println(e);}
44.
45.}}
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.
Next TopicJDBC RowSet
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.
The implementation classes of RowSet interface are as follows:
JdbcRowSet
CachedRowSet
WebRowSet
JoinRowSet
FilteredRowSet
Let's see the simple example of JdbcRowSet without event handling code.
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.
12.
Class.forName("oracle.jdbc.driver.OracleDriver");
13.
14.
15.
16.
rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
17.
rowSet.setUsername("system");
18.
rowSet.setPassword("oracle");
19.
20.
21.
rowSet.execute();
22.
23.
while (rowSet.next()) {
24.
25.
26.
27.
28.
29.
30.
31.}
3. Salary: 70000
4. Id: 190
5. Name: abhi
6. Salary: 40000
7. Id: 191
8. Name: umesh
9. Salary: 50000
To perform event handling with JdbcRowSet, you need to add the instance of RowSetListener
in the addRowSetListener method of JdbcRowSet.
The RowSetListener interface provides 3 method that must be implemented. They are as follows:
1. 1) public void cursorMoved(RowSetEvent event);
2. 2) public void rowChanged(RowSetEvent event);
3. 3) public void rowSetChanged(RowSetEvent event);
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 {
11.
12.
13.
14.
15.
16.
rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
17.
rowSet.setUsername("system");
18.
rowSet.setPassword("oracle");
19.
20.
21.
rowSet.execute();
22.
23.
24.
rowSet.addRowSetListener(new MyListener());
25.
26.
while (rowSet.next()) {
27.
28.
29.
30.
31.
32.
33.
34.}
35.
36.class MyListener implements RowSetListener {
37.
38.
39.
System.out.println("Cursor Moved...");
}
40.
41.
System.out.println("Cursor Changed...");
42.
43.
44.
45.
System.out.println("RowSet changed...");
}
46.}
10.Id: 191
11.Name: umesh
12.Salary: 50000
13.Cursor Moved...
Next TopicJDBC New Features
Jdbc New Features
The latest version of JDBC is 4.0 currently. Java has updated jdbc api to ease and simplify the
coding ot database interactivity.
Here, we are going to see the features included in Jdbc 3.0 and Jdbc 4.0.
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.
Retrieval of auto generated keys Now you are able to get the auto
generated keys by the method getGeneratedKeys().
There are many new features that have been added in java. There are major enhancement made
in Java5, Java6 and Java7 like auto-boxing, generics, var-args, java annotations, enum,
premain method etc.
Most of the interviewers ask questions from this chapter.
Do You Know ?
1. How to create generic class and generic method in java ?
2. What is annotation and how to create custom annotation ?
3. What is the advantage of assertion and where we should not use it ?
4. What is variable argument and what rules are defined for variable
argument ?
5. What is the difference between import and static import ?
6. How autoboxing is applied in method overloading. Which concept beats
autoboxing ?
7. What is enum type and how to specify specific value to the enum constants ?
J2SE 4 Features
Assertion (Java 4)
J2SE 5 Features
The important features of J2SE 5 are generics and assertions. Others are auto-boxing, enum, varargs, static import, for-each loop (enhanced for loop etc.
Varargs (Java 5)
Enum (Java 5)
Annotation (Java 5)
Generics (Java 5)
JavaSE 6 Features
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.
5.
6.
7.
8.
9.
11.
12. System.out.println("value is "+value);
13. }
14.}
15.
16.
download this example
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.
Compile it by: javac AssertionExample.java
Run it by: java -ea AssertionExample
Output: Enter ur age 11
Exception in thread "main" java.lang.AssertionError: Not valid
4.
int arr[]={12,13,14,44};
5.
6.
for(int i:arr){
7.
8.
System.out.println(i);
}
9.
10. }
11.}
12.
Output:12
13
14
44
4.
5.
list.add("vimal");
6.
list.add("sonoo");
7.
list.add("ratan");
8.
9.
for(String s:list){
10.
11.
System.out.println(s);
}
12.
13. }
14.}
15.
16.</string></string>
Output:vimal
sonoo
ratan
approach.
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:
1. return_type method_name(data_type... variableName){}
5.
6.
7.
8.
9.
10. display();//zero argument
11. display("my","name","is","varargs");//four arguments
12. }
13.}
14.
Output:display method invoked
display method invoked
5.
6.
for(String s:values){
7.
System.out.println(s);
8.
9.
}
}
10.
11. public static void main(String args[]){
12.
13. display();//zero argument
14. display("hello");//one argument
15. display("my","name","is","varargs");//four arguments
16. }
17.}
18.
Output:display method invoked
display method invoked
hello
display method invoked
my
name
is
varargs
5.
System.out.println("number is "+num);
6.
for(String s:values){
7.
8.
9.
System.out.println(s);
}
}
10.
11. public static void main(String args[]){
12.
13. display(500,"hello");//one argument
14. display(1000,"my","name","is","varargs");//four arguments
15. }
16.}
17.
Output:number is 500
hello
number is 1000
my
name
is
varargs
Less coding is required if you have access any static member of a class
oftenly.
If you overuse the static import feature, it makes the program unreadable
and unmaintainable.
3.
4.
5.
6.
out.println("Java");
7.
8.
9. }
10.
Output:Hello
Java
4.
int a=50;
5.
6.
7.
Integer a3=5;//Boxing
8.
9.
System.out.println(a2+" "+a3);
10. }
11.}
12.
Output:50 5
7.
8.
System.out.println(a);
}
9. }
10.
Output:50
4.
5.
6.
if(i<100){
7.
System.out.println(i);
8.
9.
//unboxing internally
10.}
11.
Output:50
4.
5.
6.
7.
short s=30;
8.
m(s);
9.
10.}
11.
Output:int
4.
5.
6.
7.
short s1=30,s2=40;
8.
m(s1,s2);
9.
10.}
11.
Output:int int
4.
5.
6.
7.
int a=30;
8.
m(a);
9.
10.}
11.
Output:Integer
2. class Boxing3{
3.
4.
5.
6.
int a=30;
7.
m(a);
8.
9. }
10.
Output:Compile Time Error
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.
Points to remember for Enum:
1. enum improves type safety
2. enum can be easily used in switch
3. enum can be traversed
4. enum can have fields, constructors and methods
5. enum may implement many interfaces but cannot extend any class because
it internally extends Enum class
2. class EnumExample1{
3.
4. public enum Season { WINTER, SPRING, SUMMER, FALL }
5.
6. public static void main(String[] args) {
7. for (Season s : Season.values())
8. System.out.println(s);
9.
10.}}
11.
Output:WINTER
SPRING
SUMMER
FALL
Internal code generated by the compiler for the above example of enum
type
The java compiler internally creates a static and final class that extends the Enum
class as shown in the below example:
1. public static final class EnumExample1$Season extends Enum
2. {
3.
4.
5.
6.
super(s, i);
}
7.
8.
9.
10.
return (EnumExample1$Season[])$VALUES.clone();
11.
12.
13.
14.
15.
return (EnumExample1$Season)Enum.valueOf(EnumExample1$Season,
s);
16.
17.
18.
19.
20.
21.
22.
23.
24.
static
25.
26.
27.
28.
29.
30.
31.
32.
33.
});
}
34.
35.}
Defining enum:
The enum can be defined within or outside the class because it is similar to a class.
Example of enum that is defined outside the class:
1.
2. enum Season { WINTER, SPRING, SUMMER, FALL }
3.
4. class EnumExample2{
5. public static void main(String[] args) {
6.
7. Season s=Season.WINTER;
8. System.out.println(s);
9.
10.}}
11.
Output:WINTER
3.
4. public static void main(String[] args) {
5. Season s=Season.WINTER;//enum type is required to access WINTER
6. System.out.println(s);
7.
8. }}
9.
Output:WINTER
13.
14.}}
15.
download this enum example
Output:WINTER 5
SPRING 10
SUMMER 15
FALL 20
Constructor of enum type is private if you don't declare private compiler internally
have private constructor
1. enum Season{
2. WINTER(10),SUMMER(20);
3. private int value;
4. Season(int value){
5. this.value=value;
6. }
7. }
8.
Internal code generated by the compiler for the above example of enum
type
1. final class Season extends Enum
2. {
3.
4.
5.
6.
7.
return (Season[])$VALUES.clone();
}
8.
9.
10.
11.
12.
13.
14.
15.
16.
super(s, i);
17.
value = j;
18.
19.
20.
21.
22.
23.
24.
25.
static
26.
27.
28.
29.
30.
31.
WINTER, SUMMER
});
32.
33.}
14. break;
15.default:
16.System.out.println("other day");
17.}
18.
19.}}
20.
download this enum example
Output:monday
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.
Built-In Annotations that are applied to java code
@Override
@SuppressWarnings
@Deprecated
@Target
@Retention
@Inherited
@Documented
@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
7. void eatsomething(){System.out.println("eating foods");}//should be eatSome
thing
8. }
9.
10.class Test{
11.public static void main(String args[]){
12.Animal a=new Dog();
13.a.eatSomething();
14.}}
Output: Comple Time Error
@SuppressWarnings
@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. }
7.
8. class Test{
9. public static void main(String args[]){
10.
11.A a=new A();
12.a.n();
13.}}
At Compile Time:
Note: Test.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
At Runtime:
hello n
Custom Annotation
Creating, Applying and Accessing Custom Annotation
Next TopicCustom Annotation
<<prev
next>>
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
2) Single-Value Annotation
An annotation that has one method, is called Single-Value annotation. For example:
1. @interface MyAnnotation{
2. int value();
3. }
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. }
@Target
@Retention
@Inherited
@Documented
@Target
TYPE
FIELD
fields
METHOD
methods
CONSTRUCTOR
constructors
LOCAL_VARIABLE
local variables
ANNOTATION_TYPE
annotation type
PARAMETER
parameter
2. @interface MyAnnotation{
3. int value1();
4. String value2();
5. }
Example to specify annoation for a class, methods or fields
1. @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
2. @interface MyAnnotation{
3. int value1();
4. String value2();
5. }
@Retention
Availability
RetentionPolicy.SOU
RCE
RetentionPolicy.CLA
SS
RetentionPolicy.RUN
TIME
5. String value2();
6. }
Let's see the simple example of creating, applying and accessing annotation.
1. //Creating annotation
2. import java.lang.annotation.*;
3. import java.lang.reflect.*;
4.
5. @Retention(RetentionPolicy.RUNTIME)
6. @Target(ElementType.METHOD)
7. @interface MyAnnotation{
8. int value();
9. }
10.
11.//Applying annotation
12.class Hello{
13.@MyAnnotation(value=10)
14.public void sayHello(){System.out.println("hello annotation");}
15.}
16.
17.//Accessing annotation
18.class Test{
19.public static void main(String args[])throws Exception{
20.
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{}
@Documented
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.
Advantage of Java Generics
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than
runtime.
1. List<String> list = new ArrayList<String>();
2. list.add("hello");
3. list.add(32);//Compile Time Error
Here, we are using the ArrayList class, but you can use any collection class such as ArrayList,
LinkedList, HashSet, TreeSet, HashMap, Comparator etc.
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
Now we are going to use map elements using generics. Here, we need to pass key and value. Let
us understand it by a simple example:
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.}
17.
18.}}
Output:1 vijay
2 ankit
4 umesh
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.
Lets see the simple example to create and use the generic class.
Creating 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.
Using generic class:
The type parameters naming conventions are important to learn generics thoroughly. The
commonly type parameters are as follows:
1. T - Type
2. E - Element
3. K - Key
4. N - Number
5. V - Value
6. S,U,V etc. - 2nd, 3rd, 4th types
Generic Method
Like generic class, we can create generic method that can accept any type of argument.
Lets see a simple example of java generic method to print array elements. We are using here E
to denote the element.
1. public class GenericMethodDemo{
2.
3.
4.
5.
System.out.println(element );
6.
7.
System.out.println();
8.
9.
10.
11.
12.
13.
14.
printArray( intArray );
15.
16.
17.
18.
printArray( charArray );
}
19.}
Output:Printing Integer Array
10
20
30
40
50
Printing Character Array
J
A
V
A
T
P
O
I
N
T
Next TopicRMI
creating a remote interface that extends the Remote interface. There is only one
method named add() and it declares RemoteException.
1. import java.rmi.*;
2. public interface Adder extends Remote{
3.
4. public int add(int x,int y)throws RemoteException;
5. }
In case, you extend the UnicastRemoteObject class, you must define a constructor
that declares RemoteException.
1. import java.rmi.*;
2. import java.rmi.server.*;
3.
4. public class AdderRemote extends UnicastRemoteObject implements Adder{
5.
6. AdderRemote()throws RemoteException{
7. super();
8. }
9.
10.public int add(int x,int y){return x+y;}
11.
12.}
3) create the stub and skeleton objects using the rmic tool.
Next step is to create stub and skeleton objects using the rmi compiler. The rmic
tool invokes the RMI compiler and creates stub and skeleton objects.
1. rmic AdderRemote
In this example, we are binding the remote object by the name sonoo.
1. import java.rmi.*;
2. import java.rmi.registry.*;
3.
4. public class MyServer{
5.
6. public static void main(String args[]){
7. try{
8.
9. Adder stub=new AdderRemote();
10.Naming.rebind("rmi://localhost:5000/sonoo",stub);
11.
12.}catch(Exception e){System.out.println(e);}
13.}
14.
15.}
4.
5. public static void main(String args[]){
6. try{
7.
8. Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
9. System.out.println(stub.add(34,4));
10.
11.}catch(Exception e){}
12.}
13.
14.}
12.
13.rmiregistry 5000
14.
15.4)start the server in another command prompt
16.
17.java MyServer
18.
19.5)start the client application in another command prompt
20.
21.java MyClient
ERROR
Internationalization and Localization in Java
1. Internationalization and Localization
2. Understanding the culturally dependent data
3. Locale class
4. Example of Local class that prints the informations of the default locale
5. Example of Local class that prints english in different languages
6. Example of Local class that print display language of many locales
Internationalization is also abbreviated as I18N because there are total 18 characters between
the first letter 'I' and the last letter 'N'.
Internationalization is a mechanism to create such an application that can be adapted to different
languages and regions.
Internationalization is one of the powerful concept of java if you are developing an application
and want to display messages, currencies, date, time etc. according to the specific region or
language.
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 ?
How can we globalize the messages (or) What is the use of ResourceBundle
class?
Messages
Dates
Times
Numbers
Currencies
Measurements
Phone Numbers
Postal Addresses
can be used to get the locale specific information such as country name, language,
variant etc.
Fields of Locale class
There are fields of Locale class:
1. public static final Locale ENGLISH
2. public static final Locale FRENCH
3. public static final Locale GERMAN
4. public static final Locale ITALIAN
5. public static final Locale JAPANESE
6. public static final Locale KOREAN
7. public static final Locale CHINESE
8. public static final Locale SIMPLIFIED_CHINESE
9. public static final Locale TRADITIONAL_CHINESE
10.public static final Locale FRANCE
11.public static final Locale GERMANY
12.public static final Locale ITALY
13.public static final Locale JAPAN
14.public static final Locale KOREA
15.public static final Locale CHINA
16.public static final Locale PRC
17.public static final Locale TAIWAN
18.public static final Locale UK
19.public static final Locale US
20.public static final Locale CANADA
Example of Local class that prints the informations of the default locale
In this example, we are displaying the informations of the default locale. If you want
to get the informations about any specific locale, comment the first line statement
and uncomment the second line statement in the main method.
1. import java.util.*;
3.
4.
5.
6.
7.
8.
enLocale.getDisplayLanguage());
9.
10.
11.
enLocale.getDisplayLanguage(frLocale));
12.
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
9.
10.}
11.}
12.
13.}
Output:en_US: English
es_ES: espa???ol
it_IT: italiano
ResourceBundle class
<<prev
Next TopicResourceBundle Class
ResourceBundle class in Java
1. ResourceBundle class
2. Commonly used methods of ResourceBundle class
3. Example of ResourceBundle class
The ResourceBundle class is used to internationalize the messages. In other words, we can say
that it provides a mechanism to globalize the messages.
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.
Conventionally, the name of the properties file should be filename_languagecode_country code
for example MyMessage_en_US.properties.
MessageBundle_en_US.properties
greeting=Hello, how are you?
MessageBundle_in_ID.properties
InternationalizationDemo.java
1. import java.util.Locale;
2. import java.util.ResourceBundle;
3. public class InternationalizationDemo {
4.
5.
6.
7.
8.
9.
<<prev
next>>
<<prev
Internationalizing Date (I18N with Date)
1. Internationalizing Date
2. Commonly used methods of the DateFormat class
3. Example of Inernationalizing Date
The format of the dates differ from one region to another that is why we internationalize the
dates.
We can internationalize the date by using the getDateInstance() method of the DateFormat
class. It receives the locale object as a parameter and returns the instance of the DateFormat
class.
public String format(Date date) returns the formatted and localized date
as a string.
printDate(Locale.UK);
14.
printDate(Locale.US);
15.
printDate(Locale.FRANCE);
16.}
17.}
download this example
Output:01-Mar-2012 en_GB
Mar 1, 2012 en_US
1 mars 2012 fr_FR
<<prev
next>>
The display format of the time differs from one region to another, so we need to internationalize
the time.
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.
Syntax of the getTimeInstance() method is given below:
public static DateFormat getTimeInstance(int style, 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.}
download this example
Output:16:22:49 in locale en_GB
4:22:49 PM in locale en_US
16:22:49 in locale fr_FR
The representation of the numbers differ from one locale to another. Internationalizing the
numbers is good approach for the application that displays the informations according to the
locales.
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.
Syntax of these methods is given below:
1. public static NumberFormat getNumberInstance(Locale locale)
2. public static NumberFormat getInstance(Locale locale)//same as above
In this example, we are internationalizing the number. The format method of the NumberFormat
class formats the double value into the locale specific number.
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);
printNumber(Locale.UK);
15.
printNumber(Locale.US);
16.
printNumber(Locale.FRANCE);
17.
printNumber(Locale.JAPAN);
18.
19.}
20.}
download this example
Output:105,500.324 for the locale en_GB
105,000.324 for the locale en_US
105,a000,324 for the locale fr_FR
As we have internationalize the date, time and numbers, we can internationalize the currency
also. The currency differs from one country to another so we need to internationalize the
currency.
The NumberFormat class provides methods to format the currency according to the locale. The
getCurrencyInstance() method of the NumberFormat class returns the instance of the
NumberFormat class.
The syntax of the getCurrencyInstance() method is given below:
1. public static NumberFormat getCurrencyInstance(Locale locale)
Example of Internationalizing Currency
In this example, we are internationalizing the currency. The format method of the
NumberFormat class formats the double value into the locale specific currency.
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.
10.}
11.
12.public static void main(String[] args) {
13.
printCurrency(Locale.UK);
14.
printCurrency(Locale.US);
15.
printCurrency(Locale.FRANCE);
16.}
17.}
download this example
Output:?10,500.32 for the locale en_GB
$10,500.32 for the locale en_US
10 500,32 ? for the locale fr_FR