Core Java
Core Java
What is Java?
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:
There are mainly 4 type of applications that can be created using java:
1) Standalone Application
It is also known as desktop application or window-based application. An application that we need to install on every machine such as
media player, antivirus etc. AWT and Swing are used in java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates dynamic page, is called web application. Currently, servlet, jsp, struts, jsf etc.
technologies are used for creating web applications in java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the advantage of high level security, load balancing
and clustering. In java, EJB is used for creating enterprise applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used for creating mobile applications.
Do You Know?
What is the difference between JRE and JVM?
What is the purpose of JIT compiler?
Can we save the java source file without any name?
Why java uses the concept of unicode system?
At that time, it was a advanced concept for the green team. But, it was good for internet programming. Later, Netscape Navigator
incorporated Java technology.
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.
5) Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries like U.S.A., France, Germany, Romania
etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
7) Why they choosed java name for java language? The team gathered to choose a new name. The suggested words were
"dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They wanted something that reflected the essence of the technology:
revolutionary, dynamic, lively, cool, unique, and easy to spell and fun to say.
According to James Gosling "Java was one of the top choices along with Silk". Since java was so unique, most of the team members
preferred java.
8) Java is an island of Indonesia where first coffee was produced (called java coffee).
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
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:
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
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.
No need to remove unreferenced objects because there is Automatic Garbage Collection in java.
Object-oriented
Object-oriented means we organize our software as a combination of different types of objects that incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software development and maintenace by providing some rulues.
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
A platform is the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-
based. Java provides software-based platform. The Java platform differs from most other platforms in the sense that it's a software-based
platform that runs on top of other hardware-based platforms.It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms
e.g.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.
Classloader- adds security by separating the package for the classes of the local file system from those that are imported from network
sources.
Bytecode Verifier- checks the code fragments for illegal code that can violate accesss right to objects.
Security Manager- determines what resources a class can access such as reading and writing to the local disk.
These security are provided by java language. Some sucurity can also be provided by application developer through SSL,JAAS,cryptography etc.
Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers that avoids security problem. There is automatic
garbage collection in java. There is exception handling and type checking mechanism in java. All these points makes java robust.
Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is set.
Portable
We may carry the java bytecode to any platform.
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a compiled language (e.g., C++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access files by calling the
methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it shares
the same memory. Threads are important for multi-media, Web applications etc.
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java")
4. }
5. }
To compile:javac Simple.java
To execute:java Simple
Output:Hello Java
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
To write the simple program, open notepad and write simple program as displayed below:
As displayed in the above diagram, write the simple program of java in notepad and saved it as Simple.java. To compile and run this program,
you need to open command prompt by start -> All Programs -> Accessories -> command prompt.
To compile and run the above program, go to your current directory first; my current directory is c:\new . Write here:
To compile:javac Simple.java
To execute:java Simple
Q)Can you save a java source file by other name than the class name?
Yes, like the figure given below illustrates:
To
javac Hard.java
compile:
To execute:java Simple
For Example:
Go to MyComputer properties -> advanced tab -> environment variables -> new tab of user variable -> write path in variable name ->
write path of bin folder in variable value -> ok -> ok -> ok
For Example:
1)Go to MyComputer properties
2)click on advanced tab
3)click on environment variables
4)click on new tab of user variables
5)write path in variable name
6)Copy the path of bin folder
7)paste path of bin folder in variable value
8)click on ok button
9)click on ok button
Now your permanent path is set.You can now execute any program of java from any drive.
Setting Path in Linux OS
Setting the path in Linux OS is same as setting the path in the Windows OS. But here we use export tool rather than set. Let's see how to set path
in Linux OS:
export PATH=$PATH:/home/jdk1.6.01/bin/
Here, we have installed the JDK in the home directory under Root (/home).
JVM
JVM (Java Virtual Machine) is an abstract machine.It is a specification that provides runtime environment in which java bytecode can be
executed.
JVMs are available for many hardware and software platforms (i.e.JVM is plateform dependent).
Loads code
Verifies code
Executes code
Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the implementation of JVM.It physically exists.It
contains set of libraries + other files that JVM uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.
JVM (Java Virtual Machine)
JVM (Java Virtual Machine) is an abstract machine.It is a specification that provides runtime environment in which java bytecode can be
executed.
JVMs are available for many hardware and software platforms (i.e.JVM is plateform dependent).
Loads code
Verifies code
Executes code
Provides runtime environment
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
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:
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.
PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed.
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
Variable is name of reserved area allocated in memory.
int data=50;//Here data is variable
Types of Variable
There are three types of variables in java
local variable
instance variable
static 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 instance variable . It is not declared as static.
Static variable
A variable that is declared as static is called static variable. It cannot be local.
class A{
void method(){
int n=90;//local variable
}
}//end of class
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Unicode System
Unicode is a universal international standard character encoding that is capable of representing most of the world's written languages.
1. A particular code value corresponds to different letters in the various language standards.
2. The encodings for languages with large character sets have variable length.Some common
characters are encoded as single bytes, other require two or more byte.
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF
Operators in java
Operator is a special symbol that is used to perform operations. There are many types of operators in java such as unary operator,
arithmetic operator, relational operator, shift operator, bitwise operator, ternary operator and assignment operator.
Precedence of Operators
Operators Precedence
multiplicative * / %
additive + -
equality == !=
bitwise inclusive OR |
logical OR ||
ternary ? :
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.
}
}
}
}
}
}
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);
}
}
return n*=fact(n-1);
}
int f=fact(5);
System.out.println(f);
}
}
Java OOPs Concepts
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.
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to
design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code
reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to convense the customer differently, to
draw something e.g. shape or rectangle etc.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal
processing.
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.
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.
What is difference between object-oriented programming language and object-based programming language?
Object based programming language follows all the features of OOPs except Inheritance. JavaScript and VBScript are examples of object based
programming languages.
Do You Know ?
Advantage of OOPs
Naming Convention
Object and class
Method overloading
Constructor
static keyword
this keyword with 6 usage
Inheritance
Aggregation
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
Name Convension
class name should begin with uppercase letter and be a noun e.g.String,System,Thread etc.
Interface name should begin with uppercase letter and be an adjective (whereever possible). e.g. Runnable,ActionListener etc.
method name should begin with lowercase letter and be a verb. e.g. main(),print(),println(),actionPerformed() etc.
variable name should begin with lowercase letter e.g. firstName,orderNumber etc.
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
A runtime entity that has state and behaviour is known as an object. For example: chair, table, pen etc. It can be tengible or intengible
(physical or logical).
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to write, so writing is its behaviour.
Object is an instance of a class.Class is a template or blueprint from which objects are created.So object is the instance(result) of a class.
Class
A class is a group of objects that have common property. It is a template or blueprint from which objects are created.
data member
method
constructor
block
1. class <class_name>{
2. data member;
3. method;
4. }
1. class Student{
2. int id;//data member (also instance variable)
3. String name;//data member(also instance variable)
4.
5. public static void main(String args[]){
6. Student s1=new Student();//creating an object of Student
7. System.out.println(s1.id+" "+s1.name);
8.
9. }
10. }
Output:0 null
Instance variable
A variable that is created inside the class but outside the method, is known as instance variable.Instance variable doesn't get memory at compile
time.It gets memory at runtime when object(instance) is created.That is why, it is known as instance variable.
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.
Output:111 Karan
222 Aryan
1. class Rectangle{
2. int length;
3. int width;
4.
5. void insert(int l,int w){
6. length=l;
7. width=w;
8. }
9.
10. void calculateArea(){System.out.println(length*width);}
11.
12. public static void main(String args[]){
13. Rectangle r1=new Rectangle();
14. Rectangle r2=new Rectangle();
15.
16. r1.insert(11,5);
17. r2.insert(3,15);
18.
19. r1.calculateArea();
20. r2.calculateArea();
21. }
22. }
Output:55
45
By new keyword
By newInstance() method
By clone() method
By factory method etc.
If you have to use an object only once, annonymous object is a good approach.
1. class Calculation{
2.
3. void fact(int n){
4. int fact=1;
5. for(int i=1;i<=n;i++){
6. fact=fact*i;
7. }
8. System.out.println("factorial is "+fact);
9. }
10.
11. public static void main(String args[]){
12. new Calculation().fact(5);//calling method with annonymous object
13. }
14. }
Output:Factorial is 120
1. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
Output:55
45
Method Overloading in Java
If a class have multiple methods by same name but different parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such
as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to
understand the behaviour of the method because its name differs. So, we perform method overloading to figure out the program
quickly.
In java, Methood Overloading is not possible by changing the return type of the method.
1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10,10,10);
8. obj.sum(20,20);
9.
10. }
11. }
Output:30
40
2)Example of Method Overloading by changing data type of argument
In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and
second sum method receives two double arguments.
1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(double a,double b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10.5,10.5);
8. obj.sum(20,20);
9.
10. }
11. }
Output:21.0
40
Que) Why Method Overloaing is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity. Let's see how
ambiguity may occur:
1. class Calculation{
2. int sum(int a,int b){System.out.println(a+b);}
3. double sum(int a,int b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. int result=obj.sum(20,20); //Compile Time Error
8.
9. }
10. }
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see the simple
example:
1. class Simple{
2. public static void main(int a){
3. System.out.println(a);
4. }
5.
6. public static void main(String args[]){
7. System.out.println("main() method invoked");
8. main(10);
9. }
10. }
As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int,long,float
or double. The char datatype can be promoted to int,long,float or double and so on.
1. class Calculation{
2. void sum(int a,long b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(20,20);//now second int literal will be promoted to long
8. obj.sum(20,20,20);
9.
10. }
11. }
Output:40
60
1. class Calculation{
2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b){System.out.println("long arg method invoked");}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(20,20);//now int arg sum() method gets invoked
8. }
9. }
1. class Calculation{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(20,20);//now ambiguity
8. }
9. }
One type is not depromoted implicitely for example double cannot be depromoted to any type implicitely.
Constructor in Java
1. Types of constructors
1. 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 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.
1. <class_name>(){}
1. class Bike{
2.
3. Bike(){System.out.println("Bike is created");}
4.
5. public static void main(String args[]){
6. Bike b=new Bike();
7. }
8. }
Output:Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
Default constructor provides the default values to the object like 0, null etc. depending on the type.
1. class Student{
2. int id;
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. <strong>Output:</strong>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.
1. class Student{
2. int id;
3. String name;
4.
5. Student(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
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.
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
Constructor Method
Constructor is used to initialize the state of an object. Method is used to expose behaviour of an object.
Constructor must not have return type. Method must have return type.
The java compiler provides a default constructor if you don't have any constructor. Method is not provided by compiler in any case.
Constructor name must be same as the class name. Method name may 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. class Student{
2. int id;
3. String name;
4. Student(int i,String n){
5. id = i;
6. name = n;
7. }
8.
9. Student(Student s){
10. id = s.id;
11. name =s.name;
12. }
13. void display(){System.out.println(id+" "+name);}
14.
15. public static void main(String args[]){
16. Student s1 = new Student(111,"Karan");
17. Student s2 = new Student(s1);
18. s1.display();
19. s2.display();
20. }
21. }
Output:111 Karan
111 Karan
1. class Student{
2. int id;
3. String name;
4. Student(int i,String n){
5. id = i;
6. name = n;
7. }
8. void display(){System.out.println(id+" "+name);}
9.
10. public static void main(String args[]){
11. Student s1 = new Student(111,"Karan");
12. Student s2 = new Student();
13. s2.id=s1.id;
14. s2.name=s1.name;
15. s1.display();
16. s2.display();
17. }
18. }
Output:111 Karan
111 Karan
Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the constructor as you perform in the
method.
static keyword
1. Static variable
2. Program of counter without static variable
3. Program of counter with static variable
4. Static method
5. Restrictions for static method
6. Why main method is static ?
7. Static block
8. Can we execute a program without main method ?
The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods, blocks
and nested class. The static keyword belongs to the class than instance of the class.
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.
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }
Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All
student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.If
we make it static,this field will get memory only once.
1. //<b>Program of static variable</b>
2.
3. class Student{
4. int rollno;
5. String name;
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. }
1. class Counter{
2. int count=0;//will get memory when instance is created
3.
4. Counter(){
5. count++;
6. System.out.println(count);
7. }
8.
9. public static void main(String args[]){
10.
11. Counter c1=new Counter();
12. Counter c2=new Counter();
13. Counter c3=new Counter();
14.
15. }}
Output:1
1
1
Output:1
2
3
2) static method
If you apply static keyword with any method, it is known as static method.
1. //Program of changing the common property of all objects(static 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. }
1. //Program to get cube of a given number by static method
2.
3. Class Calculate{
4.
5. static int cube(int x){
6. return x*x*x;
7. }
8.
9. public static void main(String args[]){
10. int result=Calculate.cube(5);
11. System.out.println(result);
12. }
13. }
Output:125
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. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
Output:Compile Time Error
3)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. }
this keyword
1. this keyword
2. Usage of this keyword
1. to refer the current class instance variable
2. to invoke the current class constructor
3. to invoke the current class method
4. to pass as an argument in the method call
5. to pass as an argument in the constructor call
6. to return the current class instance
3. Proving this keyword
There can be a lot of usage of this keyword. In java, this is a reference variable that refers to the current object.
Suggestion:If you are beginner to java, lookup only two usage of this keyword.
1) 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.
1. class student{
2. int id;
3. String name;
4.
5. student(int id,String name){
6. id = id;
7. name = name;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
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.
3. class Student{
4. int id;
5. String name;
6.
7. student(int id,String name){
8. this.id = id;
9. this.name = name;
10. }
11. void display(){System.out.println(id+" "+name);}
12. public static void main(String args[]){
13. Student s1 = new Student(111,"Karan");
14. Student s2 = new Student(222,"Aryan");
15. s1.display();
16. s2.display();
17. }
18. }
Output:111 Karan
222 Aryan
If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:
1. class Student{
2. int id;
3. String name;
4.
5. student(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10. public static void main(String args[]){
11. Student e1 = new Student(111,"karan");
12. Student e2 = new Student(222,"Aryan");
13. e1.display();
14. e2.display();
15. }
16. }
Output:111 Karan
222 Aryan
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. //Program of this() constructor call (constructor chaining)
2.
3. class Student{
4. int id;
5. String name;
6. Student (){System.out.println("default constructor is invoked");}
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
default constructor is invoked
111 Karan
222 Aryan
1. class Student{
2. int id;
3. String name;
4. String city;
5.
6. Student(int id,String name){
7. this.id = id;
8. this.name = name;
9. }
10. Student(int id,String name,String city){
11. this(id,name);//now no need to initialize id and name
12. this.city=city;
13. }
14. void display(){System.out.println(id+" "+name+" "+city);}
15.
16. public static void main(String args[]){
17. Student e1 = new Student(111,"karan");
18. Student e2 = new Student(222,"Aryan","delhi");
19. e1.display();
20. e2.display();
21. }
22. }
1. class Student{
2. int id;
3. String name;
4. Student (){System.out.println("default constructor is invoked");}
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. }
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. class S{
2. void m(){
3. System.out.println("method is invoked");
4. }
5. void n(){
6. this.m();//no need because compiler does it for you.
7. }
8. void p(){
9. n();//complier will add this to invoke n() method as this.n()
10. }
11. public static void main(String args[]){
12. S s1 = new S();
13. s1.p();
14. }
15. }
Output:method is invoked
1. class S{
2. void m(S obj){
3. System.out.println("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8.
9. public static void main(String args[]){
10. S s1 = new S();
11. s1.p();
12. }
13. }
Output:method is invoked
1. class B{
2. A obj;
3. B(A obj){
4. this.obj=obj;
5. }
6. void display(){
7. System.out.println(obj.data);//using data member of A class
8. }
9. }
10.
11. class A{
12. int data=10;
13. A(){
14. B b=new B(this);
15. b.display();
16. }
17. public static void main(String args[]){
18. A a=new A();
19. }
20. }
Output:10
1. return_type method_name(){
2. return this;
3. }
Example of this keyword that you return as a statement from the method
1. class A{
2. A getA(){
3. return this;
4. }
5. void msg(){System.out.println("Hello java");}
6. }
7.
8. class Test{
9. public static void main(String args[]){
10. new A().getA().msg();
11. }
12. }
Output:Hello java
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.
Syntax of Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
The keyword extends indicates that you are making a new class that derives from an existing class. In the terminology of Java, a class that is
inherited is called a superclass. The new class is called a subclass.
Understanding the simple example of inheritance
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship between two classes is
Programmer IS-A Employee.It means that Programmer is a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4.
5. class Programmer extends Employee{
6. int bonus=10000;
7.
8. public static void main(String args[]){
9. Programmer p=new Programmer();
10. System.out.println("Programmer salary is:"+p.salary);
11. System.out.println("Bonus of Programmer is:"+p.bonus);
12. }
13. }
In the above example,Programmer object can access the field of own class as well as of Employee class i.e. code reusability.
Types of Inheritance
On the basis of class, there can be three types of inheritance: single, multilevel and hierarchical.
Multiple and Hybrid is supported through interface only. We will learn about interfaces later.
Multiple inheritance is not supported in java in case of class.
When a class extends multiple classes i.e. known as multiple inheritance. For Example:
Que) Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java. For example:
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4.
5. class B{
6. void msg(){System.out.println("Welcome");}
7. }
8.
9. class C extends A,B{//suppose if it were
10.
11. Public Static void main(String args[]){
12. C obj=new C();
13. obj.msg();//Now which msg() method would be invoked?
14. }
15. }
Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.
Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more object named
address, which contains its own informations such as city, state, country, zipcode etc. as given below.
1. class Employee{
2. int id;
3. String name;
4. Address address;//Address is a class
5. ...
6. }
In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.
Why use Aggregation?
In this example, we have created the reference of Operation class in the Circle class.
1. class Operation{
2. int square(int n){
3. return n*n;
4. }
5. }
6.
7. class Circle{
8. Operation op;//aggregation
9. double pi=3.14;
10.
11. double area(int radius){
12. op=new Operation();
13. int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
14. return pi*rsquare;
15. }
16.
17.
18.
19. public static void main(String args[]){
20. Circle c=new Circle();
21. double result=c.area(5);
22. System.out.println(result);
23. }
24. }
Output:78.5
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.
In this example, Employee has an object of Address, address object contains its own informations such as city, state, country etc. In
such case relationship is Employee HAS-A address.
Address.java
1. public class Address {
2. String city,state,country;
3.
4. public Address(String city, String state, String country) {
5. this.city = city;
6. this.state = state;
7. this.country = country;
8. }
9.
10. }
Emp.java
1. public class Emp {
2. int id;
3. String name;
4. Address address;
5.
6. public Emp(int id, String name,Address address) {
7. this.id = id;
8. this.name = name;
9. this.address=address;
10. }
11.
12. void display(){
13. System.out.println(id+" "+name);
14. System.out.println(address.city+" "+address.state+" "+address.country);
15. }
16.
17. public static void main(String[] args) {
18. Address address1=new Address("gzb","UP","india");
19. Address address2=new Address("gno","UP","india");
20.
21. Emp e=new Emp(111,"varun",address1);
22. Emp e2=new Emp(112,"arun",address2);
23.
24. e.display();
25. e2.display();
26.
27. }
28. }
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.
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
Let's understand the problem that we may face in the program if we don't use method overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike extends Vehicle{
5.
6. public static void main(String args[]){
7. Bike obj = new Bike();
8. obj.run();
9. }
10. }
Output:Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.
In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation.
The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6.
7. public static void main(String args[]){
8. Bike obj = new Bike();
9. obj.run();
10. }
There are three basic differences between the method overloading and method overriding. They are as follows:
1) Method overloading is used to increase the Method overriding is used to provide the specific implementation of the method that is
readability of the program. already provided by its super class.
2) method overlaoding is performed within a class. Method overriding occurs in two classes that have IS-A relationship.
Whenever you create the instance of subclass, an instance of parent class is created implicitely i.e. referred by super reference
variable.
1. class Vehicle{
2. int speed=50;
3. }
4.
5. class Bike extends Vehicle{
6. int speed=100;
7.
8. void display(){
9. System.out.println(speed);//will print speed of Bike
10. }
11. public static void main(String args[]){
12. Bike b=new Bike();
13. b.display();
14.
15. }
16. }
Output:100
In the above example Vehicle and Bike both class have a common property speed. Instance variable of current class is refered by instance
bydefault, but I have to refer parent class instance variable that is why we use super keyword to distinguish between parent class instance
variable and current class instance variable.
1. //example of super keyword
2.
3. class Vehicle{
4. int speed=50;
5. }
6.
7. class Bike extends Vehicle{
8. int speed=100;
9.
10. void display(){
11. System.out.println(super.speed);//will print speed of Vehicle now
12. }
13. public static void main(String args[]){
14. Bike b=new Bike();
15. b.display();
16.
17. }
18. }
Output:50
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 construtor automatically by compiler.
As we know well that default constructor is provided by compiler automatically but it also adds super() for the first statement.If you are creating
your own constructor and you don't have either this() or super() as the first statement, compiler will provide super() as the first statement of the
consructor.
Another example of super keyword where super() is provided by the compiler implicitely.
1. class Vehicle{
2. Vehicle(){System.out.println("Vehicle is created");}
3. }
4.
5. class Bike extends Vehicle{
6. int speed;
7. Bike(int speed){
8. this.speed=speed;
9. System.out.println(speed);
10. }
11. public static void main(String args[]){
12. Bike b=new Bike(10);
13. }
14. }
Output:Vehicle is created
10
1. class Person{
2. void message(){System.out.println("welcome");}
3. }
4.
5. class Student extends Person{
6. void message(){System.out.println("welcome to java");}
7.
8. void dislay(){
9. message();//will invoke current class message() method
10. super.message();//will invoke parent class message() method
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.
In case there is no method in subclass as parent, there is no need to use super. In the example given below message() method is invoked from
Student class but Student class does not have message() method, so you can directly call message() method.
1. class Person{
2. void message(){System.out.println("welcome");}
3. }
4.
5. class Student extends Person{
6.
7. void dislay(){
8. message();//will invoke parent class message() method
9. }
10.
11. public static void main(String args[]){
12. Student s=new Student();
13. s.display();
14. }
15. }
Output:welcome
Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created.
The initialization of the instance variable can be directly but there can be performed extra operations while initilizing the instance variable in the
instance initializer block.
Que) What is the use of instance initializer block while we can directly assign a value in instance data member? For example:
1. class Bike{
2. int speed=100;
3. }
1. <b><i>//Program of instance initializer block that initializes values to the instance variable</i></b>
2.
3. class Bike{
4. int speed;
5.
6. Bike(){System.out.println("speed is "+speed);}
7.
8. {speed=100;}
9.
10. public static void main(String args[]){
11. Bike b1=new Bike();
12. Bike b2=new Bike();
13. }
14. }
Output:speed is 100
speed is 100
There are three places in java where you can perform operations:
1. method
2. constructor
3. block
1. <b><i>//Program of instance initializer block</i></b>
2.
3. class Bike{
4. int speed;
5.
6. Bike(){System.out.println("constructor is invoked");}
7.
8. {System.out.println("instance initializer block invoked");}
9.
10. public static void main(String args[]){
11. Bike b1=new Bike();
12. Bike b2=new Bike();
13. }
14. }
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 costructor after the first statement super(). So firstly, constructor is
invoked. Let's understand it by the figure given below:
Note: The java compiler copies the code of instance initializer block in every constructor.
1. <b><i>//Program of instance initializer block that is invoked after super()</i></b>
2.
3. class A{
4.
5. A(){
6. System.out.println("parent class constructor invoked");
7. }
8.
9. }
10.
11. class B extends A{
12.
13. B(){
14. super();
15. System.out.println("child class constructor invoked");
16. }
17.
18. {System.out.println("instance initializer block is invoked");}
19.
20. public static void main(String args[]){
21. B b=new B();
22. }
23. }
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
1. <b><i>//Another example of instance initializer block that is invoked after super()</i></b>
2.
3. class A{
4.
5. A(){
6. System.out.println("parent class constructor invoked");
7. }
8.
9. }
10.
11. class B extends A{
12.
13. B(){
14. super();
15.
16. System.out.println("child class constructor invoked");
17. }
18.
19. B(int a){
20. super();
21.
22. System.out.println("child class constructor invoked "+a);
23. }
24.
25. {System.out.println("instance initializer block is invoked");}
26.
27. public static void main(String args[]){
28. B b1=new B();
29. B b2=new B(10);
30. }
31. }
The final keyword in java is used to restrict the user. The final keyword can be used in many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized
final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of final keyword.
1) final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
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. class Bike{
2. final int speedlimit=90;//final variable
3.
4. void run(){
5. speedlimit=400;
6. }
7.
8. public static void main(String args[]){
9. Bike obj=new Bike();
10. obj.run();
11. }
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 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
3) final class
If you make any class as final, you cannot extend it.
1. final class Bike{}
2.
3. class Honda extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda honda= new Honda();
8. honda.run();
9. }
Output:Compile Time Error
1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda extends Bike{
5.
6. public static void main(String args[]){
7. new Honda().run();
8. }
9. }
Output:running...
1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }
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
1. class A{
2. static final int data;//static blank final variable
3.
4. static{ data=50;}
5.
6. public Static void main(String args[]){
7. System.out.println(A.data);
8. }
9. }
1. class Bike{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final
4. n*n*n;
5. }
6.
7.
8. public Static void main(String args[]){
9. Bike b=new Bike();
10. b.cube(5);
11. }
12. }
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.
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.
1. abstract class <class_name>{}
abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
Syntax to define the abstract method
1. abstract return_type <method_name>();//no braces{}
In this example, Bike the abstract class that contains only one abstract method run. It implementation is provided by the Honda class.
1. abstract class Bike{
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. }
Output:running safely..
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. abstract class Shape{
2. abstract void draw();
3. }
4.
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8.
9. class Circle extends Shape{
10. void draw(){System.out.println("drawing circle");}
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 method
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.
3. abstract class Bike{
4. abstract void run();
5. void changeGear(){System.out.println("gear changed");}
6. }
7.
8. class Honda extends Bike{
9. void run(){System.out.println("running safely..");}
10.
11. public static void main(String args[]){
12. Bike obj = new Honda();
13. obj.run();
14. obj.changeGear();
15. }
16. }
Output:running safely..
gear changed
1. //example of abstract class having constructor, field and method
2. abstract class Bike
3. {
4. int limit=30;
5. Bike(){System.out.println("constructor is invoked");}
6. 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. class Bike{
2. abstract void run();
3. }
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.
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
1. Interface
2. Example of Interface
3. Multiple inheritance by Interface
4. Why multiple inheritance is supported in Interface while it is not supported in case of class.
5. Marker Interface
6. Nested Interface
The interface is a mechanism to achieve fully abstraction in java. There can be only abstract methods in the interface. It is used to
achieve fully abstraction and multiple inheritance in Java.
The java compiler adds public and abstract keywords before the interface method and public, static and final keywords before data
members.
In other words, Interface fields are public, static and final bydefault, and methods are public and abstract.
Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an
interface.
1. interface printable{
2. void print();
3. }
4.
5. class A implements printable{
6. public void print(){System.out.println("Hello");}
7.
8. public static void main(String args[]){
9. A obj = new A();
10. obj.print();
11. }
12. }
Output:Hello
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.
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?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class. But it is supported in case of interface
because there is no ambiguity as implmentation is provided by the implementation class. For example:
1. interface Printable{
2. void print();
3. }
4.
5. interface Showable{
6. void print();
7. }
8.
9. class A implements Printable,Showable{
10.
11. public void print(){System.out.println("Hello");}
12.
13. public static void main(String args[]){
14. A obj = new A();
15. obj.print();
16. }
17. }
Output:Hello
As you can see in the above example, Printable and Showable interface have same methods but its implementation is provided by class A, so
there is no ambiguity.
Note: A class implements interface but One interface extends another interface .
1. interface Printable{
2. void print();
3. }
4.
5. interface Showable extends Printable{
6. 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
1. //How Serializable interface is written?
2.
3. public interface Serializable{
4. }
Nested Interface
Note: An interface can have another interface i.e. known as nested interface. We will learn it in detail in the nested classes chapter. For
example:
1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }
Nested Interface
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.
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.
1. interface interface_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
7.
1. class class_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
7.
1. interface Showable{
2. void show();
3. interface Message{
4. void msg();
5. }
6. }
7.
8. class Test implements Showable.Message{
9. public void msg(){System.out.println("Hello nested interface");}
10.
11. public static void main(String args[]){
12. Showable.Message message=new Test();//upcasting here
13. message.msg();
14. }
15. }
1. public static interface Showable$Message
2. {
3. public abstract void msg();
4. }
1. class A{
2. interface Message{
3. void msg();
4. }
5. }
6.
7. class Test implements A.Message{
8. public void msg(){System.out.println("Hello nested interface");}
9.
10. public static void main(String args[]){
11. A.Message message=new Test();//upcasting here
12. message.msg();
13. }
14. }
1. interface M{
2. class A{}
3. }
Runtime Polymorphism
1. Runtime Polymorphism
2. Upcasting
3. Example of Runtime Polymorphism
4. Runtime Polymorphism with data members
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime
rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be
called is based on the object being referred to by the reference variable.
When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:
1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting
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. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splender extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splender();//upcasting
9. b.run();
10. }
11. }
In the example given below, both the classes have a datamember speedlimit, we are accessing the datamember by the reference variable of
Parent class which refers to the subclass object. Since we are accessing the datamember which is not overridden, hence it will access the
datamember of Parent class always.
1. class 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. class Animal{
2. void eat(){System.out.println("eating");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("eating fruits");}
7. }
8.
9. class BabyDog extends Dog{
10. void eat(){System.out.println("drinking milk");}
11.
12. public static void main(String args[]){
13. Animal a1,a2,a3;
14. a1=new Animal();
15. a2=new Dog();
16. a3=new BabyDog();
17.
18. a1.eat();
19. a2.eat();
20. a3.eat();
21. }
22. }
Output: eating
eating fruits
drinking Milk
Try for Output
1. class Animal{
2. void eat(){System.out.println("animal is eating...");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7. }
8.
9. class BabyDog extends Dog{
10. public static void main(String args[]){
11. Animal a=new BabyDog();
12. a.eat();
13. }}
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.
Understanding Type
1. int data=30;
1. class Dog{
2. public static void main(String args[]){
3. Dog d1;//Here d1 is a type of Dog
4. }
5. }
1. class Animal{}
2.
3. class Dog extends Animal{
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. }
7. }
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.
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
1. class Animal{
2. void eat(){System.out.println("animal is eating...");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7.
8. public static void main(String args[]){
9. Animal a=new Dog();
10. a.eat();
11. }
12. }
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the instance of Dog is also an instance of Animal.So compiler
doesn't know its type, only its base type.
nstanceof operator
1. The instanceof operator
2. Example of instanceof operator
3. Applying the instanceof operator with a variable the have null value
4. Downcasting with instanceof operator
5. Downcasting without instanceof operator
The instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).
The instanceof operator is also known as type comparison operator because it compares the instance with type. It returns either true or
false. If we apply the instanceof operator with any variable that have null value, it returns false.
Simple example of instanceof operator
Let's see the simple example of instance operator where it tests the current class.
1. class Simple{
2. public static void main(String args[]){
3. Simple s=new Simple();
4. System.out.println(s instanceof Simple);//true
5. }
6. }
Output:true
An object of subclass type is also a type of parent class. For example, if Dog extends Animal then object of Dog can be reffered by either Dog or
Animal class.
1. class Animal{}
2.
3. class Dog extends Animal{//Dog inherits Animal
4.
5. public static void main(String args[]){
6. Dog d=new Dog();
7. System.out.println(d instanceof Animal);//true
8. }
9. }
Output:true
1. class Dog{
2. public static void main(String args[]){
3. Dog d=null;
4. System.out.println(d instanceof Dog);//false
5. }
6. }
Output:false
1. Dog d=new Animal();//Compilation error
1. Dog d=(Dog)new Animal();
2. //Compiles successfully but ClassCastException is thrown at runtime
1. class Animal { }
2.
3. class Dog extends Animal {
4. static void method(Animal a) {
5. Dog d=(Dog)a;//downcasting
6. System.out.println("ok downcasting performed");
7. }
8.
9. public static void main (String [] args) {
10. Animal a=new Dog();
11. Dog.method(a);
12. }
13.
14. }
1. Animal a=new Animal();
2. Dog.method(a);
3.
4. //Now ClassCastException but not in case of instanceof operator
Let's see the real use of instanceof operator by the example given below.
1. interface Printable{}
2.
3. class A implements Printable{
4. public void a(){System.out.println("my a method");}
5. }
6. class B implements Printable{
7. public void b(){System.out.println("my a method");}
8. }
9.
10. class Call{
11. void invoke(Printable p){//upcasting
12.
13. if(p instanceof A){
14. A a=(A)p;//Downcasting
15. a.a();
16. }
17. if(p instanceof B){
18. B b=(B)p;//Downcasting
19. b.b();
20. }
21.
22. }
23. }//end of Call class
24.
25. class Test{
26. public static void main(String args[]){
27. Printable p=new B();
28. Call c=new Call();
29. c.invoke(p);
30. }
31. }
Package
1. Package
2. Example of package
3. Accessing package
1. By import packagename.*
2. By import packagename.classname
3. By fully qualified name
4. Subpackage
5. Sending class file to another directory
6. -classpath switch
7. 4 ways to load the class file or jar file
8. How to put two public class in a package
9. Static Import
10. Package class
Package can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java,
lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Package
Package is used to categorize the classes and interfaces so that they can be easily maintained.
Package provids access protection.
Package removes naming collision.
Simple example of package
1. //save as Simple.java
2.
3. package mypack;
4. public class Simple{
5. public static void main(String args[]){
6. System.out.println("Welcome to package");
7. }
8. }
If you are not using any IDE, you need to follow the syntax given below:
1. javac -d directory javafilename
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any directory name like /home (in case of
Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
1. import package.*;
2. import package.classname;
3. fully qualified name.
Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current package.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello
Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.A;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello
If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you
need to use fully qualified name every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. class B{
5. public static void main(String args[]){
6. pack.A obj = new pack.A();//using fully qualified name
7. obj.msg();
8. }
9. }
Output:Hello
If you import a package, all the classes and interface of that package will be imported excluding the classes and interfaces of the
subpackages. Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
Subpackage
Package inside the package is called the subpackage. It should be created to categorize the package further.
Let's take an example, Sun Microsystem has definded a package named java that contains many classes like System, String, Reader,
Writer, Socket etc. These classes represent a particular group e.g. Reader and Writer classes are for Input/Output operation, Socket
and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java package into subpackages such as
lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in net packages and so on.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the class file resides.
To run this program from e:\source directory, you can use -classpath switch of java that tells where to look for class file. For example:
Temporary
o By setting the classpath in the command prompt
o By -classpath switch
Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file in the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved by the public class name.
1. //save as C.java otherwise Compilte Time Error
2.
3. class A{}
4. class B{}
5. public class C{}
1. //save as A.java
2.
3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}
Static Import:
The static import feature of Java 5 facilitate the java programmer to access any static member of a class directly. There is no need to qualify it by
the class name.
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.
1. import static java.lang.System.*;
2. class StaticImportExample{
3. public static void main(String args[]){
4.
5. out.println("Hello");//Now no need of System.out
6. out.println("Java");
7.
8. }
9. }
10.
Output:Hello
Java
Package class
The package class provides methods to get information about the specification and implementation of a package. It provides methods such as
getName(), getImplementationTitle(), getImplementationVendor(), getImplementationVersion() etc.
1. class PackageInfo{
2. public static void main(String args[]){
3.
4. Package p=Package.getPackage("java.lang");
5.
6. System.out.println("package name: "+p.getName());
7.
8. System.out.println("Specification Title: "+p.getSpecificationTitle());
9. System.out.println("Specification Vendor: "+p.getSpecificationVendor());
10. System.out.println("Specification Version: "+p.getSpecificationVersion());
11.
12. System.out.println("Implementaion Title: "+p.getImplementationTitle());
13. System.out.println("Implementation Vendor: "+p.getImplementationVendor());
14. System.out.println("Implementation Version: "+p.getImplementationVersion());
15. System.out.println("Is sealed: "+p.isSealed());
16.
17.
18. }
19. }
Output:package name: java.lang
Specification Title: Java Plateform API Specification
Specification Vendor: Sun Microsystems, Inc.
Specification Version: 1.6
Implemenation Title: Java Runtime Environment
Implemenation Vendor: Sun Microsystems, Inc.
Implemenation Version: 1.6.0_30
IS sealed: false
Access Modifiers
1. private access modifier
2. Role of private constructor
3. default access modifier
4. protected access modifier
5. public access modifier
6. Applying access modifer with method overriding
There are two types of modifiers in java: access modifier and non-access modifier. The access modifiers specifies accessibility
(scope) of a datamember, method, constructor or class.
1. private
2. default
3. protected
4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will learn access modifiers.
1) private
The private access modifier is accessible only within class.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }
1. class A{
2. private A(){}//private constructor
3.
4. void msg(){System.out.println("Hello java");}
5. }
6.
7. public class Simple{
8. public static void main(String args[]){
9. A obj=new A();//Compile Time Error
10. }
11. }
2) default
If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package.
1. //save by A.java
2.
3. package pack;
4. class A{
5. void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();//Compile Time Error
9. obj.msg();//Compile Time Error
10. }
11. }
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.
3) protected
The protected access modifier is accessible within package and outside the package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. protected void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B extends A{
7. public static void main(String args[]){
8. B obj = new B();
9. obj.msg();
10. }
11. }
Output:Hello
4) public
The public access modifier is accessible everywhere. It has the widest scope among all other modiers.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello
Understanding all java access modifiers
Access Modifier within class within package outside package by subclass only outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
If you are overriding any method, overriden method (i.e. declared in subclass) must not be more restrictive.
1. class A{
2. protected void msg(){System.out.println("Hello java");}
3. }
4.
5. public class Simple extends A{
6. void msg(){System.out.println("Hello java");}//C.T.Error
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. obj.msg();
10. }
11. }
The default modifier is more restrictive than protected. That is why there is compile time error.
Encapsulation in Java
Encapsulation is a process of wrapping code and data together into a single unit e.g. capsule i.e mixed of several medicines.
We can create a fully encapsulated class by making all the data members of the class private. Now we can use setter and getter
methods to set and get the data in it.
Advantage of Encapsulation
By providing only setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data. Suppose you want to set the value of id i.e. greater than 100 only, you can write the logic
inside the setter method.
Let's see the simple example of encapsulation that has only one field with its setter and getter methods.
1. //save as Student.java
2.
3. package com.javatpoint;
4. public class student{
5. private string name;
6.
7. public String getName(){
8. return name;
9. }
10. public void setName(String name){
11. this.name=name
12. }
13. }
1. //save as Test.java
2. package com.javatpoint;
3. class Test
4. public static void main(){
5. Student s=new Student();
6. s.setname("vijay");
7. System.out.println(s.getName());
8. }
9. }
The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable
can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type like Employee,Student etc, we can
use Object class reference to refer that object. For example:
1. Object obj=getObject();//we don't what object would be returned from this method
The Object class provides some common behaviours to all the objects such as object can be compared, object can be cloned, object
can be notified etc.
Methods of Object class
The Object class provides many methods. They are as follows:
Method Description
returns the Class class object of this object. The Class class can further be used to get the
public final Class getClass()
metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws causes the current thread to wait for the specified miliseconds, until another thread
InterruptedException notifies (invokes notify() or notifyAll() method).
public final void wait(long timeout,int nanos)throws causes the current thread to wait for the specified miliseconds and nanoseconds, until
InterruptedException another thread notifies (invokes notify() or notifyAll() method).
causes the current thread to wait, until another thread notifies (invokes notify() or
public final void wait()throws InterruptedException
notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage collected.
The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an
object.
The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement
Cloneable interface, clone() method generates CloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as follows:
1. protected Object clone() throws CloneNotSupportedException
The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new
keyword, it will take a lot of processing to be performed that is why we use object cloning.
Advantage of Object cloning
1. class Student implements Cloneable{
2. int rollno;
3. String name;
4.
5. Student(int rollno,String name){
6. this.rollno=rollno;
7. this.name=name;
8. }
9.
10. public Object clone()throws CloneNotSupportedException{
11. return super.clone();
12. }
13.
14. public static void main(String args[]){
15. try{
16. Student s1=new Student(101,"amit");
17.
18. Student s2=(Student)s1.clone();
19.
20. System.out.println(s1.rollno+" "+s1.name);
21. System.out.println(s2.rollno+" "+s2.name);
22.
23. }catch(CloneNotSupportedException c){}
24.
25. }
26. }
Output:101 amit
101 amit
download the example of object cloning
As you can see in the above example, both reference variables have the same value. Thus, the clone() copies the values of an object to
another. So we don't need to write explicit code to copy the value of an object to another.
If we create another object by new keyword and assign the values of another object to this one, it will require a lot of processing on
this object. So to save the extra processing task we use clone() method.
Array in Java
Normally, array is a collection of similar type of elements that have contigious memory location.
In java, array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can
store only fixed elements in an array.
Advantage of Array
Code Optimization: It makes the code optimized, we can retrive or sort the data easily.
Random access: We can get any data located at any index position.
Disadvantage of Array
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection
framework is used in java.
Types of Array
1. dataType[] arrayRefVar; (or)
2. dataType []arrayRefVar; (or)
3. dataType arrayRefVar[];
1. arrayRefVar=new datatype[size];
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array.
1. class B{
2. public static void main(String args[]){
3.
4. int a[]=new int[5];//declaration and instantiation
5. a[0]=10;//initialization
6. a[1]=20;
7. a[2]=70;
8. a[3]=40;
9. a[4]=50;
10.
11. //printing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14.
15. }}
Output:10
20
70
40
50
We can declare, instantiate and initialize the java array together by:
1. int a[]={33,3,4,5};//declaration, instantiation and initialization
1. class B{
2. public static void main(String args[]){
3.
4. int a[]={33,3,4,5};//declaration, instantiation and initialization
5.
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9.
10. }}
Output:33
3
4
5
We can pass the array in the method so that we can reuse the same logic on any array.
Let's see the simple example to get minimum number of an array using method.
1. class B{
2. static void min(int arr[]){
3. int min=arr[0];
4. for(int i=1;i<arr.length;i++)
5. if(min>arr[i])
6. min=arr[i];
7.
8. System.out.println(min);
9. }
10.
11. public static void main(String args[]){
12.
13. int a[]={33,3,4,5};
14. min(a);//passing array in the method
15.
16. }}
Output:3
Multidimensional array
In such case, data is stored in row and column based index (also known as matrix form).
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
1. int[][] arr=new int[3][3];//3 row and 3 column
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
1. class B{
2. public static void main(String args[]){
3.
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.
7. //printing 2D array
8. for(int i=0;i<3;i++){
9. for(int j=0;j<3;j++){
10. System.out.print(arr[i][j]+" ");
11. }
12. System.out.println();
13. }
14.
15. }}
Output:1 2 3
2 4 5
4 4 5
In java, array is an object. For array object, an proxy class is created whose name can be obtained by getClass().getName() method on
the object.
1. class B{
2. public static void main(String args[]){
3.
4. int arr[]={4,4,5};
5.
6. Class c=arr.getClass();
7. String name=c.getName();
8.
9. System.out.println(name);
10. }
11.
12. }}
Output:[I
Copying an array
1. class ArrayCopyDemo {
2. public static void main(String[] args) {
3. char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
4. 'i', 'n', 'a', 't', 'e', 'd' };
5. char[] copyTo = new char[7];
6.
7. System.arraycopy(copyFrom, 2, copyTo, 0, 7);
8. System.out.println(new String(copyTo));
9. }
10. }
Output:caffein
Addition 2 matrices
1. class AE{
2. public static void main(String args[]){
3. //creating two matrices
4. int a[][]={{1,3,4},{3,4,5}};
5. int b[][]={{1,3,4},{3,4,5}};
6.
7. //creating another matrix to store the sum of two matrices
8. int c[][]=new int[2][3];
9.
10. //adding and printing addition of 2 matrices
11. for(int i=0;i<2;i++){
12. for(int j=0;j<3;j++){
13. c[i][j]=a[i][j]+b[i][j];
14. System.out.print(c[i][j]+" ");
15. }
16. System.out.println();//new line
17. }
18.
19. }}
Output:2 6 8
6 8 10
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8.
9. public static void main(String args[]){
10. Operation op=new Operation();
11.
12. System.out.println("before change "+op.data);
13. op.change(500);
14. System.out.println("after change "+op.data);
15.
16. }
17. }
1. class Operation2{
2. int data=50;
3.
4. void change(Operation op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7.
8.
9. public static void main(String args[]){
10. Operation2 op=new Operation2();
11.
12. System.out.println("before change "+op.data);
13. op.change(op);//passing object
14. System.out.println("after change "+op.data);
15.
16. }
17. }
1. strictfp class A{}//strictfp applied on class
1. strictfp interface M{}//strictfp applied on interface
1. class A{
2. void m(){}//strictfp applied on method
3. }
1. class B{
2. strictfp int data=10;//modifier strictfp not allowed here
3. }
1. class B{
2. strictfp B(){}//modifier strictfp not allowed here
3. }
1. package com.abc;
2. /** This class is a user-defined class that contains one methods cube.*/
3.
4. public class M{
5.
6. /** The cube method prints cube of the given number */
7. public static void cube(int n){System.out.println(n*n*n);}
8. }
To create the document API, you need to use the javadoc tool followed by java file name. There is no need to compile the javafile.
javadoc M.java
to generate the document api. Now, there will be created a lot of html files. Open the index.html file to get the information about the
classes.
The command-line argument is an argument passed at the time of running the java program. The argument can be received in the program and
used as an input. So, it provides an convenient way to check out the behaviour of the program on different values. You can pass N numbers of
arguments from the command prompt.
1. class A{
2. public static void main(String args[]){
3.
4. System.out.println("first argument is: "+args[0]);
5.
6. }
7. }
1. compile by > javac A.java
2.
3. run by > java A sonoo
1. class A{
2. public static void main(String args[]){
3.
4. for(int i=0;i<args.length;i++)
5. System.out.println(args[i]);
6.
7. }
8. }
1. compile by > javac A.java
2.
3. run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc
String Handling
String Handling provides a lot of concepts that can be performed on a string such as concatenating string, comparing string, substring etc.
In java, string is basically an immutable object. We will discuss about immutable string later. Let's first understand what is string and how we can
create the string object.
String
Generally string is a sequence of characters. But in java, string is an object. String class is used to create string object.
Do You Know ?
1. By string literal
2. By new keyword
1) String literal:
String literal is created by double quote.For Example:
1. String s="Hello";
Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the
pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.For example:
1. String s1="Welcome";
2. String s2="Welcome";//no new object will be created
In the above example only one object will be created.First time JVM will find no string object with the name "Welcome" in string constant
pool,so it will create a new object.Second time it will find the string with the name "Welcome" in string constant pool,so it will not create new
object whether will return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool inside the Heap memory.
2) By new keyword:
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new String object in normal(nonpool) Heap memory and the literal "Welcome" will be placed in the string
constant pool.The variable s will refer to the object in Heap(nonpool).
Concept of String
Immutable String
String Comparison
String Concatenation
Concept of Substring
String class methods and its usage
StringBuffer class
StringBuilder class
Creating Immutable class
Immutable String:
In java, strings are immutable (unmodifiable) objects.For example
1. class Simple{
2. public static void main(String args[]){
3.
4. String s="Sachin";
5. s.concat(" Tendulkar");//concat() method appends the string at the end
6. System.out.println(s);//will print Sachin because strings are immutable objects
7. }
8. }
Output:Sachin
As you can see in the above figure that two objects will be created but no reference variable refers to "Sachin Tendulkar".But if we explicitely
assign it to the reference variable, it will refer to "Sachin Tendulkar" object.For example:
1. class Simple{
2. public static void main(String args[]){
3.
4. String s="Sachin";
5. s=s.concat(" Tendulkar");
6. System.out.println(s);
7. }
8. }
Output:Sachin Tendulkar
We can compare two given on the basis of content and reference. It is used in authentication (equals() method), sorting (compareTo()
method) etc.
1. By equals() method
2. By = = operator
3. By compareTo() method
1) By equals() method:
equals() method compares the original content of the string.It compares values of string for equality.String class provides two methods:
public boolean equals(Object another){} compares this string to the specified object.
public boolean equalsIgnoreCase(String another){} compares this String to another String, ignoring case.
1. //<b><i>Example of equals(Object) method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s1="Sachin";
7. String s2="Sachin";
8. String s3=new String("Sachin");
9. String s4="Saurav";
10.
11. System.out.println(s1.equals(s2));//true
12. System.out.println(s1.equals(s3));//true
13. System.out.println(s1.equals(s4));//false
14. }
15. }
Output:true
true
false
1. //<b><i>Example of equalsIgnoreCase(String) method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s1="Sachin";
7. String s2="SACHIN";
8.
9. System.out.println(s1.equals(s2));//false
10. System.out.println(s1.equalsIgnoreCase(s3));//true
11. }
12. }
Output:false
true
2) By == operator:
The = = operator compares references not values.
1. //<b><i>Example of == operator</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s1="Sachin";
7. String s2="Sachin";
8. String s3=new String("Sachin");
9.
10. System.out.println(s1==s2);//true (because both refer to same instance)
11. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
12. }
13. }
Output:true
false
3) By compareTo() method:
compareTo() method compares values and returns an int which tells if the values compare less than, equal, or greater than.
1. //<b><i>Example of compareTo() method:</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s1="Sachin";
7. String s2="Sachin";
8. String s3="Ratan";
9.
10. System.out.println(s1.compareTo(s2));//0
11. System.out.println(s1.compareTo(s3));//1(because s1>s3)
12. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
13. }
14. }
Output:0
1
-1
1. //Example of string concatenation operator
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin"+" Tendulkar";
7. System.out.println(s);//Sachin Tendulkar
8. }
9. }
Output:Sachin Tendulkar
1. String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();
String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.String concatenation operator
produces a new string by appending the second operand onto the end of the first operand.The string concatenation operator can concat not
only string but primitive values also.For Example:
1. class Simple{
2. public static void main(String args[]){
3.
4. String s=50+30+"Sachin"+40+40;
5. System.out.println(s);//80Sachin4040
6. }
7. }
Output:80Sachin4040
Note:If either operand is a string, the resulting operation will be string concatenation. If both operands are numbers, the operator will perform
an addition.
2) By concat() method
concat() method concatenates the specified string to the end of current string.
1. //<b><i>Example of concat(String) method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s1="Sachin ";
7. String s2="Tendulkar";
8.
9. String s3=s1.concat(s2);
10.
11. System.out.println(s3);//Sachin Tendulkar
12. }
13. }
Output:Sachin Tendulkar
Substring in Java
A part of string is called substring. In other words, substring is a subset of another string.
In case of substring startIndex starts from 0 and endIndex starts from 1 or startIndex is inclusive and endIndex is exclusive.
You can get substring from the given String object by one of the two methods:
1. public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified
startIndex (inclusive).
2. public String substring(int startIndex,int endIndex): This method returns new String object containing the substring of the given string
from specified startIndex to endIndex.
In case of string:
1. //Example of substring() method
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin Tendulkar";
7. System.out.println(s.substring(6));//Tendulkar
8. System.out.println(s.substring(0,6));//Sachin
9. }
10. }
Output:Tendulkar
Sachin
Method Description
1)public boolean equals(Object anObject) Compares this string to the specified object.
2)public boolean equalsIgnoreCase(String another) Compares this String to another String, ignoring case.
3)public String concat(String str) Concatenates the specified string to the end of this string.
4)public int compareTo(String str) Compares two strings and returns int
5)public int compareToIgnoreCase(String str) Compares two strings, ignoring case differences.
6)public String substring(int beginIndex) Returns a new string that is a substring of this string.
7)public String substring(int beginIndex,int endIndex) Returns a new string that is a substring of this string.
8)public String toUpperCase() Converts all of the characters in this String to upper case
9)public String toLowerCase() Converts all of the characters in this String to lower case.
10)public String trim() Returns a copy of the string, with leading and trailing whitespace omitted.
11)public boolean startsWith(String prefix) Tests if this string starts with the specified prefix.
12)public boolean endsWith(String suffix) Tests if this string ends with the specified suffix.
13)public char charAt(int index) Returns the char value at the specified index.
15)public String intern() Returns a canonical representation for the string object.
First seven methods have already been discussed.Now Let's take the example of other methods:
1. //<b><i>Example of toUpperCase() and toLowerCase() method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin";
7. System.out.println(s.toUpperCase());//SACHIN
8. System.out.println(s.toLowerCase());//sachin
9. System.out.println(s);//Sachin(no change in original)
10. }
11. }
Output:SACHIN
sachin
Sachin
trim() method
1. //<b><i>Example of trim() method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s=" Sachin ";
7. System.out.println(s);// Sachin
8. System.out.println(s.trim());//Sachin
9. }
10. }
Output: Sachin
Sachin
1. //<b><i>Example of startsWith() and endsWith() method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin";
7. System.out.println(s.startsWith("Sa"));//true
8. System.out.println(s.startsWith("n"));//true
9. }
10. }
Output:true
true
charAt() method
1. //<b><i>Example of charAt() method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin";
7. System.out.println(s.charAt(0));//S
8. System.out.println(s.charAt(3));//h
9. }
10. }
Output:S
h
length() method
1. //<b><i>Example of length() method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s="Sachin";
7. System.out.println(s.length());//6
8. }
9. }
Output:6
intern() method
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method,
then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
1. //<b><i>Example of length() method</i></b>
2.
3. class Simple{
4. public static void main(String args[]){
5.
6. String s=new String("Sachin");
7. String s2=s.intern();
8. System.out.println(s2);//Sachin
9. }
10. }
Output:Sachin
StringBuffer class:
The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class is same as String except it is mutable i.e. it can be
changed.
Note: StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously .So it is safe and will result in an order.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello ");
5. sb.append("Java");//now original string is changed
6.
7. System.out.println(sb);//prints Hello Java
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello ");
5. sb.insert(1,"Java");//now original string is changed
6.
7. System.out.println(sb);//prints HJavaello
8. }
9. }
Example of replace() method of StringBuffer class
The replace() method replaces the given string from the specified beginIndex and endIndex.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.replace(1,3,"Java");
6.
7. System.out.println(sb);//prints HJavalo
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.delete(1,3);
6.
7. System.out.println(sb);//prints Hlo
8. }
9. }
Example of reverse() method of StringBuffer class
The reverse() method of StringBuilder class reverses the current string.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer("Hello");
5. sb.reverse();
6.
7. System.out.println(sb);//prints olleH
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10. sb.append("java is my favourite language");
11. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12. }
13. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuffer sb=new StringBuffer();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10. sb.append("java is my favourite language");
11. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12.
13. sb.ensureCapacity(10);//now no change
14. System.out.println(sb.capacity());//now 34
15.
16. sb.ensureCapacity(50);//now (34*2)+2
17. System.out.println(sb.capacity());//now 70
18.
19. }
20. }
tringBuilder class:
The StringBuilder class is used to create mutable (modifiable) string. The StringBuilder class is same as StringBuffer class except that it is non-
synchronized. It is available since JDK1.5.
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello ");
5. sb.insert(1,"Java");//now original string is changed
6.
7. System.out.println(sb);//prints HJavaello
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder("Hello");
5. sb.delete(1,3);
6.
7. System.out.println(sb);//prints Hlo
8. }
9. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10. sb.append("java is my favourite language");
11. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12. }
13. }
1. class A{
2. public static void main(String args[]){
3.
4. StringBuilder sb=new StringBuilder();
5. System.out.println(sb.capacity());//default 16
6.
7. sb.append("Hello");
8. System.out.println(sb.capacity());//now 16
9.
10. sb.append("java is my favourite language");
11. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
12.
13. sb.ensureCapacity(10);//now no change
14. System.out.println(sb.capacity());//now 34
15.
16. sb.ensureCapacity(50);//now (34*2)+2
17. System.out.println(sb.capacity());//now 70
18.
19. }
20. }
1. public final class Employee{
2. final String pancardNumber;
3.
4. public Employee(String pancardNumber){
5. this.pancardNumber=pancardNumber;
6. }
7.
8. public String getPancardNumber(){
9. return pancardNumber;
10. }
11.
12. }
The instance variable of the class is final i.e. we cannot change the value of it after creating an object.
The class is final so we cannot create the subclass.
There is no setter methods i.e. we have no option to change the value of the instance variable.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method,
returns the desired output, it can be the state of an object etc. depends on your implementation.
1. class Student{
2. int rollno;
3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
7. this.rollno=rollno;
8. this.name=name;
9. this.city=city;
10. }
11.
12. public static void main(String args[]){
13. Student s1=new Student(101,"Raj","lucknow");
14. Student s2=new Student(102,"Vijay","ghaziabad");
15.
16. System.out.println(s1);//compiler writes here s1.toString()
17. System.out.println(s2);//compiler writes here s2.toString()
18. }
19. }
Output:Student@1fee6fc
Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects but I want to print the values of these objects.
Since java compiler internally calls toString() method, overriding this method will return the specified values. Let's understand it with the
example given below:
1. class Student{
2. int rollno;
3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
7. this.rollno=rollno;
8. this.name=name;
9. this.city=city;
10. }
11.
12. public String toString(){//overriding the toString() method
13. return rollno+" "+name+" "+city;
14. }
15. public static void main(String args[]){
16. Student s1=new Student(101,"Raj","lucknow");
17. Student s2=new Student(102,"Vijay","ghaziabad");
18.
19. System.out.println(s1);//compiler writes here s1.toString()
20. System.out.println(s2);//compiler writes here s2.toString()
21. }
22. }
StringTokenizer in Java
1. StringTokenizer
2. Methods of StringTokenizer
3. Example of StringTokenizer
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class. We will discuss
about the StreamTokenizer class in I/O chapter.
Constructor Description
StringTokenizer(String str, String delim) creates StringTokenizer with specified string and delimeter.
StringTokenizer(String str, String delim, creates StringTokenizer with specified string, delimeter and returnValue. If return value is true,
delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate
boolean returnValue)
tokens.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
Let's see the simple example of StringTokenizer class that tokenizes a string "my name is khan" on the basis of whitespace.
1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }
Output:my
name
is
khan
1. import java.util.*;
2.
3. public class Test {
4. public static void main(String[] args) {
5. StringTokenizer st = new StringTokenizer("my,name,is,khan");
6.
7. // printing next token
8. System.out.println("Next token is : " + st.nextToken(","));
9. }
10. }
Output:Next token is : my
StringTokenizer class is deprecated now. It is recommended to use split() method of String class or regex (Regular Expression).
In this page, we will know about exception, its type and the difference between checked and unchecked exceptions.
Exception
Exception Handling
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of the code will not be executed i.e.
statement 6 to 10 will not run. If we perform exception handling, rest of the exception will be executed. That is why we use exception handling.
Do You Know ?
1. Checked Exception
2. Unchecked Exception
3. Error
1)Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException
etc. Checked exceptions are checked at compile-time.
2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3)Error
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
Use of try-catch block in Exception handling:
try block
Enclose the code that might throw an exception in try block. It must be used within the method and must be followed by either catch or finally
block.
1. try{
2. ...
3. }catch(Exception_class_Name reference){}
1. try{
2. ...
3. }finally{}
catch block
Catch block is used to handle the Exception. It must be used after the try block.
Problem without exception handling
1. class Simple{
2. public static void main(String args[]){
3. int data=50/0;
4.
5. System.out.println("rest of the code...");
6. }
7. }
As displayed in the above example, rest of the code is not executed i.e. rest of the code... statement is not printed. Let's see what happens
behind the scene:
What happens behind the code int a=50/0;
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that
performs the following tasks:
But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=50/0;
5.
6. }catch(ArithmeticException e){System.out.println(e);}
7.
8. System.out.println("rest of the code...");
9. }
10. }
Output:task1 completed
rest of the code...
Rule:At a time only one Exception is occured and at a time only one catch block is executed.
Rule:All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch
for Exception .
1. class Excep4{
2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(Exception e){System.out.println("common task completed");}
8. catch(ArithmeticException e){System.out.println("task1 is completed");}
9. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Output:Compile-time error
Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....
Example:
1. <b><i>Example of nested try block</i></b>
2.
3. class Excep6{
4. public static void main(String args[]){
5. try{
6. try{
7. System.out.println("going to divide");
8. int b =39/0;
9. }catch(ArithmeticException e){System.out.println(e);}
10.
11. try{
12. int a[]=new int[5];
13. a[5]=4;
14. }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
15.
16. System.out.println("other statement);
17. }catch(Exception e){System.out.println("handeled");}
18.
19. System.out.println("normal flow..");
20. }
21. }
finally block
The finally block is a block that is always executed. It is mainly used to perform some important tasks such as closing connection, stream etc.
Note:Before terminating the program, JVM executes finally block(if any).
Note:finally must be followed by try or catch block.
case 1
Program in case exception does not occur
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Output:5
finally block is always executed
rest of the code...
case 2
Program in case exception occured but not handled
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
case 3
Program in case exception occured and handled
1. class Simple{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(ArithmeticException e){System.out.println(e);}
8.
9. finally{System.out.println("finally block is always executed");}
10.
11. System.out.println("rest of the code...");
12. }
13. }
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes
the process to abort).
throw keyword
The throw keyword is used to explictily throw an exception.
We can throw either checked or uncheked exception. The throw keyword is mainly used to throw custom exception. We will see custom
exceptions later.
1. class Excep13{
2.
3. static void validate(int age){
4. if(age<18)
5. throw new ArithmeticException("not valid");
6. else
7. System.out.println("welcome to vote");
8. }
9.
10. public static void main(String args[]){
11. validate(13);
12. System.out.println("rest of the code...");
13. }
14. }
Exception propagation:
An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method,If not caught
there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call
stack.This is called exception propagation.
1. class Simple{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handled");}
12. }
13. public static void main(String args[]){
14. Simple obj=new Simple();
15. obj.p();
16. System.out.println("normal flow...");
17. }
18. }
Output:exception handled
normal flow...
In the above example exception occurs in m() method where it is not handled,so it is propagated to previous n() method where it is not
handled, again it is propagated to p() method where exception is handled.
Exception can be handled in any method in call stack either in main() method,p() method,n() method or m() method.
Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).
Program which describes that checked exceptions are not propagated
1. class Simple{
2. void m(){
3. throw new java.io.IOException("device error");//checked exception
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handeled");}
12. }
13. public static void main(String args[]){
14. Simple obj=new Simple();
15. obj.p();
16. System.out.println("normal flow");
17. }
18. }
throws keyword:
The throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better
for the programmer to provide the exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is
programmers fault that he is not performing check up before the code being used.
1. void method_name() throws exception_class_name{
2. ...
3. }
Program which describes that checked exceptions can be propagated by throws keyword.
1. import java.io.IOException;
2. class Simple{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Simple obj=new Simple();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
Output:exception handled
normal flow...
Rule: If you are calling a method that declares an exception, you must either caught or declare the exception.
There are two cases:
1. Case1:You caught the exception i.e. handle the exception using try/catch.
2. Case2:You declare the exception i.e. specifying throws with the method.
In case you handle the exception, the code will be executed fine whether exception occurs during the program or not.
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7.
8.
9. class Test{
10. public static void main(String args[]){
11. try{
12. Test t=new Test();
13. t.method();
14. }catch(Exception e){System.out.println("exception handled");}
15.
16. System.out.println("normal flow...");
17. }
18. }
Output:exception handled
normal flow...
A)In case you declare the exception, if exception does not occur, the code will be executed fine.
B)In case you declare the exception if exception occures, an exception will be thrown at runtime because throws does not handle the
exception.
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7.
8.
9. class Test{
10. public static void main(String args[])throws IOException{//declare exception
11. Test t=new Test();
12. t.method();
13.
14. System.out.println("normal flow...");
15. }
16. }
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7.
8.
9. class Test{
10. public static void main(String args[])throws IOException{//declare exception
11. Test t=new Test();
12. t.method();
13.
14. System.out.println("normal flow...");
15. }
16. }
Output:Runtime Exception
4)throw is used within the method. throws is used with the method signature.
1) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception.
1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg()throws IOException{
8. System.out.println("child");
9. }
10. public static void main(String args[]){
11. Parent p=new Child();
12. p.msg();
13. }
14. }
2) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception
but can declare unchecked exception.
1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg()throws ArithmeticException{
8. System.out.println("child");
9. }
10. public static void main(String args[]){
11. Parent p=new Child();
12. p.msg();
13. }
14. }
Output:child
1) Rule: If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no
exception but cannot declare parent exception.
1. import java.io.*;
2. class Parent{
3. void msg()throws ArithmeticException{System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg()throws Exception{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new Child();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:Compile Time Error
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg()throws Exception{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new Child();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:child
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg()throws ArithmeticException{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new Child();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:child
1. import java.io.*;
2. class Parent{
3. void msg()throws Exception{System.out.println("parent");}
4. }
5.
6. class Child extends Parent{
7. void msg(){System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new Child();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Output:child
Custom Exception :
If you are creating your own Exception that is known as custom exception or user-defined exception.
1. <b><i>//Example of custom exception</i></b>
2.
3. class InvalidAgeException extends Exception{
4. InvalidAgeException(String s){
5. super(s);
6. }
7. }
1. class Excep13{
2.
3. static void validate(int age)throws InvalidAgeException{
4. if(age<18)
5. throw new InvalidAgeException("not valid");
6. else
7. System.out.println("welcome to vote");
8. }
9.
10. public static void main(String args[]){
11. try{
12. validate(13);
13. }catch(Exception m){System.out.println("Exception occured: "+m);}
14.
15. System.out.println("rest of the code...");
16. }
17. }
A class declared inside a class is known as nested class. We use nested classes to logically group classes in one place so that it can be more
readable and maintainable code. Moreover, it can access all the members of outer class including private members.
Syntax of Nested class
1. class Outer_class_Name{
2. ...
3. class Nested_class_Name{
4. ...
5. }
6. ...
7. }
Do You Know ?
What is the internal code generated by the compiler for member inner class ?
What are the two ways to create annonymous inner class ?
Can we access the non-final local variable inside the local inner class ?
How to access the static nested class ?
Can we define an interface within the class ?
Can we define a class within the interface ?
Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class
including private.
Nested classes can lead to more readable and maintainable code because it logically group classes in one place only.
Code Optimization as we need less code to write.
Que) What is the difference between nested class and inner class?
Inner class is a part of nested class. Non-static nested classes are known as nested classes.
Types of Nested class:
There are two types of nested classes non-static and static nested classes.The non-static nested classes are also known as inner classes.
Nested class
Member inner class
Annonymous inner class
Local Inner class
static nested class
Nested interface
In this example, we are invoking the method of member inner class from the display method of Outer class.
1. class Outer{
2. private int data=30;
3. class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6.
7. void display(){
8. Inner in=new Inner();
9. in.msg();
10. }
11. public static void main(String args[]){
12. Outer obj=new Outer();
13. obj.display();
14. }
15. }
Output:data is 30
1. import java.io.PrintStream;
2.
3. class Outer$Inner
4. {
5. final Outer this$0;
6. Outer$Inner()
7. { super();
8. this$0 = Outer.this;
9. }
10.
11. void msg()
12. {
13. System.out.println((new StringBuilder()).append("data is ")
14. .append(Outer.access$000(Outer.this)).toString());
15. }
16.
17. }
In this example, we are invoking the msg() method of Inner class from outside the outer class i.e. Test class.
1. <b><i>//Program of member inner class that is invoked outside a class</i></b>
2.
3. class Outer{
4. private int data=30;
5. class Inner{
6. void msg(){System.out.println("data is"+data);}
7. }
8. }
9.
10. class Test{
11. public static void main(String args[]){
12. Outer obj=new Outer();
13. Outer.Inner in=obj.new Inner();
14. in.msg();
15. }
16. }
Output:data is 30
1. abstract class Person{
2. abstract void eat();
3. }
4.
5. class Emp{
6. public static void main(String args[]){
7. Person p=new Person(){
8. void eat(){System.out.println("nice fruits");}
9. };
10.
11. p.eat();
12. }
13. }
Output:nice fruits
1. Person p=new Person(){
2. void eat(){System.out.println("nice fruits");}
3. };
4.
5. }
6. }
1. A class is created but its name is decided by the compiler which extends the Person class and provides the implementation of the eat()
method.
2. An object of Annonymous class is created that is reffered by p reference variable of Person type. As you know well that Parent class
reference variable can refer the object of Child class.
The internal code generated by the compiler for annonymous inner class
1. import java.io.PrintStream;
2. static class Emp$1 extends Person
3. {
4. Emp$1(){}
5.
6. void eat()
7. {
8. System.out.println("nice fruits");
9. }
10. }
1. interface Eatable{
2. void eat();
3. }
4.
5. class Emp{
6. public static void main(String args[]){
7.
8. Eatable e=new Eatable(){
9. public void eat(){System.out.println("nice fruits");}
10. };
11. e.eat();
12. }
13. }
Output:nice fruits
What does the compiler for annonymous inner class created by interface
It performs two main tasks behind this code:
1. Eatable p=new Eatable(){
2. void eat(){System.out.println("nice fruits");}
3. };
4.
5. }
6. }
1. A class is created but its name is decided by the compiler which implements the Eatable interface and provides the implementation of
the eat() method.
2. An object of Annonymous class is created that is reffered by p reference variable of Eatable type. As you know well that Parent class
reference variable can refer the object of Child class.
The internal code generated by the compiler for annonymous inner class created by interface
1. import java.io.PrintStream;
2. static class Emp$1 implements Eatable
3. {
4. Emp$1(){}
5.
6. void eat(){System.out.println("nice fruits");}
7. }
1. class Simple{
2. private int data=30;//instance variable
3. void display(){
4. class Local{
5. void msg(){System.out.println(data);}
6. }
7. Local l=new Local();
8. l.msg();
9. }
10. public static void main(String args[]){
11. Simple obj=new Simple();
12. obj.display();
13. }
14. }
Output:30
1. import java.io.PrintStream;
2. class Simple$1Local
3. {
4. final Simple this$0;
5.
6. Simple$1Local()
7. {
8. super();
9. this$0 = Simple.this;
10. }
11. void msg()
12. {
13. System.out.println(Simple.access$000(Simple.this));
14. }
15.
16. }
1. class Simple{
2. private int data=30;//instance variable
3. void display(){
4. int value=50;//local variable must be final
5. class Local{
6. void msg(){System.out.println(value);}//C.T.Error
7. }
8. Local l=new Local();
9. l.msg();
10. }
11. public static void main(String args[]){
12. Simple obj=new Simple();
13. obj.display();
14. }
15. }
1. class Simple{
2. private int data=30;//instance variable
3. void display(){
4. final int value=50;//local variable must be final
5. class Local{
6. void msg(){System.out.println(data+" "+value);}//ok
7. }
8. Local l=new Local();
9. l.msg();
10. }
11. public static void main(String args[]){
12. Simple obj=new Simple();
13. obj.display();
14. }
15. }
Output:30 50
1. class Outer{
2. static int data=30;
3.
4. static class Inner{
5. void msg(){System.out.println("data is "+data);}
6. }
7.
8. public static void main(String args[]){
9. Outer.Inner obj=new Outer.Inner();
10. obj.msg();
11. }
12. }
Output:data is 30
In this example, you need to create the instance of static nested class because it has instance method msg(). But you don't need to create the
object of Outer class because nested class is static and static properties, methods or classes can be accessed without object.
1. import java.io.PrintStream;
2.
3. static class Outer$Inner
4. {
5. Outer$Inner(){}
6.
7. void msg(){
8. System.out.println((new StringBuilder()).append("data is ")
9. .append(Outer.data).toString());
10. }
11.
12. }
Program of static nested class that have static method
1. class Outer{
2. static int data=30;
3.
4. static class Inner{
5. static void msg(){System.out.println("data is "+data);}
6. }
7.
8. public static void main(String args[]){
9. Outer.Inner.msg();//no need to create the instance of static nested class
10. }
11. }
Output:data is 30
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.
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. interface interface_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
7.
1. class class_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
7.
1. interface Showable{
2. void show();
3. interface Message{
4. void msg();
5. }
6. }
7.
8. class Test implements Showable.Message{
9. public void msg(){System.out.println("Hello nested interface");}
10.
11. public static void main(String args[]){
12. Showable.Message message=new Test();//upcasting here
13. message.msg();
14. }
15. }
Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed below:.
1. public static interface Showable$Message
2. {
3. public abstract void msg();
4. }
1. class A{
2. interface Message{
3. void msg();
4. }
5. }
6.
7. class Test implements A.Message{
8. public void msg(){System.out.println("Hello nested interface");}
9.
10. public static void main(String args[]){
11. A.Message message=new Test();//upcasting here
12. message.msg();
13. }
14. }
1. interface M{
2. class A{}
3. }
Multithreading in Java
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.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two
ways:
Process-based Multitasking(Multiprocessing)
Thread-based Multitasking(Multithreading)
What is Thread?
A thread is a lightweight subprocess, a smallest unit of processing. It is a separate path of execution. It shares the memory area of process.
As shown in the above figure, thread is executed inside the process. There is context-switching between the threads. There can be multiple
processes inside the OS and one process can have multiple threads.
Do You Know ?
Why your class, which extends the Thread class, object is treated as thread ? Who is responsible for it ?
How to perform two tasks by two threads ?
How to perform multithreading by annonymous class ?
What is the Thread Schedular and what is the difference between preemptive scheduling and time slicing ?
What happens if we start a thread twice ?
What happens if we call the run() method instead of start() method ?
What is the purpose of join method ?
Why JVM terminates the daemon thread if there is no user threads remaining ?
What is the shutdown hook?
What is garbage collection ?
What is the purpose of finalize() method ?
What does gc() method ?
What is synchronization and why use synchronization ?
What is the difference between synchronized method and synchronized block ?
What are the two ways to perform static synchronization ?
What is deadlock and when it can occur ?
What is interthread-communication or cooperation ?
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
Life cycle of a Thread (Thread States)
1. Life cycle of a thread
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
A thread can be in one of the five states in the thread. According to sun, there is only 4 states new, runnable, non-runnable and terminated.
There is no running state. But for better understanding the threads, we are explaining it in the 5 states. The life cycle of the thread is controlled
by JVM. The thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1)New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
2)Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.
3)Running
The thread is in running state if the thread scheduler has selected it.
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.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements
Runnable interface.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have
only one method named run().
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }
Output:thread is running...
1. class Multi3 implements Runnable{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1);
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.
1. //<b><i>Program of performing single task by multiple threads</i></b>
2.
3. class Multi extends Thread{
4. public void run(){
5. System.out.println("task one");
6. }
7. public static void main(String args[]){
8. Multi t1=new Multi();
9. Multi t2=new Multi();
10. Multi t3=new Multi();
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 threads</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 annonymous 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.
1. //<b><i>Program of performing two tasks by two threads</i></b>
2.
3. class Simple1 extends Thread{
4. public void run(){
5. System.out.println("task one");
6. }
7. }
8.
9. class Simple2 extends Thread{
10. public void run(){
11. System.out.println("task two");
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
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
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. Runnable r1=new Runnable(){
6. public void run(){
7. System.out.println("task one");
8. }
9. };
10.
11. Runnable r2=new Runnable(){
12. public void run(){
13. System.out.println("task two");
14. }
15. };
16.
17. Thread t1=new Thread(r1);
18. Thread t2=new Thread(r1);
19.
20. t1.start();
21. t2.start();
22. }
23. }
Output:task one
task two
1. //<b><i>Program of sleep() method</i></b>
2.
3. class Multi extends Thread{
4. public void run(){
5. for(int i=1;i<5;i++){
6. try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
7. System.out.println(i);
8. }
9. }
10. public static void main(String args[]){
11. Multi t1=new Multi();
12. Multi t2=new Multi();
13.
14. t1.start();
15. t2.start();
16. }
17. }
1. <strong>Output:</strong>1
2. 1
3. 2
4. 2
5. 3
6. 3
7. 4
8. 4
9. 5
10. 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.
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. t1.start();
9. }
10. }
1. <strong>Output:</strong>running
2. Exception in thread "main" java.lang.IllegalThreadStateException
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.run();//fine, but does not start a separate call stack
8. }
9. }
1. <strong>Output:</strong>running...
1. //<b><i>Problem if you direct call run() method</i></b>
2.
3. class Multi extends Thread{
4. public void run(){
5. for(int i=1;i<5;i++){
6. try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
7. System.out.println(i);
8. }
9. }
10. public static void main(String args[]){
11. Multi t1=new Multi();
12. Multi t2=new Multi();
13.
14. t1.run();
15. t2.run();
16. }
17. }
Output:1
2
3
4
5
1
2
3
4
5
As you can see in the above program that there is no context-switching because here t1 and t2 will be treated as normal object not
thread object.
Syntax:
public void join()throws InterruptedException
1. //<b><i>Example of join() method</i></b>
2.
3. class Multi extends Thread{
4. public void run(){
5. for(int i=1;i<=5;i++){
6. try{
7. Thread.sleep(500);
8. }catch(Exception e){System.out.println(e);}
9. System.out.println(i);
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();
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. //<b><i>Example of join(long miliseconds) method</i></b>
2.
3. class Multi extends Thread{
4. public void run(){
5. for(int i=1;i<=5;i++){
6. try{
7. Thread.sleep(500);
8. }catch(Exception e){System.out.println(e);}
9. System.out.println(i);
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.
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...
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. class Multi6 extends Thread{
2. public void run(){
3. System.out.println("running...");
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.getName());
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...
The currentThread() method:
The currentThread() method returns a reference to the currently executing thread object.
public static Thread currentThread(): returns the reference of currently running thread.
1. class Multi6 extends Thread{
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
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
1. class Multi10 extends Thread{
2. public void run(){
3. System.out.println("running thread name is:"+Thread.currentThread().getName());
4. System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
5.
6. }
7. public static void main(String args[]){
8. Multi10 m1=new Multi10();
9. Multi10 m2=new Multi10();
10. m1.setPriority(Thread.MIN_PRIORITY);
11. m2.setPriority(Thread.MAX_PRIORITY);
12. m1.start();
13. m2.start();
14.
15. }
16. }
Daemon Thread
There are two types of threads user thread and daemon thread. The daemon thread is a service provider thread. It provides services to the user
thread. Its life depends on the user threads i.e. when all the user threads dies, JVM termintates this thread automatically.
It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
Its life depends on user threads.
It is a low priority thread.
Why JVM termintates the daemon thread if there is no user thread remaining?
The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why
should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.
public void setDaemon(boolean status): is used to mark the current thread as daemon thread or user thread.
public boolean isDaemon(): is used to check that current is daemon.
1. class MyThread extends Thread{
2. public void run(){
3. System.out.println("Name: "+Thread.currentThread().getName());
4. System.out.println("Daemon: "+Thread.currentThread().isDaemon());
5. }
6.
7. public static void main(String[] args){
8. MyThread t1=new MyThread();
9. MyThread t2=new MyThread();
10. t1.setDaemon(true);
11.
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. class MyThread extends Thread{
2. public void run(){
3. System.out.println("Name: "+Thread.currentThread().getName());
4. System.out.println("Daemon: "+Thread.currentThread().isDaemon());
5. }
6.
7. public static void main(String[] args){
8. MyThread t1=new MyThread();
9. MyThread t2=new MyThread();
10. t1.start();
11. t1.setDaemon(true);//will throw exception here
12. t2.start();
13. }
14. }
In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and assigned a job by the
service provider. After completion of the job, thread is contained in the thread pool again.
Better performance It saves time because there is no need to create new thread.
Where is it used?
It is used in Servlet and JSP where container creates a thread pool to process the request.
Let's see a simple example of java thread pool using executors and ThreadPoolExecutor.
1. import java.util.concurrent.ExecutorService;
2. import java.util.concurrent.Executors;
3. class WorkerThread implements Runnable {
4. private String message;
5. public WorkerThread(String s){
6. this.message=s;
7. }
8.
9. public void run() {
10. System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);
11. processmessage();
12. System.out.println(Thread.currentThread().getName()+" (End)");
13. }
14.
15. private void processmessage() {
16. try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
17. }
18. }
19.
20. public class SimpleThreadPool {
21. public static void main(String[] args) {
22. ExecutorService executor = Executors.newFixedThreadPool(5);
23. for (int i = 0; i < 10; i++) {
24. Runnable worker = new WorkerThread("" + i);
25. executor.execute(worker);
26. }
27. executor.shutdown();
28. while (!executor.isTerminated()) { }
29.
30. System.out.println("Finished all threads");
31. }
32.
33. }
1. pool-1-thread-1 (Start) message = 0
2. pool-1-thread-2 (Start) message = 1
3. pool-1-thread-3 (Start) message = 2
4. pool-1-thread-5 (Start) message = 4
5. pool-1-thread-4 (Start) message = 3
6. pool-1-thread-2 (End)
7. pool-1-thread-2 (Start) message = 5
8. pool-1-thread-1 (End)
9. pool-1-thread-1 (Start) message = 6
10. pool-1-thread-3 (End)
11. pool-1-thread-3 (Start) message = 7
12. pool-1-thread-4 (End)
13. pool-1-thread-4 (Start) message = 8
14. pool-1-thread-5 (End)
15. pool-1-thread-5 (Start) message = 9
16. pool-1-thread-2 (End)
17. pool-1-thread-1 (End)
18. pool-1-thread-4 (End)
19. pool-1-thread-3 (End)
20. pool-1-thread-5 (End)
21. Finished all threads
Shutdown Hook
The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts down normally or abruptly. Performing clean
resource means closing log file, sending some alerts or something else. So if you want to execute some code before JVM shuts down, use
shutdown hook.
When does the JVM shut down?
The JVM shuts down when:
1. public void addShutdownHook(Runnable r){}
The object of Runtime class can be obtained by calling the static factory method getRuntime(). For example:
Runtime r = Runtime.getRuntime();
Factory method
The method that returns the instance of a class is known as factory method.
1. class MyThread extends Thread{
2. public void run(){
3. System.out.println("shut down hook task completed..");
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. }
Note: The shutdown sequence can be stopped by invoking the halt(int) method of Runtime class.
1. public class Shutdown {
2. public static void main(String[] args)throws Exception {
3.
4. Runtime r=Runtime.getRuntime();
5.
6. r.addShutdownHook(new Runnable(){
7. public void run(){
8. System.out.println("shut down hook task completed..");
9. }
10. }
11. );
12.
13. System.out.println("Now main sleeping... press ctrl+c to exit");
14. try{Thread.sleep(3000);}catch (Exception e) {}
15. }
16. }
1. //<b><i>Program of performing single task by multiple threads</i></b>
2.
3. class Multi extends Thread{
4. public void run(){
5. System.out.println("task one");
6. }
7. public static void main(String args[]){
8. Multi t1=new Multi();
9. Multi t2=new Multi();
10. Multi t3=new Multi();
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 threads</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 annonymous 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.
1. //<b><i>Program of performing two tasks by two threads</i></b>
2.
3. class Simple1 extends Thread{
4. public void run(){
5. System.out.println("task one");
6. }
7. }
8.
9. class Simple2 extends Thread{
10. public void run(){
11. System.out.println("task two");
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
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
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. Runnable r1=new Runnable(){
6. public void run(){
7. System.out.println("task one");
8. }
9. };
10.
11. Runnable r2=new Runnable(){
12. public void run(){
13. System.out.println("task two");
14. }
15. };
16.
17. Thread t1=new Thread(r1);
18. Thread t2=new Thread(r1);
19.
20. t1.start();
21. t2.start();
22. }
23. }
Output:task one
task two
1. //<b><i>Program of sleep() method</i></b>
2.
3. class Multi extends Thread{
4. public void run(){
5. for(int i=1;i<5;i++){
6. try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
7. System.out.println(i);
8. }
9. }
10. public static void main(String args[]){
11. Multi t1=new Multi();
12. Multi t2=new Multi();
13.
14. t1.start();
15. t2.start();
16. }
17. }
1. <strong>Output:</strong>1
2. 1
3. 2
4. 2
5. 3
6. 3
7. 4
8. 4
9. 5
10. 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.
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. t1.start();
9. }
10. }
1. <strong>Output:</strong>running
2. Exception in thread "main" java.lang.IllegalThreadStateException
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.run();//fine, but does not start a separate call stack
8. }
9. }
1. <strong>Output:</strong>running...
1. //<b><i>Problem if you direct call run() method</i></b>
2.
3. class Multi extends Thread{
4. public void run(){
5. for(int i=1;i<5;i++){
6. try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
7. System.out.println(i);
8. }
9. }
10. public static void main(String args[]){
11. Multi t1=new Multi();
12. Multi t2=new Multi();
13.
14. t1.run();
15. t2.run();
16. }
17. }
Output:1
2
3
4
5
1
2
3
4
5
As you can see in the above program that there is no context-switching because here t1 and t2 will be treated as normal object not
thread object.
Syntax:
public void join()throws InterruptedException
1. //<b><i>Example of join() method</i></b>
2.
3. class Multi extends Thread{
4. public void run(){
5. for(int i=1;i<=5;i++){
6. try{
7. Thread.sleep(500);
8. }catch(Exception e){System.out.println(e);}
9. System.out.println(i);
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();
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. //<b><i>Example of join(long miliseconds) method</i></b>
2.
3. class Multi extends Thread{
4. public void run(){
5. for(int i=1;i<=5;i++){
6. try{
7. Thread.sleep(500);
8. }catch(Exception e){System.out.println(e);}
9. System.out.println(i);
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.
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...
Synchronization
Synchronization is the capabilility of control the access of multiple threads to any shared resource. Synchronization is better in case
we want only one thread can access the shared resource at a time.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
Cooperation (Inter-thread communication)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
In this example, there is no synchronization, so output is inconsistent. Let's see the example:
1. Class Table{
2.
3. void printTable(int n){//method not synchronized
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
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
Output: 5
10
15
20
25
100
200
300
400
500
In this program, we have created the two threads by annonymous class, so less coding is required.
1. <b><i>//Program of synchronized method by using annonymous class</i></b>
2.
3. Class Table{
4.
5. synchronized void printTable(int n){//synchronized method
6. for(int i=1;i<=5;i++){
7. System.out.println(n*i);
8. try{
9. Thread.sleep(400);
10. }catch(Exception e){System.out.println(e);}
11. }
12.
13. }
14. }
15.
16. class Use{
17. public static void main(String args[]){
18. final Table obj = new Table();//only one object
19.
20. MyThread1 t1=new MyThread1(){
21. public void run(){
22. obj.printTable(5);
23. }
24. };
25. MyThread1 t2=new MyThread1(){
26. public void run(){
27. obj.printTable(100);
28. }
29. };
30.
31. 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.
1. synchronized (object reference expression) {
2. //code block
3. }
1. <b><i>//Program of synchronized block</i></b>
2.
3. class Table{
4.
5. void printTable(int n){
6. synchronized(this){//synchronized block
7. for(int i=1;i<=5;i++){
8. System.out.println(n*i);
9. try{
10. Thread.sleep(400);
11. }catch(Exception e){System.out.println(e);}
12. }
13. }
14. }//end of the method
15. }
16.
17. class MyThread1 extends Thread{
18. Table t;
19. MyThread1(Table t){
20. this.t=t;
21. }
22. public void run(){
23. t.printTable(5);
24. }
25.
26. }
27. class MyThread2 extends Thread{
28. Table t;
29. MyThread2(Table t){
30. this.t=t;
31. }
32. public void run(){
33. t.printTable(100);
34. }
35. }
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
1. <b><i>//Program of synchronized block by using annonymous class</i></b>
2.
3. class Table{
4.
5. void printTable(int n){
6. synchronized(this){//synchronized block
7. for(int i=1;i<=5;i++){
8. System.out.println(n*i);
9. try{
10. Thread.sleep(400);
11. }catch(Exception e){System.out.println(e);}
12. }
13. }
14. }//end of the method
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.
In this example we are applying synchronized keyword on the static method to perform statis synchrnization.
1. class Table{
2.
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12.
13. class MyThread1 extends Thread{
14. public void run(){
15. Table.printTable(1);
16. }
17. }
18.
19. class MyThread2 extends Thread{
20. public void run(){
21. Table.printTable(10);
22. }
23. }
24.
25. class MyThread3 extends Thread{
26. public void run(){
27. Table.printTable(100);
28. }
29. }
30.
31.
32.
33.
34. class MyThread4 extends Thread{
35. public void run(){
36. Table.printTable(1000);
37. }
38. }
39.
40. class Use{
41. public static void main(String t[]){
42. MyThread1 t1=new MyThread1();
43. MyThread2 t2=new MyThread2();
44. MyThread3 t3=new MyThread3();
45. MyThread4 t4=new MyThread4();
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
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
1. static void printTable(int n) {
2. synchronized (Table.class) { // Synchronized block on class A
3. // ...
4. }
5. }
Deadlock:
Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for
an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called daedlock.
Example of Deadlock in java:
1. public class DeadlockExample {
2. public static void main(String[] args) {
3. final String resource1 = "ratan jaiswal";
4. final String resource2 = "vimal jaiswal";
5. // t1 tries to lock resource1 then resource2
6. Thread t1 = new Thread() {
7. public void run() {
8. synchronized (resource1) {
9. System.out.println("Thread 1: locked resource 1");
10.
11. try { Thread.sleep(100);} catch (Exception e) {}
12.
13. synchronized (resource2) {
14. System.out.println("Thread 1: locked resource 2");
15. }
16. }
17. }
18. };
19.
20. // t2 tries to lock resource2 then resource1
21. Thread t2 = new Thread() {
22. public void run() {
23. synchronized (resource2) {
24. System.out.println("Thread 2: locked resource 2");
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.
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.Syntax:
2)notify() method:
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be
awakened. The choice is arbitrary and occurs at the discretion of the implementation.Syntax:
3)notifyAll() method:
Wakes up all threads that are waiting on this object's monitor.
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
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. }}
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. class A extends Thread{
2. public void run(){
3. try{
4. Thread.sleep(1000);
5. System.out.println("task");
6. }catch(InterruptedException e){
7. throw new RuntimeException("Thread interrupted..."+e);
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. }
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)
1. <strong>Output:</strong>Exception handled
2. java.lang.InterruptedException: sleep interrupted
3. thread is running...
1. <strong>Output:</strong>1
2. 2
3. 3
4. 4
5. 5
1. class InterruptedDemo extends Thread{
2.
3. public void run(){
4. for(int i=1;i<=2;i++){
5. if(Thread.interrupted()){
6. System.out.println("code for interrupted thread");
7. }
8. else{
9. System.out.println("code for normal thread");
10. }
11.
12. }//end of for loop
13. }
14.
15. public static void main(String args[]){
16.
17. InterruptedDemo t1=new InterruptedDemo();
18. InterruptedDemo t2=new InterruptedDemo();
19.
20. t1.start();
21. t1.interrupt();
22.
23. t2.start();
24.
25. }
26. }
1. <strong>Output:</strong>Code for interrupted thread
2. code for normal thread
3. code for normal thread
4. code for normal thread
5.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it's like a stream of water that continues to
flow.
Do You Know ?
How to write a common data to multiple files using single stream only ?
How can we access multiple files by single stream ?
How can we improve the performance of Input and Output operation ?
How many ways can we read data from the keyboard?
What is console class ?
How to compress and uncompress the data of a file?
OutputStream
Java application uses an output stream to write data to a destination, it may be a file,an array,peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source, it may be a file,an array,peripheral device or socket.
OutputStream class
OutputStream class ia an abstract class.It is the superclass of all classes representing an output stream of bytes. An output stream accepts
output bytes and sends them to some sink.
1) public void write(int)throws IOException: is used to write a byte to the current output stream.
2) public void write(byte[])throws IOException: is used to write an array of byte to the current output stream.
3) public void flush()throws IOException: flushes the current output stream.
4) public void close()throws IOException: is used to close the current output stream.
InputStream class
InputStream class ia an abstract class.It is the superclass of all classes representing an input stream of bytes.
1) public abstract int read()throws IOException: reads the next byte of data from the input stream.It returns -1 at the end of file.
2) public int available()throws IOException: returns an estimate of the number of bytes that can be read from the current input stream.
3) public void close()throws IOException: is used to close the current input stream.
FileInputStream and FileOutputStream (File Handling):
FileInputStream and FileOutputStream classes are used to read and write data in file. In another words, they are used for file handling in java.
FileOutputStream class:
A FileOutputStream is an output stream for writing data to a file.
If you have to write primitive values then use FileOutputStream.Instead, for character-oriented data, prefer FileWriter.But you can write byte-
oriented as well as character-oriented data.
Example of FileOutputStream class:
1. //<b><i>Simple program of writing data into the file</i></b>
2.
3.
4. import java.io.*;
5. class Test{
6. public static void main(String args[]){
7. try{
8. FileOutputstream fout=new FileOutputStream("abc.txt");
9. String s="Sachin Tendulkar is my favourite player";
10.
11. byte b[]=s.getBytes();
12. fout.write(b);
13.
14. fout.close();
15.
16. System.out.println("success...");
17. }catch(Exception e){system.out.println(e);}
18. }
19. }
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.
1. //<b><i>Simple program of reading data from the file</i></b>
2.
3. import java.io.*;
4. class SimpleRead{
5. public static void main(String args[]){
6. try{
7. FileInputStream fin=new FileInputStream("abc.txt");
8. int i;
9. while((i=fr.read())!=-1)
10. System.out.println((char)i);
11.
12. fin.close();
13. }catch(Exception e){system.out.println(e);}
14. }
15. }
1. <strong>Output:</strong>Sachin is my favourite player.
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. import java.io.*;
2.
3. class C{
4. public static void main(String args[])throws Exception{
5.
6. FileInputStream fin=new FileInputStream("C.java");
7. FileOutputStream fout=new FileOutputStream("M.java");
8.
9. int i=0;
10. while((i=fin.read())!=-1){
11. fout.write((byte)i);
12. }
13.
14. fin.close();
15. }
16. }
ByteArrayOutputStream class:
In this stream, the data is written into a byte array. The buffer automatically grows as data is written to it.
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.
1. //<b><i>Simple program of writing data by ByteArrayOutputStream class</i></b>
2.
3.
4. import java.io.*;
5. class S{
6. public static void main(String args[])throws Exception{
7.
8. FileOutputStream fout1=new FileOutputStream("f1.txt");
9. FileOutputStream fout2=new FileOutputStream("f2.txt");
10.
11. ByteArrayOutputStream bout=new ByteArrayOutputStream();
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.
2) SequenceInputStream(Enumeration e):creates a new input stream by reading the data of an enumeration whose type is InputStream.
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. import java.io.*;
2. import java.util.*;
3.
4. class B{
5. 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 method
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. }
BufferedOutputStream class:
BufferedOutputStream used an internal buffer. It adds more efficiency than to write data directly into a stream. So, it makes the performance
fast.
Example of BufferedOutputStream class:
In this example, we are writing the textual information in the BufferedOutputStream object which is connected to the FileOutputStream object.
The flush() flushes the data of one stream and send it into another. It is required if you have connected the one stream with another.
1. import java.io.*;
2. class Test{
3. public static void main(String args[])throws Exception{
4.
5. FileOutputStream fout=new FileOutputStream("f1.txt");
6. BufferedOutputStream bout=new BufferedOutputStream(fout);
7.
8. String s="Sachin is my favourite player";
9. byte b[]=s.getBytes();
10. bout.write(b);
11.
12. bout.flush();
13. bout.close();
14. System.out.println("success");
15. }
16. }
Output:success...
1. //<b><i>Simple program of reading data from the file using buffer</i></b>
2.
3. import java.io.*;
4. class SimpleRead{
5. public static void main(String args[]){
6. try{
7.
8. FileInputStream fin=new FileInputStream("f1.txt");
9. BufferedInputStream bin=new BufferedInputStream(fin);
10. int i;
11. while((i=bin.read())!=-1)
12. System.out.println((char)i);
13.
14. fin.close();
15. }catch(Exception e){system.out.println(e);}
16. }
17. }
1. <strong>Output:</strong>Sachin is my favourite player
FileWriter class:
FileWriter class is used to write character-oriented data to the file. Sun Microsystem has suggested not to use the FileInputStream and
FileOutputStream classes if you have to read and write the textual information.
1. import java.io.*;
2. class Simple{
3. public static void main(String args[]){
4. try{
5. FileWriter fw=new FileWriter("abc.txt");
6. fw.write("my name is sachin");
7. fw.flush();
8.
9. fw.close();
10. }catch(Exception e){System.out.println(e);}
11. System.out.println("success");
12. }
13. }
Output:success...
FileReader class:
FileReader class is used to read data from the file.
1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4.
5. FileReader fr=new FileReader("abc.txt");
6. int i;
7. while((i=fr.read())!=-1)
8. System.out.println((char)i);
9.
10. fr.close();
11. }
12. }
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:
BufferedReader class:
BufferedReader class can be used to read data line by line by readLine() method.
1. //<b><i>Program of reading data</i></b>
2.
3. import java.io.*;
4. class G5{
5. public static void main(String args[])throws Exception{
6.
7. InputStreamReader r=new InputStreamReader(System.in);
8. BufferedReader br=new BufferedReader(r);
9.
10. System.out.println("Enter ur name");
11. String name=br.readLine();
12. System.out.println("Welcome "+name);
13. }
14. }
Output:Enter ur name
Amit
Welcome Amit
Another Example of reading data from keyboard by InputStreamReader and BufferdReader class until the user writes stop
In this example, we are reading and printing the data until the user prints stop.
1. import java.io.*;
2. class G5{
3. public static void main(String args[])throws Exception{
4.
5. InputStreamReader r=new InputStreamReader(System.in);
6. BufferedReader br=new BufferedReader(r);
7.
8. String name="";
9.
10. while(name.equals("stop")){
11. System.out.println("Enter data: ");
12. name=br.readLine();
13. System.out.println("data is: "+name);
14. }
15.
16. br.close();
17. r.close();
18. }
19. }
Syntax:
1. public static Console console(){}
2) public String readLine(String fmt,Object... args): it provides a formatted prompt then reads the single line of text from the console.
3) public char[] readPassword(): is used to read password that is not being displayed on the console.
4) public char[] readPassword(String fmt,Object... args): it provides a formatted prompt then reads the password that is not being displayed on
the console.
1. import java.io.*;
2. class A{
3. public static void main(String args[]){
4.
5. Console c=System.console();
6.
7. System.out.println("Enter ur name");
8. String n=c.readLine();
9. System.out.println("Welcome "+n);
10.
11. }
12. }
1. import java.io.*;
2. class A{
3. public static void main(String args[]){
4.
5. Console c=System.console();
6.
7. System.out.println("Enter password");
8. char[] ch=c.readPassword();
9.
10. System.out.println("Password is");
11. for(char ch2:ch)
12. System.out.print(ch2);
13.
14. }
15. }
java.util.Scanner class:
There are various ways to read input from the keyboad, the java.util.Scanner class is one of them. The Scanner class breaks the input into tokens
using a delimiter which is whitespace bydefault. It provides many methods to read and parse various primitive values.
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.
1. import java.util.Scanner;
2. class ScannerTest{
3. public static void main(String args[]){
4.
5. Scanner sc=new Scanner(System.in);
6.
7. System.out.println("Enter your rollno");
8. int rollno=sc.nextInt();
9. System.out.println("Enter your name");
10. String name=sc.next();
11. System.out.println("Enter your fee");
12. double fee=sc.nextDouble();
13.
14. System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
15.
16. }
17. }
java.io.PrintStream class:
The PrintStream class provides methods to write data to another stream. The PrintStream class automatically flushes the data so there is no
need to call flush() method. Moreover, its methods don't throw IOException.
1. import java.io.*;
2. class PrintStreamTest{
3. public static void main(String args[])throws Exception{
4.
5. FileOutputStream fout=new FileOutputStream("mfile.txt");
6. PrintStream pout=new PrintStream(fout);
7. pout.println(1900);
8. pout.println("Hello Java");
9. pout.println("Welcome to Java");
10. pout.close();
11. fout.close();
12.
13. }
14. }
1. class PrintStreamTest{
2. public static void main(String args[]){
3. int a=10;
4. System.out.printf("%d",a);//Note, out is the object of PrintStream class
5.
6. }
7. }
Output:10
DeflaterOutputStream class:
The DeflaterOutputStream class is used to compress the data in the deflate compression format. It provides facility to the other compression
filters, such as GZIPOutputStream.
InflaterInputStream class:
The InflaterInputStream class is used to uncompress the file in the deflate compression format. It provides facility to the other uncompression
filters, such as GZIPInputStream class.
Example of uncompressing file using InflaterInputStream class
In this example, we are decompressing the compressed file def.txt into D.java .
1. import java.io.*;
2. import java.util.zip.*;
3.
4. class UnCompress{
5. public static void main(String args[]){
6.
7. try{
8. FileInputStream fin=new FileInputStream("def.txt");
9. InflaterInputStream in=new InflaterInputStream(fin);
10.
11. FileOutputStream fout=new FileOutputStream("D.java");
12.
13. int i;
14. while((i=in.read())!=-1){
15. fout.write((byte)i);
16. fout.flush();
17. }
18.
19. fin.close();
20. fout.close();
21. in.close();
22.
23. }catch(Exception e){System.out.println(e);}
24. System.out.println("rest of the code");
25. }
26. }
1. import java.io.*;
2.
3. class PipedWR{
4. public static void main(String args[])throws Exception{
5.
6. final PipedOutputStream pout=new PipedOutputStream();
7. final PipedInputStream pin=new PipedInputStream();
8.
9. pout.connect(pin);//connecting the streams
10.
11. //creating one thread t1 which writes the data
12. Thread t1=new Thread(){
13. public void run(){
14. for(int i=65;i<=90;i++){
15. try{
16.
17. pout.write(i);
18. Thread.sleep(1000);
19.
20. }catch(Exception e){}
21. }
22. }
23. };
24.
25. //creating another thread t2 which reads the data
26. Thread t2=new Thread(){
27. public void run(){
28. try{
29. for(int i=65;i<=90;i++)
30. System.out.println(pin.read());
31. }catch(Exception e){}
32. }
33. };
34.
35. //starting both threads
36. t1.start();
37. t2.start();
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. Serialization and static datamember
11. Serializing the array or collection objects
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.
1. import java.io.Serializable;
2.
3. public class Student implements Serializable{
4. int id;
5. String name;
6. public Student(int id, String name) {
7. this.id = id;
8. this.name = name;
9. }
10. }
ObjectOutputStream class:
An ObjectOutputStream is used to write primitive data types and Java objects to an OutputStream.Only objects that support the
java.io.Serializable interface can be written to streams.
Commonly used Constructors:
1) public ObjectOutputStream(OutputStream out) throws IOException {}creates an ObjectOutputStream that writes to the specified
OutputStream.
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
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.
1. import java.io.*;
2. class Depersist{
3. public static void main(String args[])throws Exception{
4.
5. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
6. Student s=(Student)in.readObject();
7. System.out.println(s.id+" "+s.name);
8.
9. in.close();
10. }
11. }
1. <strong>Output:</strong>211 ravi
If a class implements Serilizable then all its subclasses will also be serilizable. Let's see the example given below:
1. import java.io.Serializable;
2.
3. class Person implements Serializable{
4. int id;
5. String name;
6. Person(int id, String name) {
7. this.id = id;
8. this.name = name;
9. }
10. }
1. class Student extends Person{
2. String course;
3. int fee;
4. public Student(int id, String name, String course, int fee) {
5. super(id,name);
6. this.course=course;
7. this.fee=fee;
8. }
9. }
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.
Note: If there is any static data member in a class, it will not be serialized because static is related to class not to instance.
1. class Employee implements Serializable{
2. int id;
3. String name;
4. static String companyName="IBM";//it won't be serialized
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
Rule: In case of array or collection, all the objects of array or collection must be serializable,if any object is not serialiizable then
serialization will be failed.
1. import java.io.Serializable;
2.
3. public class Student implements Serializable{
4. int id;
5. String name;
6. transient int age;//Now it will not be serialized
7. public Student(int id, String name,int age) {
8. this.id = id;
9. this.name = name;
10. this.age=age;
11. }
12. }
1. import java.io.*;
2. class Persist{
3. public static void main(String args[])throws Exception{
4. Student s1 =new Student(211,"ravi",22);
5.
6. FileOutputStream f=new FileOutputStream("f.txt");
7. ObjectOutputStream out=new ObjectOutputStream(f);
8.
9. out.writeObject(s1);
10. out.flush();
11.
12. System.out.println("success");
13. }
14. }
<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
centralize software management
Do You Know ?
Networking Terminology:
There are some networking terminologies given below:
IP Address
Protocol
Port Number
MAC Address
Connection-oriented and connectionless protocol
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:
Socket class:
A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a socket.
ServerSocket class:
The ServerSocket class can be used to create a server socket. This object is used to establish communication with the clients.
1. //MyServer.java
2.
3. import java.io.*;
4. import java.net.*;
5.
6. public class MyServer {
7. public static void main(String[] args){
8. try{
9. ServerSocket ss=new ServerSocket(6666);
10. Socket s=ss.accept();//establishes connection
11.
12. DataInputStream dis=new DataInputStream(s.getInputStream());
13.
14. String str=(String)dis.readUTF();
15. System.out.println("message= "+str);
16.
17. ss.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21. }
1. //MyClient.java
2.
3. import java.io.*;
4. import java.net.*;
5.
6. public class MyClient {
7. public static void main(String[] args) {
8. try{
9. Socket s=new Socket("localhost",6666);
10.
11. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
12.
13. dout.writeUTF("Hello Server");
14. dout.flush();
15.
16. dout.close();
17. s.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21. }
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
1. //URLDemo.java
2.
3. import java.io.*;
4. import java.net.*;
5.
6. public class URLDemo{
7. public static void main(String[] args){
8. try{
9. URL url=new URL("http://www.javatpoint.com/sonoojaiswal/index.jsp");
10.
11. System.out.print("Protocol: "+url.getProtocol());
12. System.out.print("Host Name: "+url.getHost());
13. System.out.print("Port Number: "+url.getPort());
14. System.out.print("File Name: "+url.getFile());
15.
16. }catch(Exception e){System.out.println(e);}
17. }
18. }
Output:Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /sonoojaiswal/index.jsp
URLConnection class:
The URLConnection class represents a communication link between the URL and the application. This class can be used to read and write data to
the specified resource reffered by the URL.
1. public URLConnection openConnection()throws IOException{}
2.
3. }
Displaying all the data of a webpage by URLConnecton class
The URLConnection class provides many methods, we can display all the data of a webpage by using the getInputStream() method. The
getInputStream() method returns all the data of the specified URL in the stream that can be read and displayed.
1. //DisplayData.java
2.
3. import java.io.*;
4. import java.net.*;
5.
6. public class DisplayData {
7. public static void main(String[] args){
8. try{
9. URL url=new URL("http://www.javatpoint.com/sonoojaiswal/");
10. URLConnection urlcon=url.openConnection();
11.
12. InputStream stream=urlcon.getInputStream();
13. int i;
14. while((i=stream.read())!=-1){
15. System.out.print((char)i);
16. }
17.
18. }catch(Exception e){System.out.println(e);}
19. }
20. }
InetAddress class:
The java.net.InetAddress class represents an IP address. The Inet Address class provides methods to get the IP of any host name.
Commonly used methods of InetAddress class:
public static InetAddress getByName(String host) throws UnknownHostException: it returns the IP of the given host.
public static InetAddress getLocalHost() throws UnknownHostException: it returns the LocalHost IP and name.
public String getHostName(): it returns the host name of the IP address.
public String getHostAddress(): it returns the IP address in string format.
1. //InetDemo.java
2.
3. import java.io.*;
4. import java.net.*;
5.
6. public class InetDemo{
7. public static void main(String[] args){
8. try{
9.
10. InetAddress ip=InetAddress.getByName("www.javatpoint.com");
11.
12. System.out.println("Host Name: "+ip.getHostName());
13. System.out.println("IP Address: "+ip.getHostAddress());
14.
15. }catch(Exception e){System.out.println(e);}
16. }
17. }
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.
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.
1. //DSender.java
2.
3. import java.net.*;
4.
5. public class DSender{
6. public static void main(String[] args) throws Exception {
7. DatagramSocket ds = new DatagramSocket();
8. String str = "Welcome java";
9. InetAddress ip = InetAddress.getByName("127.0.0.1");
10.
11. DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
12. ds.send(dp);
13. ds.close();
14. }
15. }
1. //DReceiver.java
2.
3. import java.net.*;
4.
5. public class DReceiver{
6. public static void main(String[] args) throws Exception {
7.
8. DatagramSocket ds = new DatagramSocket(3000);
9. byte[] buf = new byte[1024];
10.
11. DatagramPacket dp = new DatagramPacket(buf, 1024);
12. ds.receive(dp);
13.
14. String str = new String(dp.getData(), 0, dp.getLength());
15. System.out.println(str);
16. ds.close();
17. }
18. }
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.
Creating a Frame:
There are two ways to create a frame:
1. import java.awt.*;
2.
3. class First extends Frame{
4.
5. First(){
6. Button b=new Button("click me");
7. b.setBounds(30,100,80,30);// setting button position
8.
9. add(b);//adding button into frame
10. setSize(300,300);//frame size 300 width and 300 height
11. setLayout(null);//no layout now bydefault BorderLayout
12. setVisible(true);//now frame willbe visible, bydefault not visible
13.
14. }
15. public static void main(String args[]){
16.
17. First f=new First();
18.
19. }
20. }
1. import java.awt.*;
2. class First2{
3. First2(){
4.
5. Frame f=new Frame();
6.
7. Button b=new Button("click me");
8. b.setBounds(30,50,80,30);
9.
10. f.add(b);
11. f.setSize(300,300);
12. f.setLayout(null);
13. f.setVisible(true);
14.
15. }
16. public static void main(String args[]){
17.
18. First2 f=new First2();
19.
20. }
21. }
ActionEvent ActionListener
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 public void addActionListener(ActionListener a){}
MenuItem
o public void addActionListener(ActionListener a){}
TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
TextArea
o public void addTextListener(TextListener a){}
Checkbox
o public void addItemListener(ItemListener a){}
Choice
o public void addItemListener(ItemListener a){}
List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
EventHandling Codes:
We can put the event handling code into one of the following places:
1. Same class
2. Other class
3. Annonymous class
1. import java.awt.*;
2. import java.awt.event.*;
3.
4. class AEvent extends Frame implements ActionListener{
5. TextField tf;
6. AEvent(){
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 AEvent();
30. }
31. }
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that sets the position of the component it
may be button, textfield etc.
1. import java.awt.*;
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. }
1. import java.awt.event.*;
2.
3. class Outer implements ActionListener{
4. AEvent2 obj;
5. Outer(AEvent2 obj){
6. this.obj=obj;
7. }
8.
9. public void actionPerformed(ActionEvent e){
10. obj.tf.setText("welcome");
11. }
12.
13. }
1. import java.awt.*;
2. import java.awt.event.*;
3.
4. class AEvent3 extends Frame{
5. TextField tf;
6. AEvent3(){
7.
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10.
11. Button b=new Button("click me");
12. b.setBounds(50,120,80,30);
13.
14. b.addActionListener(new ActionListener(){
15. public void actionPerformed(){
16. tf.setText("hello");
17. }
18. });
19.
20. add(b);add(tf);
21.
22. setSize(300,300);
23. setLayout(null);
24. setVisible(true);
25.
26. }
27. public static void main(String args[]){
28. new AEvent3();
29. }
30. }
What is JFC ?
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications.
Do You Know ?
Creating a Frame:
There are two ways to create a frame:
1. import javax.swing.*;
2. public class Simple {
3. JFrame f;
4. Simple(){
5.
6. f=new JFrame();
7.
8. JButton b=new JButton("click");
9. b.setBounds(130,100,100, 40);
10.
11. f.add(b);
12.
13. f.setSize(400,500);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17.
18. public static void main(String[] args) {
19. new Simple();
20. }
21. }
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. }
JButton class:
The JButton class is used to create a button that have plateform-independent implementation.
6) public void setMnemonic(int a): is used to set the mnemonic on the button.
7) public void addActionListener(ActionListener a): is used to add the action listener to this object.
1. import java.awt.event.*;
2. import javax.swing.*;
3.
4. public class ImageButton{
5. ImageButton(){
6. JFrame f=new JFrame();
7.
8.
9. JButton b=new JButton(new ImageIcon("b.jpg"));
10. b.setBounds(130,100,100, 40);
11.
12. f.add(b);
13.
14. f.setSize(300,400);
15. f.setLayout(null);
16. f.setVisible(true);
17.
18. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19.
20. }
21.
22. public static void main(String[] args) {
23. new ImageButton();
24. }
25. }
JRadioButton class:
The JRadioButton class is used to create a radio button.
4) public void setIcon(Icon b): is used to set the specified Icon on the button.
6) public void setMnemonic(int a): is used to set the mnemonic on the button.
7) public void addActionListener(ActionListener a): is used to add the action listener to this object.
Note: The JRadioButton class extends the JToggleButton class that extends AbstractButton class.
1. import javax.swing.*;
2. public class Radio {
3. JFrame f;
4.
5. Radio(){
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. }
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.
4) public void insert(String s, int position): is used to insert the specified text on the specified position.
5) public void append(String s): is used to append the given text to the end of the document.
1. import java.awt.Color;
2. import javax.swing.*;
3.
4. public class TArea {
5. 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. public static void main(String[] args) {
23. new TArea();
24. }
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.
JComboBox(Object[] items)
JComboBox(Vector<?> items)
Commonly used methods of JComboBox class:
1) public void addItem(Object anObject): is used to add an item to the item list.
2) public void removeItem(Object anObject): is used to delete an item to the item list.
3) public void removeAllItems(): is used to remove all the items from the list.
4) public void setEditable(boolean b): is used to determine whether the JComboBox is editable.
1. import javax.swing.*;
2. public class Combo {
3. JFrame f;
4. Combo(){
5. f=new JFrame("Combo ex");
6.
7. String country[]={"India","Aus","U.S.A","England","Newzeland"};
8.
9. JComboBox cb=new JComboBox(country);
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. }
1. import javax.swing.*;
2. public class MyTable {
3. JFrame f;
4. MyTable(){
5. f=new JFrame();
6.
7. String data[][]={ {"101","Amit","670000"},
8. {"102","Jai","780000"},
9. {"101","Sachin","700000"}};
10. String column[]={"ID","NAME","SALARY"};
11.
12. JTable jt=new JTable(data,column);
13. jt.setBounds(30,40,200,300);
14.
15. JScrollPane sp=new JScrollPane(jt);
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.
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. JColorChooserExample ch=new JColorChooserExample();
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.
2) public void setString(String s): is used to set value to the progress string.
3) public void setOrientation(int orientation): is used to set the orientation, it may be either vertical or horizontal by using
SwingConstants.VERTICAL and SwingConstants.HORIZONTAL constants..
4) public void setValue(int value): is used to set the current value on the progress bar.
1. import javax.swing.*;
2. public class MyProgress extends JFrame{
3. JProgressBar jb;
4. int i=0,num=0;
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. MyProgress m=new MyProgress();
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.
3) public void setPaintTicks(boolean b): is used to determine whether tick marks are painted.
4) public void setPaintLabels(boolean b): is used to determine whether labels are painted.
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. t = new Thread(this);
16. t.start();
17.
18. b=new JButton();
19. 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. Calendar cal = Calendar.getInstance();
32. hours = cal.get( Calendar.HOUR_OF_DAY );
33. if ( hours > 12 ) hours -= 12;
34. minutes = cal.get( Calendar.MINUTE );
35. seconds = cal.get( Calendar.SECOND );
36.
37. SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
38. Date date = cal.getTime();
39. timeString = formatter.format( date );
40.
41. printTime();
42.
43. t.sleep( 1000 ); // interval given in milliseconds
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. }
1. import java.awt.*;
2. import javax.swing.JFrame;
3.
4. public class DisplayGraphics extends Canvas{
5.
6. public void paint(Graphics g) {
7. g.drawString("Hello",40,40);
8. setBackground(Color.WHITE);
9. g.fillRect(130, 30,100, 80);
10. g.drawOval(30,130,50, 60);
11. setForeground(Color.RED);
12. g.fillOval(130,130,50, 60);
13. g.drawArc(30, 200, 40,50,90,60);
14. g.fillArc(30, 130, 40,50,180,40);
15.
16. }
17. public static void main(String[] args) {
18. DisplayGraphics m=new DisplayGraphics();
19. JFrame f=new JFrame();
20. f.add(m);
21. f.setSize(400,400);
22. //f.setLayout(null);
23. f.setVisible(true);
24. }
25.
26. }
1. import java.awt.*;
2. import javax.swing.JFrame;
3.
4. public class MyCanvas extends Canvas{
5.
6. public void paint(Graphics g) {
7.
8. Toolkit t=Toolkit.getDefaultToolkit();
9. Image i=t.getImage("p3.gif");
10. g.drawImage(i, 120,100,this);
11.
12. }
13. public static void main(String[] args) {
14. MyCanvas m=new MyCanvas();
15. JFrame f=new JFrame();
16. f.add(m);
17. f.setSize(400,400);
18. f.setVisible(true);
19. }
20.
21. }
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;}
23. String getFileName(){return new String(fileName);}
24. void setFileName(String fileName){this.fileName=new String(fileName);}
25. /////////////////////////
26. FileOperation(Notepad npd)
27. {
28. this.npd=npd;
29.
30. saved=true;
31. newFileFlag=true;
32. fileName=new String("Untitled");
33. fileRef=new File(fileName);
34. this.npd.f.setTitle(fileName+" - "+applicationTitle);
35.
36. chooser=new JFileChooser();
37. chooser.addChoosableFileFilter(new MyFileFilter(".java","Java Source Files(*.java)"));
38. chooser.addChoosableFileFilter(new MyFileFilter(".txt","Text Files(*.txt)"));
39. chooser.setCurrentDirectory(new File("."));
40.
41. }
42. //////////////////////////////////////
43.
44. boolean saveFile(File temp)
45. {
46. FileWriter fout=null;
47. try
48. {
49. fout=new FileWriter(temp);
50. fout.write(npd.ta.getText());
51. }
52. catch(IOException ioe){updateStatus(temp,false);return false;}
53. finally
54. {try{fout.close();}catch(IOException excp){}}
55. updateStatus(temp,true);
56. return true;
57. }
58. ////////////////////////
59. boolean saveThisFile()
60. {
61.
62. if(!newFileFlag)
63. {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. this.npd.f,""+temp.getPath()+" already exists.<br>Do you want to replace it?",
84. "Save As",JOptionPane.YES_NO_OPTION
85. )==JOptionPane.YES_OPTION)
86. 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. din=new BufferedReader(new InputStreamReader(fin));
103. String str=" ";
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. catch(IOException ioe){updateStatus(temp,false);return false;}
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. chooser.setApproveButtonToolTipText("Click me to open the selected file.!");
128.
129. File temp=null;
130. do
131. {
132. if(chooser.showOpenDialog(this.npd.f)!=JFileChooser.APPROVE_OPTION)
133. return;
134. temp=chooser.getSelectedFile();
135.
136. if(temp.exists()) break;
137.
138. JOptionPane.showMessageDialog(this.npd.f,
139. ""+temp.getName()+"<br>file not found.<br>"+
140. "Please verify the correct file name was given.",
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. void updateStatus(File temp,boolean saved)
158. {
159. if(saved)
160. {
161. this.saved=true;
162. fileName=new String(temp.getName());
163. if(!temp.canWrite())
164. {fileName+="(Read only)"; newFileFlag=true;}
165. fileRef=temp;
166. npd.f.setTitle(fileName + " - "+applicationTitle);
167. npd.statusBar.setText("File : "+temp.getPath()+" saved/opened successfully.");
168. newFileFlag=false;
169. }
170. else
171. {
172. npd.statusBar.setText("Failed to save/open : "+temp.getPath());
173. }
174. }
175. ///////////////////////
176. boolean confirmSave()
177. {
178. String strMsg="The text in the "+fileName+" file has been changed.<br>"+
179. "Do you want to save the changes?";
180. if(!saved)
181. {
182. int x=JOptionPane.showConfirmDialog(this.npd.f,strMsg,applicationTitle,
183. JOptionPane.YES_NO_CANCEL_OPTION);
184.
185. if(x==JOptionPane.CANCEL_OPTION) return false;
186. if(x==JOptionPane.YES_OPTION && !saveAsFile()) return false;
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. }// end defination of class FileOperation
204. /************************************/
205. public class Notepad implements ActionListener, MenuConstants
206. {
207.
208. JFrame f;
209. JTextArea ta;
210. JLabel statusBar;
211.
212. private String fileName="Untitled";
213. private boolean saved=true;
214. String applicationName="Javapad";
215.
216. String searchString, replaceString;
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. JMenuItem cutItem,copyItem, deleteItem, findItem, findNextItem,
227. replaceItem, gotoItem, selectAllItem;
228. /****************************/
229. Notepad()
230. {
231. f=new JFrame(fileName+" - "+applicationName);
232. ta=new JTextArea(30,60);
233. statusBar=new JLabel("|| Ln 1, Col 1 ",JLabel.RIGHT);
234. f.add(new JScrollPane(ta),BorderLayout.CENTER);
235. f.add(statusBar,BorderLayout.SOUTH);
236. f.add(new JLabel(" "),BorderLayout.EAST);
237. f.add(new JLabel(" "),BorderLayout.WEST);
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);
245.
246. fileHandler=new FileOperation(this);
247.
248. /////////////////////
249.
250. ta.addCaretListener(
251. new CaretListener()
252. {
253. public void caretUpdate(CaretEvent e)
254. {
255. int lineNumber=0, column=0, pos=0;
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("|| Ln "+(lineNumber+1)+", Col "+(column+1));
265. }
266. });
267. //////////////////
268. DocumentListener myListener = new DocumentListener()
269. {
270. public void changedUpdate(DocumentEvent e){fileHandler.saved=false;}
271. public void removeUpdate(DocumentEvent e){fileHandler.saved=false;}
272. public void insertUpdate(DocumentEvent e){fileHandler.saved=false;}
273. };
274. ta.getDocument().addDocumentListener(myListener);
275. /////////
276. WindowListener frameClose=new WindowAdapter()
277. {
278. public void windowClosing(WindowEvent we)
279. {
280. if(fileHandler.confirmSave())System.exit(0);
281. }
282. };
283. f.addWindowListener(frameClose);
284. //////////////////
285. /*
286. ta.append("Hello dear hello hi");
287. ta.append("\nwho are u dear mister hello");
288. ta.append("\nhello bye hel");
289. ta.append("\nHello");
290. ta.append("\nMiss u mister hello hell");
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:",""+lineNumber);
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. public void actionPerformed(ActionEvent ev)
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. "Get ur printer repaired first! It seems u dont have one!",
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. return; // text box have no text
351. if(findReplaceDialog==null)
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. return; // text box have no text
360.
361. if(findReplaceDialog==null)
362. statusBar.setText("Use Find option of Edit Menu first !!!!");
363. else
364. findReplaceDialog.findNextWithSelection();
365. }
366. ////////////////////////////////////
367. else if(cmdText.equals(editReplace))
368. {
369. if(Notepad.this.ta.getText().length()==0)
370. return; // text box have no text
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. return; // text box have no text
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. showBackgroundColorDialog();
410. ////////////////////////////////////
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. statusBar.setText("This "+cmdText+" command is yet to be implemented");
425. }//action Performed
426. ////////////////////////////////////
427. void showBackgroundColorDialog()
428. {
429. if(bcolorChooser==null)
430. bcolorChooser=new JColorChooser();
431. if(backgroundDialog==null)
432. backgroundDialog=JColorChooser.createDialog
433. (Notepad.this.f,
434. formatBackground,
435. false,
436. bcolorChooser,
437. new ActionListener()
438. {public void actionPerformed(ActionEvent evvv){
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. fcolorChooser=new JColorChooser();
449. if(foregroundDialog==null)
450. foregroundDialog=JColorChooser.createDialog
451. (Notepad.this.f,
452. formatForeground,
453. false,
454. fcolorChooser,
455. new ActionListener()
456. {public void actionPerformed(ActionEvent evvv){
457. Notepad.this.ta.setForeground(fcolorChooser.getColor());}},
458. null);
459.
460. foregroundDialog.setVisible(true);
461. }
462.
463. ///////////////////////////////////
464. JMenuItem createMenuItem(String s, int key,JMenu toMenu,ActionListener al)
465. {
466. JMenuItem temp=new JMenuItem(s,key);
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,ActionListener al)
474. {
475. JMenuItem temp=new JMenuItem(s,key);
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. int key,JMenu toMenu,ActionListener al)
485. {
486. JCheckBoxMenuItem temp=new JCheckBoxMenuItem(s);
487. temp.setMnemonic(key);
488. temp.addActionListener(al);
489. temp.setSelected(false);
490. toMenu.add(temp);
491.
492. return temp;
493. }
494. ////////////////////////////////////
495. JMenu createMenu(String s,int key,JMenuBar toMenuBar)
496. {
497. JMenu temp=new JMenu(s);
498. temp.setMnemonic(key);
499. toMenuBar.add(temp);
500. return temp;
501. }
502. /*********************************/
503. void createMenuBar(JFrame f)
504. {
505. JMenuBar mb=new JMenuBar();
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. temp=createMenuItem(editUndo,KeyEvent.VK_U,editMenu,KeyEvent.VK_Z,this);
526. temp.setEnabled(false);
527. editMenu.addSeparator();
528. cutItem=createMenuItem(editCut,KeyEvent.VK_T,editMenu,KeyEvent.VK_X,this);
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. findItem=createMenuItem(editFind,KeyEvent.VK_F,editMenu,KeyEvent.VK_F,this);
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,KeyEvent.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).setSelected(true);
552. /************For Look and Feel***/
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. MenuListener editMenuListener=new MenuListener()
562. {
563. public void menuSelected(MenuEvent evvvv)
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. public void menuDeselected(MenuEvent evvvv){}
595. public void menuCanceled(MenuEvent evvvv){}
596. };
597. editMenu.addMenuListener(editMenuListener);
598. f.setJMenuBar(mb);
599. }
600. /*************Constructor**************/
601. ////////////////////////////////////
602. public static void main(String[] s)
603. {
604. new Notepad();
605. }
606. }
607. /**************************************/
608. //public
609. interface MenuConstants
610. {
611. final String fileText="File";
612. final String editText="Edit";
613. final String formatText="Format";
614. final String viewText="View";
615. final String helpText="Help";
616.
617. final String fileNew="New";
618. final String fileOpen="Open...";
619. final String fileSave="Save";
620. final String fileSaveAs="Save As...";
621. final String filePageSetup="Page Setup...";
622. final String filePrint="Print";
623. final String fileExit="Exit";
624.
625. final String editUndo="Undo";
626. final String editCut="Cut";
627. final String editCopy="Copy";
628. final String editPaste="Paste";
629. final String editDelete="Delete";
630. final String editFind="Find...";
631. final String editFindNext="Find Next";
632. final String editReplace="Replace";
633. final String editGoTo="Go To...";
634. final String editSelectAll="Select All";
635. final String editTimeDate="Time/Date";
636.
637. final String formatWordWrap="Word Wrap";
638. final String formatFont="Font...";
639. final String formatForeground="Set Text color...";
640. final String formatBackground="Set Pad color...";
641.
642. final String viewStatusBar="Status Bar";
643.
644. final String helpHelpTopic="Help Topic";
645. final String helpAboutNotepad="About Javapad";
646.
647. final String aboutText="Your Javapad";
648. }
Example of Puzzle Game:
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. b2=new JButton(" ");
10. b3=new JButton("3");
11. b4=new JButton("4");
12. b5=new JButton("5");
13. b6=new JButton("6");
14. b7=new JButton("7");
15. b8=new JButton("8");
16. b9=new JButton("2");
17. next=new JButton("next");
18.
19. b1.setBounds(10,30,50,40);
20. b2.setBounds(70,30,50,40);
21. b3.setBounds(130,30,50,40);
22. b4.setBounds(10,80,50,40);
23. b5.setBounds(70,80,50,40);
24. b6.setBounds(130,80,50,40);
25. b7.setBounds(10,130,50,40);
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. else if(b3.getLabel().equals(" ")){ b3.setLabel(s); b6.setLabel(" ");}
101. else if(b5.getLabel().equals(" ")){ b5.setLabel(s); b6.setLabel(" ");}
102.
103. }//end of if
104.
105. if(e.getSource()==b7){
106. String s=b7.getLabel();
107. if(b4.getLabel().equals(" ")){ b4.setLabel(s); b7.setLabel(" ");}
108. else if(b8.getLabel().equals(" ")){ b8.setLabel(s); b7.setLabel(" ");}
109.
110. }//end of if
111.
112. if(e.getSource()==b8){
113. String s=b8.getLabel();
114. if(b7.getLabel().equals(" ")){ b7.setLabel(s); b8.setLabel(" ");}
115. else if(b9.getLabel().equals(" ")){ b9.setLabel(s); b8.setLabel(" ");}
116. else if(b5.getLabel().equals(" ")){ b5.setLabel(s); b8.setLabel(" ");}
117.
118. }//end of if
119.
120. if(e.getSource()==b9){
121. String s=b9.getLabel();
122. if(b6.getLabel().equals(" ")){ b6.setLabel(s); b9.setLabel(" ");}
123. else if(b8.getLabel().equals(" ")){ b8.setLabel(s); b9.setLabel(" ");}
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. public static void main(String[] args){
136. new puzzle();
137. }//end of main
138.
139. }//end of class
It can be developed only through AWT api, but we are using here swing framework.
1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. class TTT1 extends JFrame implements ItemListener, ActionListener{
5. int i,j,ii,jj,x,y,yesnull;
6. int a[][]={{10,1,2,3,11},{10,1,4,7,11},{10,1,5,9,11},{10,2,5,8,11},
7. {10,3,5,7,11},{10,3,6,9,11},{10,4,5,6,11},
8. {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. for(jj=1;jj<=3;jj++){
43. 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. if(a[i][j]==num){ a[i][0]=11; a[i][4]=10; }
58. }
59. }
60. for(i=0;i<=7;i++){ // for 1
61. set=true;
62. if(a[i][4]==10){ //if 1
63. int count=0;
64. for(j=1;j<=3;j++){ //for 2
65. if(b[(a[i][j]-1)].getIcon()!=null){ //if 2
66. count++;
67. } //eof if 2
68. else{ yesnull=a[i][j]; }
69. } //eof for 2
70. if(count==2){ //if 2
71. b[yesnull-1].setIcon(ic2);
72. this.check(yesnull); set=false;break;
73. } //eof if 2
74. } //eof if 1
75. else
76. if(a[i][0]==10){
77. for(j=1;j<=3;j++){ //for2
78. 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;
91. }//eof for 1
92.
93.
94. }//eof complogic
95.
96.
97. /*********************************************************/
98.
99. TTT1(){
100. super("tic tac toe by ashwani");
101.
102. CheckboxGroup cbg=new CheckboxGroup();
103. c1=new Checkbox("vs computer",cbg,false);
104. c2=new Checkbox("vs friend",cbg,false);
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. public void itemStateChanged(ItemEvent e){
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. public void actionPerformed(ActionEvent e){
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. for(i=0;i<=8;i++){
151. if(e.getSource()==b[i]){
152.
153. if(b[i].getIcon()==null){
154. if(state==true){ icon=ic2;
155. state=false;} else{ icon=ic1; state=true; }
156. b[i].setIcon(icon);
157. }
158. }
159. }//eof for
160. }//eof else
161. }//eof logicfriend
162. else if(type==false){ // complogic
163. 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. a[i][j]=a1[i][j]; //again initialsing array
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. }//eof for
185. }
186. }//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. JOptionPane.showMessageDialog(TTT1.this,"!!!YOU won!!! click reset");
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. JOptionPane.showMessageDialog(TTT1.this,"won! click reset");
206. break;
207. }
208. }
209. }
210.
211.
212. }//eof actionperformed
213. /************************************************************/
214.
215. public static void main(String []args){
216. new TTT1();
217. }//eof main
218. }//eof class
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. JRadioButton jb[]=new JRadioButton[5];
11. JButton b1,b2;
12. ButtonGroup bg;
13. int count=0,current=0,x=1,y=1,now=0;
14. int m[]=new int[10];
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. public void actionPerformed(ActionEvent e)
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. JButton bk=new JButton("Bookmark"+x);
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. l.setText("Que1: Which one among these is not a primitive datatype?");
105. jb[0].setText("int");jb[1].setText("Float");jb[2].setText("boolean");jb[3].setText("char");
106. }
107. if(current==1)
108. {
109. l.setText("Que2: Which class is available to all the class automatically?");
110. jb[0].setText("Swing");jb[1].setText("Applet");jb[2].setText("Object");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. l.setText("Que4: String class is defined in which package?");
120. jb[0].setText("lang");jb[1].setText("Swing");jb[2].setText("Applet");jb[3].setText("awt");
121. }
122. if(current==4)
123. {
124. l.setText("Que5: Which institute is best for java coaching?");
125. jb[0].setText("Utek");jb[1].setText("Aptech");jb[2].setText("SSS IT");jb[3].setText("jtek");
126. }
127. if(current==5)
128. {
129. l.setText("Que6: Which one among these is not a keyword?");
130. jb[0].setText("class");jb[1].setText("int");jb[2].setText("get");jb[3].setText("if");
131. }
132. if(current==6)
133. {
134. l.setText("Que7: Which one among these is not a class? ");
135. jb[0].setText("Swing");jb[1].setText("Actionperformed");jb[2].setText("ActionEvent");
136. jb[3].setText("Button");
137. }
138. if(current==7)
139. {
140. l.setText("Que8: which one among these is not a function of Object class?");
141. jb[0].setText("toString");jb[1].setText("finalize");jb[2].setText("equals");
142. jb[3].setText("getDocumentBase");
143. }
144. if(current==8)
145. {
146. l.setText("Que9: which function is not present in Applet class?");
147. jb[0].setText("init");jb[1].setText("main");jb[2].setText("start");jb[3].setText("destroy");
148. }
149. if(current==9)
150. {
151. l.setText("Que10: Which one among these is not a valid component?");
152. jb[0].setText("JButton");jb[1].setText("JList");jb[2].setText("JButtonGroup");
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. if(current==0)
162. return(jb[1].isSelected());
163. if(current==1)
164. return(jb[2].isSelected());
165. if(current==2)
166. return(jb[3].isSelected());
167. if(current==3)
168. return(jb[0].isSelected());
169. if(current==4)
170. return(jb[2].isSelected());
171. if(current==5)
172. return(jb[2].isSelected());
173. if(current==6)
174. return(jb[1].isSelected());
175. if(current==7)
176. return(jb[3].isSelected());
177. if(current==8)
178. return(jb[1].isSelected());
179. if(current==9)
180. return(jb[2].isSelected());
181. return false;
182. }
183. public static void main(String s[])
184. {
185. new OnlineTest("Online Test Of Java");
186. }
187. }
Output
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. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border {
5. JFrame f;
6. Border(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("NORTH");;
10. JButton b2=new JButton("SOUTH");;
11. JButton b3=new JButton("EAST");;
12. JButton b4=new JButton("WEST");;
13. JButton b5=new JButton("CENTER");;
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.
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyGridLayout{
5. JFrame f;
6. MyGridLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14. JButton b6=new JButton("6");
15. JButton b7=new JButton("7");
16. JButton b8=new JButton("8");
17. JButton b9=new JButton("9");
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. //setting grid layout of 3 rows and 3 columns
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.
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyFlowLayout{
5. JFrame f;
6. MyFlowLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
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. //setting flow layout of right alignment
19.
20. f.setSize(300,300);
21. f.setVisible(true);
22. }
23. public static void main(String[] args) {
24. new MyFlowLayout();
25. }
26. }
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.
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample1 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample1 () {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
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. }
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample2 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample2() {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. add (buttons[i]);
13. }
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. }
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.
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);
14. //create CardLayout object with 40 hor space and 30 ver space
15. 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. c.add("a",b1);c.add("b",b2);c.add("c",b3);
25.
26. }
27. public void actionPerformed(ActionEvent e) {
28. card.next(c);
29. }
30.
31. public static void main(String[] args) {
32. CardLayoutExample cl=new CardLayoutExample();
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:
Drawback of Applet
Plugin is required at client browser to execute applet.
Do You Know ?
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.
java.applet.Applet class:
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class:
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle,
arc etc.
1. By html file.
2. By appletViewer tool (for testing purpose).
Note: class must be public because its object is created by Java Plugin software that resides on the browser.
myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */
1. import java.applet.Applet;
2. import java.awt.*;
3.
4. public class GraphicsDemo extends Applet{
5.
6. public void paint(Graphics g){
7. g.setColor(Color.red);
8. g.drawString("Welcome",50, 50);
9. g.drawLine(20,30,20,300);
10. g.drawRect(70,100,30,30);
11. g.fillRect(170,100,30,30);
12. g.drawOval(70,200,30,30);
13.
14. g.setColor(Color.pink);
15. g.fillOval(170,200,30,30);
16. g.drawArc(90,150,30,30,30,270);
17. g.fillArc(270,150,30,30,0,180);
18.
19. }
20. }
myapplet.html
1. <html>
2. <body>
3. <applet code="GraphicsDemo.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
1. public Image getImage(URL u, String image){}
1. import java.awt.*;
2. import java.applet.*;
3.
4.
5. public class DisplayImage extends Applet {
6.
7. Image picture;
8.
9. public void init() {
10. picture = getImage(getDocumentBase(),"sonoo.jpg");
11. }
12.
13. public void paint(Graphics g) {
14. g.drawImage(picture, 30,30, this);
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.
1. import java.awt.*;
2. import java.applet.*;
3. public class AnimationExample extends Applet {
4.
5. Image picture;
6.
7. public void init() {
8. picture =getImage(getDocumentBase(),"bike_1.gif");
9. }
10.
11. public void paint(Graphics g) {
12. for(int i=0;i<500;i++){
13. g.drawImage(picture, i,30, this);
14.
15. try{Thread.sleep(100);}catch(Exception e){}
16. }
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.
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>
Applet 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.
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.
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>
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. int hours=0, minutes=0, seconds=0;
10. String timeString = "";
11.
12. public void init() {
13. setBackground( Color.green);
14. }
15.
16. public void start() {
17. t = new Thread( this );
18. t.start();
19. }
20.
21.
22. public void run() {
23. try {
24. while (true) {
25.
26. Calendar cal = Calendar.getInstance();
27. hours = cal.get( Calendar.HOUR_OF_DAY );
28. if ( hours > 12 ) hours -= 12;
29. minutes = cal.get( Calendar.MINUTE );
30. seconds = cal.get( Calendar.SECOND );
31.
32. SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
33. Date date = cal.getTime();
34. timeString = formatter.format( date );
35.
36. repaint();
37. t.sleep( 1000 ); // interval given in milliseconds
38. }
39. }
40. catch (Exception e) { }
41. }
42.
43.
44. public void paint( Graphics g ) {
45. g.setColor( Color.blue );
46. g.drawString( timeString, 50, 50 );
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:
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. int width, height;
9. Thread t = null;
10. boolean threadSuspended;
11. int hours=0, minutes=0, seconds=0;
12. String timeString = "";
13.
14. public void init() {
15. width = getSize().width;
16. height = getSize().height;
17. setBackground( Color.black );
18. }
19.
20. public void start() {
21. if ( t == null ) {
22. t = new Thread( this );
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. public void stop() {
38. threadSuspended = true;
39. }
40.
41. public void run() {
42. try {
43. while (true) {
44.
45. Calendar cal = Calendar.getInstance();
46. hours = cal.get( Calendar.HOUR_OF_DAY );
47. if ( hours > 12 ) hours -= 12;
48. minutes = cal.get( Calendar.MINUTE );
49. seconds = cal.get( Calendar.SECOND );
50.
51. SimpleDateFormat formatter
52. = new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );
53. Date date = cal.getTime();
54. timeString = formatter.format( date );
55.
56. // Now the thread checks to see if it should suspend itself
57. if ( threadSuspended ) {
58. synchronized( this ) {
59. while ( threadSuspended ) {
60. wait();
61. }
62. }
63. }
64. repaint();
65. t.sleep( 1000 ); // interval specified in milliseconds
66. }
67. }
68. catch (Exception e) { }
69. }
70.
71. void drawHand( double angle, int radius, Graphics g ) {
72. angle -= 0.5 * Math.PI;
73. int x = (int)( radius*Math.cos(angle) );
74. int y = (int)( radius*Math.sin(angle) );
75. g.drawLine( width/2, height/2, width/2 + x, height/2 + y );
76. }
77.
78. void drawWedge( double angle, int radius, Graphics g ) {
79. angle -= 0.5 * Math.PI;
80. int x = (int)( radius*Math.cos(angle) );
81. int y = (int)( radius*Math.sin(angle) );
82. angle += 2*Math.PI/3;
83. int x2 = (int)( 5*Math.cos(angle) );
84. int y2 = (int)( 5*Math.sin(angle) );
85. angle += 2*Math.PI/3;
86. int x3 = (int)( 5*Math.cos(angle) );
87. int y3 = (int)( 5*Math.sin(angle) );
88. g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y );
89. g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y );
90. g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );
91. }
92.
93. public void paint( Graphics g ) {
94. g.setColor( Color.gray );
95. drawWedge( 2*Math.PI * hours / 12, width/5, g );
96. drawWedge( 2*Math.PI * minutes / 60, width/3, g );
97. drawHand( 2*Math.PI * seconds / 60, width/2, g );
98. g.setColor( Color.white );
99. g.drawString( timeString, 10, height-10 );
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)
myapplet.html
1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </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){}
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="app1">
4. </applet>
5.
6. <applet code="First.class" width="150" height="150" name="app2">
7. </applet>
8. </body>
9. </html>