Java 2
Java 2
Test it Now
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 programming:
1) Standalone Application
2) Web Application
An application that runs on the server side and creates dynamic page, is called web application.
Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.
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.
History of Java
Java history is interesting to know. The history of java starts from Green Team. Java team
members (also known as Green Team), initiated a revolutionary task to develop a language for
digital devices such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was suited for
internet programming. Later, Java technology as incorporated by Netscape.
James Gosling
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc.
There are given 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.
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).
10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
There are many java versions that has been released. Current stable release of Java is Java SE 8.
Features of Java
There is given many features of java. They are also known as java buzzwords. The Java Features
given below are simple and easy to understand.
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
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
Object-oriented
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
• 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 access
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 security 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.
To create a simple java program, you need to create a class that contains main method. Let's
understand the requirement first.
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Test it Now
Output:Hello Java
Understanding first java program
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
To write the simple program, open notepad by start menu -> All Programs -> Accessories ->
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 bystart
menu -> 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:
There are many ways to write a java program. The modifications that can be done in a java
program are given below:
2) subscript notation in java array can be used after type, before variable or after variable.
3) You can provide var-args support to main method by passing 3 ellipses (dots)
Let's see the simple code of using var-args in main method. We will learn about var-args later in
Java New Features chapter.
class A
{
static public void main(String... args)
{
System.out.println("hello java4");
}
};
If there occurs a problem like displayed in the below figure, you need to set path. Since DOS
doesn't know javac or java, we need to set path. Path is not required in such a case if you save
your program inside the jdk/bin folder. But its good approach to set path.
At compile time, java file is compiled by Java Compiler (It does not interact with OS) and
converts the java code into bytecode.
Bytecode Verifier: checks the code fragments for illegal code that can violate access right to
objects.
Q)Can you save a java source file by other name than the class name?
Yes, if the class is not public. It is explained in the figure given below:
The path is required to be set for using tools such as javac, java etc.
If you are saving the java source file inside the jdk/bin directory, path is not required to be set
because all the tools will be available in the current directory.
But If you are having your java file outside the jdk/bin folder, it is necessary to set path of JDK.
1. temporary
2. permanent
To set the temporary path of JDK, you need to follow following steps:
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
Uday Singh(MCA), 09199511858 / 09835613557 Page 13
JAVA
Understanding the difference between JDK, JRE and JVM is important in Java. We are
having brief overview of JVM here.
If you want to get the detailed knowledge of Java Virtural Machine, move to the next page.
Firstly, let's see the basic differences between the JDK, JRE and JVM.
JVM
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are
platform dependent because configuration of each OS differs. But, Java is platform
independent.
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) 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).
What is JVM?
It is:
What it does?
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
• Memory area
• Class file format
• Register set
• Garbage-collected heap
• Fatal error reporting etc.
1) Classloader:
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
Variable is a name of memory location. There are three types of variables: local, instance and
static. There are two types of datatypes in java, primitive and non-primitive.
Variable
Variable is name of reserved area allocated in memory.
• instance variable
• static variable
Local Variable
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable .
It is not declared as static.
Static variable
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
because java uses unicode system rather than ASCII code system. \u0000 is the lowest range of
unicode system.
Unicode System
• ASCII (American Standard Code for Information Interchange) for the United States.
• ISO 8859-1 for Western European Language.
• KOI-8 for Russian.
• GB18030 and BIG-5 for chinese, and so on.
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 in java is a 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.
Operators Precedence
multiplicative */%
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
ternary ?:
Java Programs
Java programs are frequently asked in the interview. These programs can be asked from control
statements, array, string, oops etc. Let's see the list of java programs.
1) Fibonacci series
Write a java program to print fibonacci series without using recursion and using recursion.
Input: 10
Output: 0 1 1 2 3 5 8 13 21 34
2) Prime number
Input: 44
Input: 7
3) Palindrome number
Input: 329
Input: 12321
4) Factorial number
Input: 5
Output: 120
Input: 6
Output: 720
5) Armstrong number
Input: 153
Input: 22
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.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
3)OOPs provides ability to simulate real-world event much more effectively. We can provide
the solution of real word problem if we are using the Object-Oriented Programming language.
Java naming convention is a rule to follow as you decide what to name your identifiers such as
class, package, variable, constant, method etc.
All the classes, interfaces, packages, methods and fields of java programming language are given
according to java naming convention.
By using standard Java naming conventions, you make your code easier to read for yourself and
for other programmers. Readability of Java program is very important. It indicates thatless
time is spent to figure out what the code does.
Name Convention
class name should start with uppercase letter and be a noun e.g. String,
Color, Button, System, Thread etc.
package should be in lowercase letter e.g. java, lang, sql, util etc.
name
Java follows camelcase syntax for naming the class, interface, method and variable.
If name is combined with two words, second word will start with uppercase letter always e.g.
actionPerformed(), firstName, ActionEvent, ActionListener etc.
Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table,
car etc. It can be physical or logical (tengible and intengible). The example of integible object is
banking system.
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 behavior.
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 in Java
A class is a group of objects that has common properties. It is a template or blueprint from
which objects are created.
• data member
• method
• constructor
• block
• class and interface
class <class_name>
{
data member;
method;
}
Simple Example of Object and Class
In this example, we have created a Student class that have two data members id and name. We
are creating the object of the Student class by new keyword and printing the objects value.
class Student1
{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
Test it Now
Output:0 null
Method in Java
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.
In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method on it. Here, we are displaying the state
(data) of the objects by invoking the displayInformation method.
class Student2
{
int rollno;
String name;
void displayInformation()
{
System.out.println(rollno+" "+name);
}//method
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Test it Now
111 Karan
222 Aryan
As you see in the above figure, object gets the memory in Heap area and reference variable
refers to the object allocated in the Heap memory area. Here, s1 and s2 both are reference
variables that refer to the objects allocated in memory.
There is given another example that maintains the records of Rectangle class. Its exaplanation
is same as in the above Student class example.
class Rectangle
{
int length;
int width;
void calculateArea()
{
System.out.println(length*width);
}
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45
What are the different ways to create an object in Java?
Annonymous object
If you have to use an object only once, annonymous object is a good approach.
class Calculation
{
void fact(int n)
{
int fact=1;
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
Output:Factorial is 120
class Rectangle
{
int length;
int width;
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45
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.
In this example, we have created two overloaded methods, first sum method performs addition of
two numbers and second sum method performs addition of three numbers.
class Calculation
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
}
}
Test it Now
Output:30
40
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.
class Calculation2
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}
}
}
Test it Now
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:
class Calculation3
{
int sum(int a,int b)
{
System.out.println(a+b);
}
double sum(int a,int b)
{
System.out.println(a+b);
}
}
}
Test it Now
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:
class Overloading1
{
One type is promoted to another implicitly if no matching datatype is found. Let's understand the
concept by the figure given below:
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.
class OverloadingCalculation1
{
}
}
Test it Now
Output:40
60
Example of Method Overloading with TypePromotion if matching found
If there are matching type arguments in the method, type promotion is not performed.
class OverloadingCalculation2
{
void sum(int a,int b)
{
System.out.println("int arg method invoked");
}
void sum(long a,long b)
{
System.out.println("long arg method invoked");
}
If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.
class OverloadingCalculation3
{
void sum(int a,long b)
{
System.out.println("a method invoked");
}
void sum(long a,int b)
{
System.out.println("b method invoked");
}
One type is not de-promoted implicitly for example double cannot be depromoted to any type
implicitely.
Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.
Java 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.
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked
at the time of object creation.
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Test it Now
Output:
Bike is created
Default constructor provides the default values to the object like 0, null etc. depending on the
type.
class Student3
{ {
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
}
Test it Now
Output:
0 null
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.
In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.
Class Student4
{
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
Output:
111 Karan
222 Aryan
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.
cclass Student5
{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
Output:
111 Karan 0
222 Aryan 25
There are many differences between constructors and methods. They are given below.
type. type.
There is no copy constructor in java. But, we can copy 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 in java. 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 java
constructor.
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
s1.display();
s2.display();
}
}
Test it Now
Output:
111 Karan
111 Karan
We can copy the values of one object into another by assigning the objects values to another
object. In this case, there is no need to create the constructor.
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}
Output:
111 Karan
111 Karan
Q) Does constructor return any value?
Ans:yes, that is current class instance (You cannot use return type yet it returns a value).
Yes, like object creation, starting a thread, calling method etc. You can perform any operation in
the constructor as you perform in the method.
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.
• 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.
class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get memory
each time when object is created.All student have its unique rollno and name so instance data
member is good.Here, college refers to the common property of all objects.If we make it
static,this field will get memory only once.
class Student8{
int rollno;
String name;
static String college ="ITS";
s1.display();
s2.display();
}
}
Test it Now
In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object
will have the copy of the instance variable, if it is incremented, it won't reflect to other objects.
So each objects will have the value 1 in the count variable.
class Counter{
int count=0;//will get memory when instance is created
Counter(){
count++;
System.out.println(count);
}
}
}
Test it Now
Output:1
1
1
class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;
System.out.println(count);
}
}
}
Test it Now
Output:1
2
3
If you apply static keyword with any method, it is known as static method.
class Student9{
int rollno;
String name;
static String college = "ITS";
s1.display();
s2.display();
s3.display();
}
}
Test it Now
class Calculate{
static int cube(int x){
return x*x*x;
}
Output:125
Restrictions for static method
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.
class A{
int a=40;//non static
Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
Test it Now
Output:Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
There can be a lot of usage of java 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.
Let's understand the problem if we don't use this keyword by the example given below:
class Student10{
int id;
String name;
id = id;
name = name;
}
void display(){System.out.println(id+" "+name);}
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.
Output111 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:
class Student12{
int id;
String name;
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.
class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
class Student14{
int id;
String name;
String city;
class Student15{
int id;
String name;
Student15(){System.out.println("default constructor is invoked");}
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
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}
Test it Now
Output:method is invoked
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
Output:method is invoked
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Test it Now
Output:10
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Test it Now
Output:Hello java
class A5{
void m(){
System.out.println(this);//prints same reference ID
}
obj.m();
}
}
Test it Now
Output:A5@22b3ea59
A5@22b3ea59
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of parent
class, and you can add new methods and fields also.
The extends keyword 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 super class. The new class is called
a subclass.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer is
a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Test it Now
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
When a class extends multiple classes i.e. known as multiple inheritance. For Example:
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If
A and B classes have same method and you call it from child class object, there will be
ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time error
now.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Aggregation in Java
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.
class Employee{
int id;
String name;
Address address;//Address is a class
...
}
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
In this example, we have created the reference of Operation class in the Circle class.
class Operation{
int square(int n){
return n*n;
}
}
class Circle{
Operation op;//aggregation
double pi=3.14;
Output:78.5
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
Emp.java
void display(){
System.out.println(id+" "+name);
System.out.println(address.city+" "+address.state+" "+addr
ess.country);
}
e.display();
e2.display();
}
}
Test it Now
Output:111 varun
gzb UP india
112 arun
gno UP india
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
In other words, If subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.
Let's understand the problem that we may face in the program if we don't use method overriding.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
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.
class Vehicle{
Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of
interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%,
7% and 9% rate of interest.
class Bank{
int getRateOfInterest(){return 0;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will
learn it later.
because static method is bound with class whereas instance method is bound with object. Static
belongs to class area and instance belongs to heap area.
There are many differences between method overloading and method overriding in java. A list of
differences between method overloading and method overriding are given below:
class OverloadingExample{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
}
Covariant Return Type
The covariant return type specifies that the return type may vary in the same direction as the
subclass.
Before Java5, it was not possible to override any method by changing the return type. But now,
since Java5, it is possible to override method by changing the return type if subclass overrides
any method whose return type is Non-Primitive but it changes its return type to subclass type.
Let's take a simple example:
Note: If you are beginner to java, skip this topic and return to it after OOPs concepts.
class A{
A get(){return this;}
}
class B1 extends A{
B1 get(){return this;}
void message(){System.out.println("welcome to covariant return type");}
As you can see in the above example, the return type of the get() method of A class is A but the
return type of the get() method of B class is B. Both methods have different return type but it is
method overriding. This is known as covariant return type.
The super keyword in java is a reference variable that is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e.
referred by super reference variable.
class Vehicle{
int speed=50;
}
class Bike3 extends Vehicle{
int speed=100;
void display(){
System.out.println(speed);//will print speed of Bike
}
public static void main(String args[]){
Bike3 b=new Bike3();
b.display();
}
}
Test it Now
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.
class Vehicle{
int speed=50;
}
void display(){
System.out.println(super.speed);//will print speed of Veh
icle now
}
public static void main(String args[]){
Bike4 b=new Bike4();
b.display();
}
Test it Now
Output:50
The super keyword can also be used to invoke the parent class constructor as given below:
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
}
}
Test it Now
Output:Vehicle is created
Bike is created
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
constructor.
Another example of super keyword where super() is provided by the compiler implicitly.
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
Output:Vehicle is created
10
The super keyword can also be used to invoke parent class method. It should be used in case
subclass contains the same method as parent class as in the example given below:
class Person{
void message(){System.out.println("welcome");}
}
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
Test it Now
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.
void display(){
message();//will invoke parent class message() method
}
Output:welcome
The initialization of the instance variable can be directly but there can be performed extra
operations while initializing 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:
class Bike{
int speed=100;
}
Suppose I have to perform some operations while assigning value to instance data member
e.g. a for loop to fill a complex array or error handling etc.
class Bike7{
int speed;
Bike7(){System.out.println("speed is "+speed);}
{speed=100;}
Output:speed is 100
speed is 100
There are three places in java where you can perform operations:
1. method
2. constructor
3. block
class Bike8{
int speed;
Bike8(){System.out.println("constructor is invoked");}
Note: The java compiler copies the code of instance initializer block in every constructor.
There are mainly three rules for the instance initializer block. They are as follows:
1. The instance initializer block is created when instance of the class is created.
2. The instance initializer block is invoked after the parent class constructor is invoked (i.e.
after super() constructor call).
3. The instance initializer block comes in the order in which they appear.
class A{
A(){
System.out.println("parent class constructor invoked");
}
}
class B2 extends A{
B2(){
super();
System.out.println("child class constructor invoked");
}
class A{
A(){
System.out.println("parent class constructor invoked");
}
}
class B3 extends A{
B3(){
super();
System.out.println("child class constructor invoked");
}
B3(int a){
super();
System.out.println("child class constructor invoked "+a);
}
}
Test it Now
The final keyword in java is used to restrict the user. The java 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.
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.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Test it Now
Ans) Yes, final method is inherited but you cannot override it. For Example:
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Test it Now
Output:running...
A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an employee.
class Bike10{
final int speedlimit;//blank final variable
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
Output:70
A static final variable that is not initialized at the time of declaration is known as static blank
final variable. It can be initialized only in static block.
If you declare any parameter as final, you cannot change the value of it.
class Bike11{
int cube(final int n){
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}
Test it Now
Polymorphism in Java
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
If you overload static method in java, it is the example of compile time polymorphism. Here, we
will focus on runtime polymorphism in java.
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.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
class A{}
class B extends A{}
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.
class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}
Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of
interest may differ according to banks. For example, SBI, ICICI and AXIS banks could provide
8%, 7% and 9% rate of interest.
class Bank{
int getRateOfInterest(){return 0;}
}
class Test3{
public static void main(String args[]){
Bank b1=new SBI();
Bank b2=new ICICI();
Bank b3=new AXIS();
System.out.println("SBI Rate of Interest: "+b1.getRateOfIn
terest());
System.out.println("ICICI Rate of Interest: "+b2.getRateOf
Interest());
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
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.
class Bike{
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;
Output:90
Let's see the simple example of Runtime Polymorphism with multilevel inheritance.
class Animal{
void eat(){System.out.println("eating");}
}
a1.eat();
a2.eat();
a3.eat();
}
}
Test it Now
Output: eating
eating fruits
drinking Milk
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.
Understanding Type
int data=30;
class Dog{
public static void main(String args[]){
Dog d1;//Here d1 is a type of Dog
}
}
class Animal{}
}
Here d1 is an instance of Dog class, but it is also an instance of Animal.
static binding
When type of the object is determined at compiled time(by the compiler), it is known as static
binding.
If there is any private, final or static method in a class, there is static binding.
Dynamic binding
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.
Java instanceof
The java instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).
The instanceof in java is also known as typecomparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with any
variable that has null value, it returns false.
Let's see the simple example of instance operator where it tests the current class.
1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. System.out.println(s instanceof Simple);//true
5. }
6. }
Test it Now
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 referred by either Dog or Animal class.
1. class Animal{}
2. class Dog1 extends Animal{//Dog inherits Animal
3.
4. public static void main(String args[]){
5. Dog1 d=new Dog1();
6. System.out.println(d instanceof Animal);//true
7. }
8. }
Test it Now
Output:true
If we apply instanceof operator with a variable that have null value, it returns false. Let's see the
example given below where we apply instanceof operator with the variable that have null value.
1. class Dog2{
2. public static void main(String args[]){
3. Dog2 d=null;
4. System.out.println(d instanceof Dog2);//false
5. }
6. }
Test it Now
Output:false
When Subclass type refers to the object of Parent class, it is known as downcasting. If we
perform it directly, compiler gives Compilation error. If you perform it by typecasting,
ClassCastException is thrown at runtime. But if we use instanceof operator, downcasting is
possible.
1. class Animal { }
2.
3. class Dog3 extends Animal {
4. static void method(Animal a) {
5. if(a instanceof Dog3){
6. Dog3 d=(Dog3)a;//downcasting
7. System.out.println("ok downcasting performed");
8. }
9. }
10.
11. public static void main (String [] args) {
12. Animal a=new Dog3();
13. Dog3.method(a);
14. }
15.
16. }
Test it Now
Downcasting can also be performed without the use of instanceof operator as displayed in the
following example:
1. class Animal { }
2. class Dog4 extends Animal {
3. static void method(Animal a) {
4. Dog4 d=(Dog4)a;//downcasting
5. System.out.println("ok downcasting performed");
6. }
7. public static void main (String [] args) {
8. Animal a=new Dog4();
9. Dog4.method(a);
10. }
11. }
Test it Now
Let's take closer look at this, actual object that is referred by a, is an object of Dog class. So if we
downcast it, it is fine. But what will happen if we write:
Let's see the real use of instanceof keyword by the example given below.
1. interface Printable{}
2. class A implements Printable{
3. public void a(){System.out.println("a method");}
4. }
5. class B implements Printable{
6. public void b(){System.out.println("b method");}
7. }
8.
9. class Call{
Output: b method
A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
Before learning java abstract class, let's understand the abstraction in java first.
Abstraction in Java
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.
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.
abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.
In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
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.
File: TestAbstraction1.java
drawing circle
File: TestBank.java
3. }
4.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 7;}
7. }
8. class PNB extends Bank{
9. int getRateOfInterest(){return 7;}
10. }
11.
12. class TestBank{
13. public static void main(String args[]){
14. Bank b=new SBI();//if object is PNB, method of PNB will be invoked
15. int interest=b.getRateOfInterest();
16. System.out.println("Rate of Interest is: "+interest+" %");
17. }}
Test it Now
An abstract class can have data member, abstract method, method body, constructor and even
main() method.
File: TestAbstraction2.java
bike is created
running safely..
gear changed
Rule: If there is any abstract method in a class, that class must be abstract.
1. class Bike12{
2. abstract void run();
3. }
Test it Now
Rule: If you are extending any abstract 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 Test5{
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. }}
Test it Now
Output:I am a
I am b
I am c
I am d
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and
multiple inheritance in Java.
There are mainly three reasons to use interface. They are given below.
The java compiler adds public and abstract keywords before the interface method and public,
static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods are public and
abstract.
As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.
In this example, Printable interface have only one method, its implementation is provided in
the A class.
1. interface printable{
2. void print();
3. }
4.
5. class A6 implements printable{
6. public void print(){System.out.println("Hello");}
7.
8. public static void main(String args[]){
9. A6 obj = new A6();
10. obj.print();
11. }
12. }
Test it Now
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 A7 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. A7 obj = new A7();
16. obj.print();
17. obj.show();
18. }
19. }
Test it Now
Output:Hello
Welcome
Q) Multiple inheritance is not supported through class in java but it is possible by 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
implementation 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 testinterface1 implements Printable,Showable{
10.
11. public void print(){System.out.println("Hello");}
12.
13. public static void main(String args[]){
14. testinterface1 obj = new testinterface1();
15. obj.print();
16. }
17. }
Test it Now
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.
Interface inheritance
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class Testinterface2 implements Showable{
8.
9. public void print(){System.out.println("Hello");}
10. public void show(){System.out.println("Welcome");}
11.
12. public static void main(String args[]){
13. Testinterface2 obj = new Testinterface2();
14. obj.print();
15. obj.show();
16. }
17. }
Test it Now
Hello
Welcome
An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information to the
JVM so that JVM may perform some useful operation.
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. }
Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.
3) Abstract class can have final, non-final, Interface has only static and final
static and non-static variables. variables.
4) Abstract class can have static methods, Interface can't have static methods, main
main method and constructor. method or constructor.
6) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
7) Example: Example:
public class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
Let's see a simple example where we are using interface and abstract class both.
Output:
I am a
I am b
I am c
I am d
Java Package
Package in java 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.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) 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
2) 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 in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Let's take an example, Sun Microsystem has definded a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group
e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes
are for networking etc and so on. So, Sun has subcategorized the java package into subpackages
such as lang, net, io etc. and put the Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
Output:Hello subpackage
There is a scenario, I want to put the class file of A.java source file in classes folder of c:
drive. For example:
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. }
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where
the class file resides.
To run this program from e:\source directory, you can use -classpath switch of java that tells
where to look for class file. For example:
Output:Welcome to package
• Temporary
o By setting the classpath in the command prompt
o By -classpath switch
• Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file in
the jre/lib/ext folder.
Rule: There can be only one public class in a java source file and it must be saved by the
public class name.
1. //save as A.java
2.
3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}
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.
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.
In this example, we are printing the details of java.lang package by invoking the methods of
package class.
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. }
There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, 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. 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. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }
1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
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.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.
1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Output: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
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, overridden 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[]){
Encapsulation in Java
Encapsulation in java is a process of wrapping code and data together into a single unit, for
example capsule i.e. mixed of several medicines.
We can create a fully encapsulated class in java 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.
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. package com.javatpoint;
3. public class Student{
4. private String name;
5.
6. public String getName(){
7. return name;
8. }
The Object class is the parent class of all the classes in java bydefault. In other words, it is the
topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:
1. Object obj=getObject();//we don't what object would be returned from this method
The Object class provides some common behaviours to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
Method Description
protected Object clone() throws creates and returns the exact copy
CloneNotSupportedException (clone) of this object.
public final void wait(long causes the current thread to wait for
timeout)throws InterruptedException the specified milliseconds, until
another thread notifies (invokes
notify() or notifyAll() method).
public final void wait(long timeout,int causes the current thread to wait for
nanos)throws InterruptedException the specified miliseconds and
nanoseconds, until another thread
notifies (invokes notify() or
notifyAll() method).
public final void wait()throws causes the current thread to wait, until
InterruptedException another thread notifies (invokes
notify() or notifyAll() method).
The java.lang.Cloneable interface must be implemented by the class whose object clone we
want to create. If we don't implement Cloneable interface, clone() method
generatesCloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as follows:
The clone() method saves the extra processing task for creating the exact copy of an object. If
we perform it by using the new keyword, it will take a lot of processing to be performed that is
why we use object cloning.
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.
Java Array
Normally, array is a collection of similar type of elements that have contiguous memory location.
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 set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.
1. class Testarray{
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. }}
Test it Now
Output: 10
20
70
40
50
We can declare, instantiate and initialize the java array together by:
1. class Testarray1{
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. }}
Test it Now
Output:33
3
4
5
We can pass the java array to 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 Testarray2{
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 to method
15.
16. }}
Test it Now
Output:3
In such case, data is stored in row and column based index (also known as matrix form).
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
1. class Testarray3{
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. }}
Test it Now
Output:1 2 3
245
445
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 Testarray4{
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. }}
Test it Now
Output:I
Output:caffein
1. class Testarray5{
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. }}
Test it Now
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. public static void main(String args[]){
9. Operation op=new Operation();
10.
11. System.out.println("before change "+op.data);
12. op.change(500);
13. System.out.println("after change "+op.data);
14.
15. }
16. }
download this example
Output:before change 50
after change 50
In case of call by reference original value is changed if we made changes in the called method. If
we pass object in place of any primitive value, original value will be changed. In this example
we are passing object as a value. Let's take a simple example:
1. class Operation2{
2. int data=50;
3.
4. void change(Operation2 op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7.
8.
The java command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be used as
an input.
So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }
1. compile by > javac CommandLineExample.java
2. run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo
1. class A{
2. public static void main(String args[]){
3.
4. for(int i=0;i<args.length;i++)
5. System.out.println(args[i]);
6.
7. }
8. }
1. compile by > javac A.java
2. run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc
There are many differences between object and class. A list of differences between object and
class are given below:
7) There are many ways to create object in There is only one way to
java such as new keyword, newInstance() define class in java using
method, clone() method, factory method and class keyword.
deserialization.
Java String
1. Java String Handling
2. How to create string object
1. String literal
2. new keyword
Java String provides a lot of concepts that can be performed on a string such as compare,
concat, equals, split, length, replace, compareTo, intern, substring etc.
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
The java String is immutable i.e. it cannot be changed but a new instance is created. For mutable
class, you can use StringBuffer and StringBuilder class.
We will discuss about immutable string later. Let's first understand what is string in java and
how to create the string object.
Generally, string is a sequence of characters. But in java, string is an object that represents a
sequence of characters. String class is used to create string object.
1) String Literal
1. String s="welcome";
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 is returned. If string doesn't exist in
the pool, a new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
In the above example only one object will be created. Firstly JVM will not find any string object
with the value "Welcome" in string constant pool, so it will create a new object. After that it will
find the string with the value "Welcome" in the pool, it will not create new object but will return
the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool.
To make Java more memory efficient (because no new objects are created if it exists already in
string constant pool).
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(non pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in heap(non pool).
java
strings
example
The java.lang.String class provides many useful methods to perform operations on sequence of
char values.
Object... args)
Do You Know ?
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
Let's try to understand the immutability concept by the example given below:
1. class Testimmutablestring{
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the end
5. System.out.println(s);//will print Sachin because strings are immutable objects
6. }
7. }
Test it Now
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new
object is created with sachintendulkar. That is why string is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still refers
to "Sachin" not to "Sachin Tendulkar".
But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar"
object.For example:
1. class Testimmutablestring1{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=s.concat(" Tendulkar");
5. System.out.println(s);
6. }
7. }
Test it Now
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not
modified.
It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.
1. By equals() method
2. By = = operator
3. By compareTo() method
The String equals() method compares the original content of the string. It compares values of
string for equality. String class provides two methods:
o public boolean equals(Object another) compares this string to the specified object.
1. class Teststringcomparison1{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. System.out.println(s1.equals(s2));//true
8. System.out.println(s1.equals(s3));//true
9. System.out.println(s1.equals(s4));//false
10. }
11. }
Test it Now
Output:true
true
false
1. class Teststringcomparison2{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="SACHIN";
5.
6. System.out.println(s1.equals(s2));//false
7. System.out.println(s1.equalsIgnoreCase(s3));//true
8. }
9. }
Test it Now
Output:false
true
Click me for more about equals() method
1. class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both refer to same instance)
Output:true
false
The String compareTo() method compares values lexicographically and returns an integer value
that describes if first string is less than, equal to or greater than second string.
o s1 == s2 :0
o s1 > s2 :positive value
o s1 < s2 :negative value
1. class Teststringcomparison4{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
9. }
10. }
Test it Now
Output:0
1
-1
String Concatenation in Java
In java, string concatenation forms a new string that is the combination of multiple strings. There
are two ways to concat string in java:
Java string concatenation operator (+) is used to add strings. For Example:
1. class TestStringConcatenation1{
2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
4. System.out.println(s);//Sachin Tendulkar
5. }
6. }
Test it Now
Output:Sachin Tendulkar
In java, 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 TestStringConcatenation2{
2. public static void main(String args[]){
3. String s=50+30+"Sachin"+40+40;
4. System.out.println(s);//80Sachin4040
5. }
6. }
Test it Now
80Sachin4040
Note: After a string literal, all the + will be treated as string concatenation operator.
The String concat() method concatenates the specified string to the end of current string. Syntax:
1. class TestStringConcatenation3{
2. public static void main(String args[]){
3. String s1="Sachin ";
4. String s2="Tendulkar";
5. String s3=s1.concat(s2);
6. System.out.println(s3);//Sachin Tendulkar
7. }
8. }
Test it Now
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 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:
o startIndex: inclusive
o endIndex: exclusive
Let's understand the startIndex and endIndex by the code given below.
1. String s="hello";
2. System.out.println(s.substring(0,2));//he
In the above substring, 0 points to h but 2 points to e (because end index is exclusive).
Tendulkar
Sachin
The java.lang.String class provides a lot of methods to work on string. By the help of these
methods, we can perform operations on string such as trimming, concatenating, converting,
comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a string if you submit any form
in window based, web based or mobile application.
The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.
1. String s="Sachin";
2. System.out.println(s.toUpperCase());//SACHIN
3. System.out.println(s.toLowerCase());//sachin
4. System.out.println(s);//Sachin(no change in original)
Test it Now
SACHIN
sachin
Sachin
The string trim() method eliminates white spaces before and after string.
Sachin
Sachin
3. System.out.println(s.endsWith("n"));//true
Test it Now
true
true
1. String s="Sachin";
2. System.out.println(s.charAt(0));//S
3. System.out.println(s.charAt(3));//h
Test it Now
S
h
1. String s="Sachin";
2. System.out.println(s.length());//6
Test it Now
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.
Sachin
The string valueOf() method coverts given type such as int, long, float, double, boolean, char and
char array into string.
1. int a=10;
2. String s=String.valueOf(a);
3. System.out.println(s+10);
Output:
1010
The string replace() method replaces all occurrence of first sequence of character with second
sequence of character.
Output:
Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in
java is same as String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
2. public synchronized StringBuffer insert(int offset, String s): is used to insert the
specified string with this string at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float),
insert(int, double) etc.
3. public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is
used to replace the string from specified startIndex and endIndex.
4. public synchronized StringBuffer delete(int startIndex, int endIndex): is used to
delete the string from specified startIndex and endIndex.
5. public synchronized StringBuffer reverse(): is used to reverse the string.
6. public int capacity(): is used to return the current capacity.
7. public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at
least equal to the given minimum.
8. public char charAt(int index): is used to return the character at the specified position.
9. public int length(): is used to return the length of the string i.e. total number of
characters.
10. public String substring(int beginIndex): is used to return the substring from the
specified beginIndex.
11. public String substring(int beginIndex, int endIndex): is used to return the substring
from the specified beginIndex and endIndex.
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
The append() method concatenates the given argument with this string.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
The insert() method inserts the given string with this string at the given position.
1. class A{
2. public static void main(String args[]){
The replace() method replaces the given string from the specified beginIndex and endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }
The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current capacity,
it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will
be (16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }
The ensureCapacity() method of StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2
12. System.out.println(sb.capacity());//now 70
13. }
14. }
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder
class is same as StringBuffer class except that it is non-synchronized. It is available since JDK
1.5.
1. StringBuilder(): creates an empty string Builder with the initial capacity of 16.
2. StringBuilder(String str): creates a string Builder with the specified string.
3. StringBuilder(int length): creates an empty string Builder with the specified capacity as
length.
Method Description
public int length() is used to return the length of the string i.e. total
number of characters.
public String substring(int is used to return the substring from the specified
beginIndex) beginIndex.
public String substring(int is used to return the substring from the specified
beginIndex, int endIndex) beginIndex and endIndex.
The StringBuilder append() method concatenates the given argument with this string.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
The StringBuilder insert() method inserts the given string with this string at the given position.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }
Uday Singh(MCA), 09199511858 / 09835613557 Page 156
JAVA
The StringBuilder replace() method replaces the given string from the specified beginIndex and
endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
The delete() method of StringBuilder class deletes the string from the specified beginIndex to
endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }
The capacity() method of StringBuilder class returns the current capacity of the Builder. The
default capacity of the Builder is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is
16, it will be (16*2)+2=34.
1. class A{
The ensureCapacity() method of StringBuilder class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2
12. System.out.println(sb.capacity());//now 70
13. }
14. }
There are many differences between String and StringBuffer. A list of differences between String
and StringBuffer are given below:
As you can see in the program given below, String returns new hashcode value when you concat
string but StringBuffer returns same.
There are many differences between StringBuffer and StringBuilder. A list of differences
between StringBuffer and StringBuilder are given below:
StringBuffer Example
7. }
hellojava
StringBuilder Example
Let's see the code to check the performance of StringBuffer and StringBuilder classes.
below:
If you want to represent any object as a string, toString() method comes into existence.
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.
By overriding the toString() method of the Object class, we can return values of the object, so we
don't need to write much code.
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. }
download this example of toString method
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
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
The java string charAt() method returns a char value at the given index number. The index
number starts from 0.
Signature
Parameter
Returns
char value
Specified by
CharSequence interface
Throws
t
Java String compareTo
The java string compareTo() method compares the given string with current string
lexicographically. It returns positive number, negative number or 0.
If first string is greater than second string, it returns positive number (difference of character
value). If first string is less than second string, it returns negative number and if first string is
equal to second string, it returns 0.
Signature
1. public int compareTo(String anotherString)
Parameters
Returns
an integer value
Output:
0
-5
-1
Java String concat
The java string concat() method combines specified string at the end of this string. It returns
combined string. It is like appending another string.
Signature
Parameter
Returns
combined string
java string
java string is immutable so assign it explicitly
Java String contains
The java string contains() method searches the sequence of characters in this string. It
returns true if sequence of char values are found in this string otherwise returns false.
Signature
Parameter
Returns
Throws
1. class ContainsExample{
2. public static void main(String args[]){
3. String name="what do you know about me";
4. System.out.println(name.contains("do you know"));
5. System.out.println(name.contains("about"));
6. System.out.println(name.contains("hello"));
7. }}
Test it Now
true
true
false
Java String endsWith
The java string endsWith() method checks if this string ends with given suffix. It returns true if
this string ends with given suffix else returns false.
Signature
Parameter
Returns
true or false
Output:
true
true
Java String equals
The java string equals() method compares the two given strings based on the content of the
string. If any character is not matched, it returns false. If all characters are matched, it returns
true.
The String equals() method overrides the equals() method of Object class.
Signature
1. public boolean equals(Object anotherObject)
Parameter
Returns
Overrides
true
false
false
Java String format
The java string format() method returns the formatted string by given locale, format and
arguments.
If you don't specify the locale in String.format() method, it uses default locale by
callingLocale.getDefault() method.
The format() method of java language is like sprintf() function in c language and printf() method
of java language.
Signature
Parameters
Returns
formatted string
Throws
name is sonoo
value is 32.334340
value is 32.334340000000
The java string getBytes() method returns the byte array of the string. In other words, it returns
sequence of bytes.
Signature
There are 3 variant of getBytes() method. The signature or syntax of string getBytes() method is
given below:
Returns
sequence of bytes.
Output:
65
66
67
68
69
70
71
The java string indexOf() method returns index of given character value or substring. If it is not
found, it returns -1. The index counter starts from zero.
Signature
There are 4 types of indexOf method in java. The signature of indexOf methods are given below:
1 int indexOf(int ch) returns index position for the given char
value
2 int indexOf(int ch, int returns index position for the given char
fromIndex) value and from index
4 int indexOf(String substring, int returns index position for the given
fromIndex) substring and from index
Parameters
fromIndex: index position from where index of the char value or substring is retured
Returns
2 8
5
3
Java String intern
The java string intern() method returns the interned string. It returns the canonical
representation of string.
It can be used to return string from pool memory, if it is created by new keyword.
Signature
Returns
interned string
false
true
Java String isEmpty
The java string isEmpty() method checks if this string is empty. It returns true, if length of
string is 0 otherwise false.
The isEmpty() method of String class is included in java string since JDK 1.6.
Signature
Returns
Since
1.6
true
false
Java String join
The java string join() method returns a string joined with given delimiter. In string join method,
delimiter is copied for each elements.
In case of null element, "null" is added. The join() method is included in java string since JDK
1.8.
Signature
Parameters
Returns
Throws
Since
1.8
welcome-to-javatpoint
Java String lastIndexOf
The java string lastIndexOf() method returns last index of the given character value or
substring. If it is not found, it returns -1. The index counter starts from zero.
Signature
There are 4 types of lastIndexOf method in java. The signature of lastIndexOf methods are given
below:
1 int lastIndexOf(int ch) returns last index position for the given
char value
2 int lastIndexOf(int ch, int returns last index position for the given
fromIndex) char value and from index
3 int lastIndexOf(String substring) returns last index position for the given
substring
4 int lastIndexOf(String substring, returns last index position for the given
int fromIndex) substring and from index
Parameters
fromIndex: index position from where index of the char value or substring is retured
Returns
Output:
6
Java String length
The java string length() method length of the string. It returns count of total number of
characters. The length of java string is same as the unicode code units of the string.
Signature
Specified by
CharSequence interface
Returns
length of characters
The java string replace() method returns a string replacing all the old char or CharSequence to
new char or CharSequence.
Since JDK 1.5, a new replace() method is introduced, allowing you to replace a sequence of char
values.
Signature
Parameters
Returns
replaced string
5. System.out.println(replaceString);
6. }}
Test it Now
The java string replaceAll() method returns a string replacing all the sequence of characters
matching regex and replacement string.
Signature
1. public String replaceAll(String regex, String replacement)
Parameters
Returns
replaced string
Let's see an example to replace all the occurrences of single word or set of words.
The java string split() method splits this string against given regular expression and returns a
char array.
Signature
Parameter
limit : limit for the number of strings in array. If it is zero, it will returns all the strings matching
regex.
Returns
array of strings
Throws
Since
1.4
The given example returns total number of words in a string excluding space only. It also
includes special characters.
java
string
split
method
by
javatpoint
returning words:
welcome
to
split
world
returning words:
welcome to split world
returning words:
welcome
to split world
The java string startsWith() method checks if this string starts with given prefix. It returns true
if this string starts with given prefix else returns false.
Signature
Parameter
Returns
true or false
Output:
true
true
We pass begin index and end index number position in the java substring method where start
index is inclusive and end index is exclusive. In other words, start index starts from 0 whereas
end index starts from 1.
Signature
1. public String substring(int startIndex)
2. and
3. public String substring(int startIndex, int endIndex)
If you don't specify endIndex, java substring() method will return all the characters from
startIndex.
Parameters
Returns
specified string
Throws
va
vatpoint
Java String toCharArray
The java string toCharArray() method converts this string into character array. It returns a
newly created character array, its length is similar to this string and its contents are initialized
with the characters of this string.
Signature
Returns
character array
Output:
hello
Java String toLowerCase()
The java string toLowerCase() method returns the string in lowercase letter. In other words, it
converts all characters of the string into lower case letter.
Signature
There are two variant of toLowerCase() method. The signature or syntax of string toLowerCase()
method is given below:
The second method variant of toLowerCase(), converts all the characters into lowercase using
the rules of given Locale.
Returns
Output:
The java string toUpperCase() method returns the string in uppercase letter. In other words, it
converts all characters of the string into upper case letter.
Signature
There are two variant of toUpperCase() method. The signature or syntax of string toUpperCase()
method is given below:
The second method variant of toUpperCase(), converts all the characters into uppercase using the
rules of given Locale.
Returns
Output:
HELLO STRING
Java String trim
The java string trim() method eliminates leading and trailing spaces. The unicode value of
space character is '\u0020'. The trim() method in java string checks this unicode value before and
after the string, if it exists then removes the spaces and returns the omitted string.
Signature
Returns
The java string valueOf() method converts different types of values into string. By the help of
string valueOf() method, you can convert int to string, long to string, boolean to string, character
to string, float to string, double to string, object to string and char array to string.
Signature
Returns
Output:
3010
Java Regex
The Java Regex or Regular Expression is an API to define pattern for searching or
manipulating strings.
It is widely used to define constraint on strings such as password and email validation. After
learning java regex tutorial, you will be able to test your own regular expressions by the Java
Regex Tester Tool.
java.util.regex package
It provides following classes and interface for regular expressions. The Matcher and Pattern
classes are widely used in java regular expression.
1. MatchResult interface
2. Matcher class
3. Pattern class
4. PatternSyntaxException class
Matcher class
It implements MatchResult interface. It is a regex engine i.e. used to perform match operations
on a character sequence.
2 boolean find() finds the next expression that matches the pattern.
3 boolean find(int finds the next expression that matches the pattern from
start) the given start number.
Pattern class
It is the compiled version of a regular expression. It is used to define a pattern for the regex
engine.
1 static Pattern compile(String compiles the given regex and return the
regex) instance of pattern.
1. import java.util.regex.*;
2. public class RegexExample1{
3. public static void main(String args[]){
4. //1st way
5. Pattern p = Pattern.compile(".s");//. represents single character
6. Matcher m = p.matcher("as");
7. boolean b = m.matches();
8.
9. //2nd way
10. boolean b2=Pattern.compile(".s").matcher("as").matches();
11.
12. //3rd way
13. boolean b3 = Pattern.matches(".s", "as");
14.
15. System.out.println(b+" "+b2+" "+b3);
16. }}
Test it Now
Output
1. import java.util.regex.*;
2. class RegexExample2{
3. public static void main(String args[]){
4. System.out.println(Pattern.matches(".s", "as"));//true (2nd char is s)
5. System.out.println(Pattern.matches(".s", "mk"));//false (2nd char is not s)
6. System.out.println(Pattern.matches(".s", "mst"));//false (has more than 2 char)
7. System.out.println(Pattern.matches(".s", "amms"));//false (has more than 2 char)
8. System.out.println(Pattern.matches("..s", "mas"));//true (3rd char is s)
9. }}
Test it Now
5 [a-z&&[def]] d, e, or f (intersection)
1. import java.util.regex.*;
2. class RegexExample3{
3. public static void main(String args[]){
4. System.out.println(Pattern.matches("[amn]", "abcd"));//false (not a or m or n)
5. System.out.println(Pattern.matches("[amn]", "a"));//true (among a or m or n)
6. System.out.println(Pattern.matches("[amn]", "ammmna"));//false (m and a comes more than onc
e)
7. }}
Test it Now
Regex Quantifiers
Regex Description
1. import java.util.regex.*;
2. class RegexExample4{
3. public static void main(String args[]){
4. System.out.println("? quantifier ....");
5. System.out.println(Pattern.matches("[amn]?", "a"));//true (a or m or n comes one time)
6. System.out.println(Pattern.matches("[amn]?", "aaa"));//false (a comes more than one time)
7. System.out.println(Pattern.matches("[amn]?", "aammmnn"));//false (a m and n comes more than
one time)
8. System.out.println(Pattern.matches("[amn]?", "aazzta"));//false (a comes more than one time)
9. System.out.println(Pattern.matches("[amn]?", "am"));//false (a or m or n must come one time)
10.
11. System.out.println("+ quantifier ....");
12. System.out.println(Pattern.matches("[amn]+", "a"));//true (a or m or n once or more times)
13. System.out.println(Pattern.matches("[amn]+", "aaa"));//true (a comes more than one time)
14. System.out.println(Pattern.matches("[amn]+", "aammmnn"));//true (a or m or n comes more than
once)
15. System.out.println(Pattern.matches("[amn]+", "aazzta"));//false (z and t are not matching pattern)
16.
17. System.out.println("* quantifier ....");
18. System.out.println(Pattern.matches("[amn]*", "ammmna"));//true (a or m or n may come zero or
more times)
19.
20. }}
Test it Now
Regex Metacharacters
Regex Description
\b A word boundary
1. import java.util.regex.*;
2. class RegexExample5{
3. public static void main(String args[]){
4. System.out.println("metacharacters d....");\\d means digit
5.
6. System.out.println(Pattern.matches("\\d", "abc"));//false (non-digit)
7. System.out.println(Pattern.matches("\\d", "1"));//true (digit and comes once)
8. System.out.println(Pattern.matches("\\d", "4443"));//false (digit but comes more than once)
9. System.out.println(Pattern.matches("\\d", "323abc"));//false (digit and char)
10.
11. System.out.println("metacharacters D....");\\D means non-digit
12.
13. System.out.println(Pattern.matches("\\D", "abc"));//false (non-digit but comes more than once)
14. System.out.println(Pattern.matches("\\D", "1"));//false (digit)
15. System.out.println(Pattern.matches("\\D", "4443"));//false (digit)
16. System.out.println(Pattern.matches("\\D", "323abc"));//false (digit and char)
17. System.out.println(Pattern.matches("\\D", "m"));//true (non-digit and comes once)
18.
19. System.out.println("metacharacters D with quantifier....");
20. System.out.println(Pattern.matches("\\D*", "mak"));//true (non-
digit and may come 0 or more times)
21.
22. }}
Test it Now
1. /*Create a regular expression that accepts alpha numeric characters only. Its
2. length must be 6 characters long only.*/
3.
4. import java.util.regex.*;
5. class RegexExample6{
6. public static void main(String args[]){
7. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun32"));//true
8. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "kkvarun32"));//false (more than 6 char)
9. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "JA2Uk2"));//true
10. System.out.println(Pattern.matches("[a-zA-Z0-9]{6}", "arun$2"));//false ($ is not matched)
11. }}
Test it Now
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
In this page, we will learn about java exception, its type and the difference between checked and
unchecked exceptions.
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL,
Remote etc.
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
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 in java.
Do You Know ?
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
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
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1. int a=50/0;//ArithmeticException
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a
string variable that have characters, converting this variable into digit will occur
NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
1. try
2. catch
3. finally
4. throw
5. throws
Java try-catch
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw exception
3. }finally{}
Java catch block is used to handle the Exception. It must be used after the try block only.
Output:
As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
Output:
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
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.
If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
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 TestMultipleCatchBlock1{
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. System.out.println("rest of the code...");
11. }
12. }
Test it Now
Output:
Compile-time error
The try block within a try block is known as nested try block in java.
Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.
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. ....
1. class Excep6{
2. public static void main(String args[]){
3. try{
4. try{
5. System.out.println("going to divide");
6. int b =39/0;
7. }catch(ArithmeticException e){System.out.println(e);}
8.
9. try{
10. int a[]=new int[5];
11. a[5]=4;
12. }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
13.
14. System.out.println("other statement);
15. }catch(Exception e){System.out.println("handeled");}
16.
17. System.out.println("normal flow..");
18. }
19. }
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Note: If you don't handle exception, before terminating the program, JVM executes finally
block(if any).
o Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.
Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
1. class TestFinallyBlock{
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. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Test it Now
Output:5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
1. class TestFinallyBlock1{
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. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Test it Now
Case 3
Let's see the java finally example where exception occurs and handled.
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).
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
1. throw exception;
In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
Output:
1. class TestExceptionPropagation1{
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. }
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).
1. class TestExceptionPropagation2{
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. TestExceptionPropagation2 obj=new TestExceptionPropagation2();
15. obj.p();
16. System.out.println("normal flow");
17. }
18. }
Test it Now
The Java 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.
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
1. import java.io.IOException;
2. class Testthrows1{
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. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
Test it Now
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.
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. m.method();
12. }catch(Exception e){System.out.println("exception handled");}
13.
14. System.out.println("normal flow...");
15. }
16. }
Test it Now
Output:exception handled
normal flow...
14. }
Test it Now
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. class Testthrows4{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Test it Now
Output:Runtime Exception
There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
5) You cannot throw multiple You can declare multiple exceptions e.g.
exceptions. public void method()throws
IOException,SQLException.
1. void m(){
2. throw new ArithmeticException("sorry");
3. }
There are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:
1. class FinalExample{
2. public static void main(String[] args){
3. final int x=100;
4. x=200;//Compile Time Error
5. }}
1. class FinallyExample{
2. public static void main(String[] args){
3. try{
4. int x=300;
5. }catch(Exception e){System.out.println(e);}
6. finally{System.out.println("finally block is executed");}
7. }}
1. class FinalizeExample{
2. public void finalize(){System.out.println("finalize called");}
3. public static void main(String[] args){
4. FinalizeExample f1=new FinalizeExample();
5. FinalizeExample f2=new FinalizeExample();
6. f1=null;
7. f2=null;
8. System.gc();
9. }}
ExceptionHandling with MethodOverriding in Java
There are many rules if we talk about methodoverriding with exception handling. The Rules
are as follows:
•If the superclass method does not declare an exception
o If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but it can declare unchecked
exception.
•If the superclass method declares an exception
o If the superclass method declares an exception, subclass overridden method
can declare same, subclass exception or no exception but cannot declare parent
exception.
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 TestExceptionChild extends Parent{
7. void msg()throws IOException{
8. System.out.println("TestExceptionChild");
9. }
10. public static void main(String args[]){
11. Parent p=new TestExceptionChild();
12. p.msg();
13. }
14. }
Test it Now
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.
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.
Output:child
Output:child
Output:child
Java Custom Exception
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
next →← prev
Java inner class or nested class is a class i.e. declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be
more readable and maintainable.
Additionally, it can access all the members of outer class including private data members and
methods.
1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }
There are basically three advantages of inner classes in java. They are as follows:
1) 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.
2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
Do You Know
o What is the internal code generated by the compiler for member inner class ?
o What are the two ways to create annonymous inner class ?
o Can we access the non-final local variable inside the local inner class ?
o How to access the static nested class ?
o Can we define an interface within the class ?
Inner class is a part of nested class. Non-static nested classes are known as inner classes.
Type Description
A non-static class that is created inside a class but outside a method is called member inner class.
Syntax:
1. class Outer{
2. //code
3. class Inner{
4. //code
5. }
6. }
In this example, we are creating msg() method in member inner class that is accessing the private
data member of outer class.
1. class TestMemberOuter1{
2. private int data=30;
3. class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestMemberOuter1 obj=new TestMemberOuter1();
8. TestMemberOuter1.Inner in=obj.new Inner();
9. in.msg();
10. }
11. }
Test it Now
Output:
data is 30
The java compiler creates two class files in case of inner class. The class file name of inner class
is "Outer$Inner". If you want to instantiate inner class, you must have to create the instance of
outer class. In such case, instance of inner class is created inside the instance of outer class.
The java compiler creates a class file named Outer$Inner in this case. The Member inner class
have the reference of Outer class that is why it can access all the data members of Outer class
including private.
1. import java.io.PrintStream;
2. class Outer$Inner
3. {
4. final Outer this$0;
5. Outer$Inner()
6. { super();
7. this$0 = Outer.this;
8. }
9. void msg()
10. {
11. System.out.println((new StringBuilder()).append("data is ")
12. .append(Outer.access$000(Outer.this)).toString());
13. }
14. }
Java Anonymous inner class
A class that have no name is known as anonymous inner class in java. It should be used if you
have to override method of class or interface. Java Anonymous inner class can be created by two
ways:
Output:
nice fruits
1. import java.io.PrintStream;
2. static class TestAnonymousInner$1 extends Person
3. {
4. TestAnonymousInner$1(){}
5. void eat()
6. {
7. System.out.println("nice fruits");
8. }
9. }
1. interface Eatable{
2. void eat();
3. }
4. class TestAnnonymousInner1{
5. public static void main(String args[]){
6. Eatable e=new Eatable(){
7. public void eat(){System.out.println("nice fruits");}
8. };
9. e.eat();
10. }
11. }
Test it Now
Output:
nice fruits
A class i.e. created inside a method is called local inner class in java. If you want to invoke the
methods of local inner class, you must instantiate this class inside the method.
Output:
30
In such case, compiler creates a class named Simple$1Local that have the reference of the outer
class.
1. import java.io.PrintStream;
2. class localInner1$Local
3. {
4. final localInner1 this$0;
5. localInner1$Local()
6. {
7. super();
8. this$0 = Simple.this;
9. }
10. void msg()
11. {
12. System.out.println(localInner1.access$000(localInner1.this));
13. }
14. }
2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is
possible to access the non-final local variable in local inner class.
Output:
50
Java static nested class
A static class i.e. created inside a class is called static nested class in java. It cannot access non-
static data members and methods. It can be accessed by outer class name.
1. class TestOuter1{
2. static int data=30;
3. static class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter1.Inner obj=new TestOuter1.Inner();
8. obj.msg();
9. }
10. }
Test it Now
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.
If you have the static member inside static nested class, you don't need to create instance of static
nested class.
1. class TestOuter2{
2. static int data=30;
3. static class Inner{
4. static void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter2.Inner.msg();//no need to create the instance of static nested class
8. }
9. }
Test it Now
Output:
data is 30
Java Nested Interface
An interface i.e. 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.
There are given some points that should be remembered by the java programmer.
o Nested interface must be public if it is declared inside the interface but it can have any
access modifier if declared within the class.
o Nested interfaces are declared static implicitely.
1. interface Showable{
2. void show();
3. interface Message{
4. void msg();
5. }
6. }
7.
8. class TestNestedInterface1 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 TestNestedInterface1();//upcasting here
13. message.msg();
14. }
15. }
Test it Now
Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed below:.
1. class A{
2. interface Message{
3. void msg();
4. }
5. }
6.
7. class TestNestedInterface2 implements A.Message{
8. public void msg(){System.out.println("Hello nested interface");}
9.
Yes, If we define a class inside the interface, java compiler creates a static nested class. Let's see
how can we define a class within the interface:
1. interface M{
2. class A{}
3. }
next →← prev
Multithreading in Java
1. Multithreading
2. Multitasking
3. Process-based multitasking
4. Thread-based multitasking
5. What is Thread
But we use multithreading than multiprocessing because threads share a common memory
area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
Multitasking
o Process-based Multitasking(Multiprocessing)
o Thread-based Multitasking(Multithreading)
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
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.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in javanew, 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 in java is controlled by JVM. The java 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
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to
be executed by a thread. Runnable interface have only one method named run().
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
•A new thread starts(with new callstack).
•The thread moves from New state to the Runnable state.
•When the thread gets a chance to execute, its target run() method will run.
Thread scheduler in java is the part of the JVM that decides which thread should run.
There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead
states or a higher priority task comes into existence. Under time slicing, a task executes for a
predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines
which task should execute next, based on priority and other factors.
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Output:
1
1
2
2
3
3
4
4
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.
No. After starting a thread, it can never be started again. If you does so,
anIllegalThreadStateException is thrown. In such case, thread will run once but for second time,
it will throw exception.
running
Exception in thread "main" java.lang.IllegalThreadStateException
What if we call run() method directly instead start() method?
•Each thread starts in a separate call stack.
•Invoking the run() method from main thread, the run() method goes onto the current call
stack rather than at the beginning of a new call stack.
Output:running...
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
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.
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...
Syntax:
public static Thread currentThread()
Output:Thread-0
Thread-1
Naming a thread:
The Thread class provides methods to change and get the name of a thread.
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of a thread.
4. }
5. public static void main(String args[]){
6. TestMultiNaming1 t1=new TestMultiNaming1();
7. TestMultiNaming1 t2=new TestMultiNaming1();
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. }
Test it Now
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changeling name of t1:Sonoo Jaiswal
running...
The currentThread() method returns a reference to the currently executing thread object.
Output:Thread-0
Thread-1
Priority of a Thread (Thread Priority):
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.
Daemon thread in java is a service provider thread that provides services to the user thread. Its
life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this
thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
You can see all the detail by typing the jconsole in the command prompt. The jconsole tool
provides information about the loaded classes, memory usage, running threads etc.
• 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.
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.
The java.lang.Thread class provides two methods for java daemon thread.
File: MyThread.java
20. }
21. }
Test it Now
Output
Note: If you want to make a user thread as Daemon, it must not be started otherwise it will
throw IllegalThreadStateException.
File: MyThread.java
Java Thread pool represents a group of worker threads that are waiting for the job and reuse
many times.
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.
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 ExecutorService and Executors.
File: WorkerThrad.java
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. public void run() {
9. System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);
10. processmessage();//call processmessage method that sleeps the thread for 2 seconds
11. System.out.println(Thread.currentThread().getName()+" (End)");//prints thread name
12. }
13. private void processmessage() {
14. try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
15. }
16. }
File: JavaThreadPoolExample.java
8. executor.shutdown();
9. while (!executor.isTerminated()) { }
10.
11. System.out.println("Finished all threads");
12. }
13. }
Test it Now
Output:
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.
Uday Singh(MCA), 09199511858 / 09835613557 Page 256
JAVA
The addShutdownHook() method of Runtime class is used to register the thread with the Virtual
Machine. Syntax:
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.
15. }
16. }
Test it Now
Note: The shutdown sequence can be stopped by invoking the halt(int) method of Runtime
class.
Output:task one
task one
task one
Program of performing single task by multiple threads
Output:task one
task one
17.
18. t1.start();
19. t2.start();
20. }
21. }
Test it Now
Output:task one
task two
1. class TestMultitasking4{
2. public static void main(String args[]){
3. Thread t1=new Thread(){
4. public void run(){
5. System.out.println("task one");
6. }
7. };
8. Thread t2=new Thread(){
9. public void run(){
10. System.out.println("task two");
11. }
12. };
13.
14.
15. t1.start();
16. t2.start();
17. }
18. }
Test it Now
Output:task one
task two
1. class TestMultitasking5{
2. public static void main(String args[]){
3. Runnable r1=new Runnable(){
4. public void run(){
5. System.out.println("task one");
6. }
7. };
8.
Output:task one
task two
Java Garbage Collection
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;
3) By annonymous object:
1. new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method
can be used to perform cleanup processing. This method is defined in Object class as:
Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method to
perform cleanup processing (destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc()
is found in System and Runtime classes.
10. }
Test it Now
Java Runtime class is used to interact with java runtime environment. Java Runtime class
provides methods to execute a process, invoke GC, get total and free memory etc. There is only
one instance of java.lang.Runtime class is available for one java application.
In the given program, after creating 10000 instance, free memory will be less than the previous
free memory. But after gc() call, you will get more free memory.
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Types of Synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
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
Synchronization is built around an internal entity known as the lock or monitor. Every object has
an lock associated with it. By convention, a thread that needs consistent access to an object's
fields has to acquire the object's lock before accessing them, and then release the lock when it's
done with them.
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 TestSynchronization1{
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
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
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. public class TestSynchronization2{
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
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.
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. public class TestSynchronization3{
15. public static void main(String args[]){
16. final Table obj = new Table();//only one object
17.
18. Thread t1=new Thread(){
19. public void run(){
20. obj.printTable(5);
21. }
22. };
23. Thread t2=new Thread(){
24. public void run(){
25. obj.printTable(100);
26. }
27. };
28.
29. t1.start();
30. t2.start();
31. }
32. }
Output: 5
10
15
20
25
100
200
300
400
500
Synchronized block can be used to perform synchronization on any specific resource 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. class Table{
2.
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method
13. }
14.
15. class MyThread1 extends Thread{
16. Table t;
17. MyThread1(Table t){
18. this.t=t;
19. }
20. public void run(){
21. t.printTable(5);
22. }
23.
24. }
25. class MyThread2 extends Thread{
26. Table t;
27. MyThread2(Table t){
28. this.t=t;
29. }
30. public void run(){
31. t.printTable(100);
32. }
33. }
34.
35. public class TestSynchronizedBlock1{
36. public static void main(String args[]){
37. Table obj = new Table();//only one object
38. MyThread1 t1=new MyThread1(obj);
39. MyThread2 t2=new MyThread2(obj);
40. t1.start();
41. t2.start();
42. }
43. }
Test it Now
Output:5
10
15
20
25
100
200
300
400
500
1. class Table{
2.
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method
13. }
14.
15. public class TestSynchronizedBlock2{
16. public static void main(String args[]){
17. final Table obj = new Table();//only one object
18.
19. Thread t1=new Thread(){
20. public void run(){
21. obj.printTable(5);
22. }
23. };
24. Thread t2=new Thread(){
25. public void run(){
26. obj.printTable(100);
27. }
28. };
29.
30. t1.start();
31. t2.start();
32. }
33. }
Test it Now
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.
Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In case of
synchronized method and synchronized block there cannot be interference between t1 and t2 or
t3 and t4 because t1 and t2 both refers to a common object that have a single lock.But there can
be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires
another lock.I want no interference between t1 and t3 or t2 and t4.Static synchronization solves
this problem.
In this example we are applying synchronized keyword on the static method to perform static
synchronization.
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. public class TestSynchronization4{
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. }
Test it Now
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. class Table{
2.
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12.
13. public class TestSynchronization5 {
14. public static void main(String[] args) {
15.
16. Thread t1=new Thread(){
17. public void run(){
18. Table.printTable(1);
19. }
20. };
21.
22. Thread t2=new Thread(){
23. public void run(){
24. Table.printTable(10);
25. }
26. };
27.
28. Thread t3=new Thread(){
29. public void run(){
30. Table.printTable(100);
31. }
32. };
33.
34. Thread t4=new Thread(){
35. public void run(){
36. Table.printTable(1000);
37. }
38. };
39. t1.start();
40. t2.start();
41. t3.start();
42. t4.start();
43.
44. }
45. }
Test it Now
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
The block synchronizes on the lock of the object denoted by the reference .class name .class. A
static synchronized method printTable(int n) in class Table is equivalent to the following
declaration:
Deadlock in java is a part of multithreading. 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 deadlock.
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.
Output: Thread 1: locked resource 1
Thread 2: locked resource 2
Inter-thread communication in Java
• wait()
• notify()
• notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on
this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation. Syntax:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
Let's see the important differences between wait and sleep methods.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
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. }}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
next>><<prev
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.
In this example, after interrupting the thread, we are propagating it, so it will stop working.
If we don't want to stop the thread, we can handle it where sleep() or wait() method is
invoked. Let's first see the example where we are propagating the exception.
9.
10. }
11.
12. public static void main(String args[]){
13. TestInterruptingThread1 t1=new TestInterruptingThread1();
14. t1.start();
15. try{
16. t1.interrupt();
17. }catch(Exception e){System.out.println("Exception handled "+e);}
18.
19. }
20. }
Test it Now
Output:Exception in thread-0
java.lang.RuntimeException: Thread interrupted...
java.lang.InterruptedException: sleep interrupted
at A.run(A.java:7)
In this example, after interrupting the thread, we handle the exception, so it will break out
the sleeping but will not stop working.
19. }
Test it Now
Output:Exception handled
java.lang.InterruptedException: sleep interrupted
thread is running...
If thread is not in sleeping or waiting state, calling the interrupt() method sets the
interrupted flag to true that can be used to stop the thread by the java programmer later.
Output:1
2
3
4
5
The isInterrupted() method returns the interrupted flag either true or false. The static
interrupted() method returns the interrupted flag afterthat it sets the flag to false if it is
true.
According to Sun Microsystems, Java monitors are reentrant means java thread can reuse the
same monitor for different synchronized methods if method is called from the method.
Let's understand the java reentrant monitor by the example given below:
1. class Reentrant {
2. public synchronized void m() {
3. n();
4. System.out.println("this is m() method");
5. }
6. public synchronized void n() {
7. System.out.println("this is n() method");
8. }
9. }
In this class, m and n are the synchronized methods. The m() method internally calls the n()
method.
Now let's call the m() method on a thread. In the class given below, we are creating thread using
annonymous class.
Java I/O (Input and Output) is used to process the input and produce the output based on the
input.
Java uses the concept of stream to make I/O operation fast. The java.io package contains all the
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.
In java, 3 streams are created for us automatically. All these streams are attached with console.
Let's see the code to print output and error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
•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.
Let's understand working of Java OutputStream and InputStream by the figure given below.
OutputStream class
OutputStream class is 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.
InputStream class
InputStream class is an abstract class.It is the superclass of all classes representing an input
stream of bytes.
1) public abstract int reads the next byte of data from the input
read()throws IOException: stream.It returns -1 at the end of file.
In Java, FileInputStream and FileOutputStream classes are used to read and write data in file. In
another words, they are used for file handling in java.
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.
Java FileInputStream class obtains input bytes from a file.It is used for reading streams of raw
bytes such as image data. For reading streams of characters, consider using FileReader.
It should be used to read byte-oriented data for example to read image, audio, video etc.
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. class C{
3. public static void main(String args[])throws Exception{
4. FileInputStream fin=new FileInputStream("C.java");
5. FileOutputStream fout=new FileOutputStream("M.java");
6. int i=0;
7. while((i=fin.read())!=-1){
8. fout.write((byte)i);
9. }
10. fin.close();
11. }
12. }
Java ByteArrayOutputStream class
Java ByteArrayOutputStream class is used to write data into multiple files. In this stream, the
data is written into a byte array that can be written to multiple stream.
3) public void write(byte[] b) throws writes byte array into this stream.
IOException
Let's see a simple example of java ByteArrayOutputStream class to write data into 2 files.
1. import java.io.*;
2. class S{
3. public static void main(String args[])throws Exception{
4. FileOutputStream fout1=new FileOutputStream("f1.txt");
5. FileOutputStream fout2=new FileOutputStream("f2.txt");
6.
7. ByteArrayOutputStream bout=new ByteArrayOutputStream();
8. bout.write(139);
9. bout.writeTo(fout1);
10. bout.writeTo(fout2);
11.
12. bout.flush();
13. bout.close();//has no effect
14. System.out.println("success...");
15. }
16. }
success...
Java SequenceInputStream class is used to read data from multiple streams. It reads data of
streams one by one.
In this example, we are printing the data of two files f1.txt and f2.txt.
1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4. FileinputStream fin1=new FileinputStream("f1.txt");
5. FileinputStream fin2=new FileinputStream("f2.txt");
6.
7. SequenceinputStream sis=new SequenceinputStream(fin1,fin2);
8. int i;
9. while((i=sis.read())!=-1){
10. System.out.println((char)i);
11. }
12. sis.close();
13. fin1.close();
14. fin2.close();
15. }
16. }
In this example, we are writing the data of two files f1.txt and f2.txt into another file named
f3.txt.
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. }
Java BufferedOutputStream class uses an internal buffer to store data. It adds more efficiency
than to write data directly into a stream. So, it makes the performance fast.
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. FileOutputStream fout=new FileOutputStream("f1.txt");
5. BufferedOutputStream bout=new BufferedOutputStream(fout);
6. String s="Sachin is my favourite player";
7. byte b[]=s.getBytes();
8. bout.write(b);
9.
10. bout.flush();
11. bout.close();
12. fout.close();
13. System.out.println("success");
14. }
15. }
Output:
success...
Java BufferedInputStream class is used to read information from stream. It internally uses buffer
mechanism to make the performance fast.
Let's see the simple example to read data of file using BufferedInputStream.
1. import java.io.*;
2. class SimpleRead{
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("f1.txt");
6. BufferedInputStream bin=new BufferedInputStream(fin);
7. int i;
8. while((i=bin.read())!=-1){
9. System.out.println((char)i);
10. }
11. bin.close();
12. fin.close();
13. }catch(Exception e){system.out.println(e);}
14. }
15. }
Output:
Java FileWriter and FileReader classes are used to write and read data from text files. These are
character-oriented classes, used for file handling in java.
Java has suggested not to use the FileInputStream and FileOutputStream classes if you have to
read and write the textual information.
FileWriter(File file) creates a new file. It gets file name in File object.
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.close();
8. }catch(Exception e){System.out.println(e);}
9. System.out.println("success");
10. }
11. }
Output:
success...
Java FileReader class is used to read data from the file. It returns data in byte format like
FileInputStream class.
1) public int read() returns a character in ASCII form. It returns -1 at the end
of file.
In this example, we are reading the data from the file abc.txt file.
1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4. FileReader fr=new FileReader("abc.txt");
5. int i;
6. while((i=fr.read())!=-1)
7. System.out.println((char)i);
8.
9. fr.close();
10. }
11. }
Output:
my name is sachin
CharArrayWriter class:
The CharArrayWriter class can be used to write data to multiple files. This class implements the
Appendable interface. Its buffer automatically grows when data is written in this stream. Calling
the close() method on this object has no effect.
In this example, we are writing a common data to 4 files a.txt, b.txt, c.txt and d.txt.
1. import java.io.*;
2. class Simple{
3. public static void main(String args[])throws Exception{
4.
5. CharArrayWriter out=new CharArrayWriter();
6. out.write("my name is");
7.
8. FileWriter f1=new FileWriter("a.txt");
9. FileWriter f2=new FileWriter("b.txt");
10. FileWriter f3=new FileWriter("c.txt");
11. FileWriter f4=new FileWriter("d.txt");
12.
13. out.writeTo(f1);
14. out.writeTo(f2);
15. out.writeTo(f3);
16. out.writeTo(f4);
17.
18.
19. f1.close();
20. f2.close();
21. f3.close();
22. f4.close();
23. }
24. }
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.
In this example, we are connecting the BufferedReader stream with the InputStreamReader
stream for reading the line by line data from the keyboard.
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. }
Output:Enter data: Amit
data is: Amit
Enter data: 10
data is: 10
Enter data: stop
The Java Console class is be used to get input from console. It provides methods to read text and
password.
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console class is
introduced since 1.5.
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);
Method Description
1) public String readLine() is used to read a single line of text from the
console.
System class provides a static method console() that returns the unique instance of Console class.
1. Console c=System.console();
1. import java.io.*;
2. class ReadStringTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter your name: ");
6. String n=c.readLine();
7. System.out.println("Welcome "+n);
8. }
9. }
Output:
1. import java.io.*;
2. class ReadPasswordTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter password: ");
6. char[] ch=c.readPassword();
7. String pass=String.valueOf(ch);//converting char array into string
8. System.out.println("Password is: "+pass);
9. }
10. }
Output:
Enter password:
Password is: sonoo
There are various ways to read input from the keyboard, the java.util.Scanner class is one of
them.
The Java Scanner class breaks the input into tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive types using regular
expression.
Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
Method Description
public String next() it returns the next token from the scanner.
public String it moves the scanner position to the next line and
nextLine() returns the value as a string.
Let's see the simple example of the Java Scanner class which reads the int, string and double
value as an input:
1. import java.util.Scanner;
2. class ScannerTest{
3. public static void main(String args[]){
4. Scanner sc=new Scanner(System.in);
5.
6. System.out.println("Enter your rollno");
7. int rollno=sc.nextInt();
8. System.out.println("Enter your name");
9. String name=sc.next();
10. System.out.println("Enter your fee");
11. double fee=sc.nextDouble();
12. System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
13. sc.close();
14. }
15. }
download this scanner example
Output:
Let's see the example of Scanner class with delimiter. The \s represents whitespace.
1. import java.util.*;
2. public class ScannerTest2{
3. public static void main(String args[]){
4. String input = "10 tea 20 coffee 30 tea buiscuits";
5. Scanner s = new Scanner(input).useDelimiter("\\s");
6. System.out.println(s.nextInt());
7. System.out.println(s.next());
8. System.out.println(s.nextInt());
9. System.out.println(s.next());
10. s.close();
11. }}
Output:
10
tea
20
coffee
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. }
download this PrintStream example
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
Compressing and Uncompressing File
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.
In this example, we are reading data of a file and compressing it into another file using
DeflaterOutputStream class. You can compress any file, here we are compressing the
Deflater.java file
1. import java.io.*;
2. import java.util.zip.*;
3.
4. class Compress{
5. public static void main(String args[]){
6.
7. try{
8. FileInputStream fin=new FileInputStream("Deflater.java");
9.
10. FileOutputStream fout=new FileOutputStream("def.txt");
11. DeflaterOutputStream out=new DeflaterOutputStream(fout);
12.
13. int i;
14. while((i=fin.read())!=-1){
15. out.write((byte)i);
16. out.flush();
17. }
18.
19. fin.close();
20. out.close();
21.
22. }catch(Exception e){System.out.println(e);}
23. System.out.println("rest of the code");
24. }
25. }
download this example
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.
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. }
PipedInputStream and PipedOutputStream classes
The PipedInputStream and PipedOutputStream classes can be used to read and write data
simultaneously. Both streams are connected with each other using the connect() method of the
PipedOutputStream class.
Here, we have created two threads t1 and t2. The t1 thread writes the data using the
PipedOutputStream object and the t2 thread reads the data from that pipe using the
PipedInputStream object. Both the piped stream object are connected with each other.
1. import java.io.*;
2. class PipedWR{
3. public static void main(String args[])throws Exception{
4. final PipedOutputStream pout=new PipedOutputStream();
5. final PipedInputStream pin=new PipedInputStream();
6.
7. pout.connect(pin);//connecting the streams
8. //creating one thread t1 which writes the data
9. Thread t1=new Thread(){
10. public void run(){
11. for(int i=65;i<=90;i++){
12. try{
13. pout.write(i);
14. Thread.sleep(1000);
15. }catch(Exception e){}
16. }
17. }
18. };
19. //creating another thread t2 which reads the data
20. Thread t2=new Thread(){
21. public void run(){
22. try{
23. for(int i=65;i<=90;i++)
24. System.out.println(pin.read());
25. }catch(Exception e){}
26. }
27. };
28. //starting both threads
29. t1.start();
30. t2.start();
31. }}
Serialization in Java
1. Serialization
2. Serializable Interface
3. Example of Serialization
4. Deserialization
5. Example of Deserialization
6. Serialization with Inheritance
7. Externalizable interface
8. Serialization and static datamember
Serialization in java is a mechanism of writing the state of an object into a byte stream.
The String class and all the wrapper classes implements java.io.Serializable interface by
default.
java.io.Serializable interface
Serializable is a marker interface (has no body). It is just used to "mark" java classes which
support a certain capability.
It must be implemented by the class whose object you want to persist. Let's see the example
given below:
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
ObjectOutputStream class
The ObjectOutputStream class 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.
Constructor
1) public ObjectOutputStream(OutputStream out) throws IOException {}creates
an ObjectOutputStream that writes to the specified OutputStream.
Important Methods
Method Description
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. System.out.println("success");
12. }
13. }
success
download this example of serialization
Deserialization in java
Deserialization is the process of reconstructing the object from the serialized state.It is the
reverse operation of serialization.
ObjectInputStream class
Constructor
1) public ObjectInputStream(InputStream creates an ObjectInputStream
in) throws IOException {} that reads from the specified
InputStream.
Important Methods
Method Description
10. }
11. }
211 ravi
download this example of deserialization
If a class implements serializable then all its sub classes will also be serializable. Let's see the
example given below:
1. import java.io.Serializable;
2. class Person implements Serializable{
3. int id;
4. String name;
5. Person(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
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.
If a class has a reference of another class, all the references must be Serializable otherwise
serialization process will not be performed. In such case, NotSerializableException is thrown
at runtime.
1. class Address{
2. String addressLine,city,state;
Since Address is not Serializable, you can not serialize the instance of Student class.
If there is any static data member in a class, it will not be serialized because static is the part
of class not object.
Rule: In case of array or collection, all the objects of array or collection must be serializable.
If any object is not serialiizable, serialization will be failed.
Externalizable in java
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.
If you don't want to serialize any data member of a class, you can mark it as transient.
Java transient keyword is used in serialization. If you define any data member as transient, it
will not be serialized.
Let's take an example, I have declared a class as Student, it has three data members id, name and
age. If you serialize the object, all the values will be serialized but I don't want to serialize one
value, e.g. age then we can declare the age data member as transient.
In this example, we have created the two classes Student and PersistExample. The age data
member of the Student class is declared as transient, its value will not be serialized.
If you deserialize the object, you will get the default value for transient variable.
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. transient int age;//Now it will not be serialized
6. public Student(int id, String name,int age) {
7. this.id = id;
8. this.name = name;
9. this.age=age;
10. }
11. }
1. import java.io.*;
2. class PersistExample{
3. public static void main(String args[])throws Exception{
4. Student s1 =new Student(211,"ravi",22);//creating object
5. //writing object into file
6. FileOutputStream f=new FileOutputStream("f.txt");
7. ObjectOutputStream out=new ObjectOutputStream(f);
8. out.writeObject(s1);
9. out.flush();
10.
11. out.close();
12. f.close();
13. System.out.println("success");
14. }
15. }
Output:
success
1. import java.io.*;
2. class DePersist{
3. public static void main(String args[])throws Exception{
4. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
5. Student s=(Student)in.readObject();
6. System.out.println(s.id+" "+s.name+" "+s.age);
7. in.close();
8. }
9. }
211 ravi 0
As you can see, printing age of the student returns 0 because value of age was not serialized.
Java Networking
Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.
Java socket programming provides facility to share data between different computing devices.
Do You Know ?
• How to perform connection-oriented Socket Programming in networking ?
• How to display the data of any online web page ?
• How to get the IP address of any host name e.g. www.google.com ?
• How to perform connection-less socket programming in networking ?
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1) IP Address
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
• TCP
• FTP
• Telnet
• SMTP
• POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.
The port number is associated with the IP address for communication between two applications.
4) MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC.
6) Socket
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components uses the resources of system.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
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 such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. 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 menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
public void setSize(int width,int sets the size (width and height) of the
height) component.
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
6.
7. add(b);//adding button into frame
8. setSize(300,300);//frame size 300 width and 300 height
9. setLayout(null);//no layout manager
10. setVisible(true);//now frame will be visible, by default not visible
11. }
12. public static void main(String args[]){
13. First f=new First();
14. }}
download this example
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example
that sets the position of the awt button.
8.
9. f.add(b);
10. f.setSize(300,300);
11. f.setLayout(null);
12. f.setVisible(true);
13. }
14. public static void main(String args[]){
15. First2 f=new First2();
16. }}
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:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o 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
BorderLayout (LayoutManagers):
LayoutManagers:
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
displayed 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");
next>><<prev
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:
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. }
download this example
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. }
Java 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
Drawback of Applet
1. Plugin is required at client browser to execute applet.
Do You Know
1. Who is responsible to manage the life cycle of an applet ?
2. How to perform animation in applet ?
3. How to paint like paint brush in applet ?
4. How to display digital clock in applet ?
5. How to display analog clock in applet ?
6. How to communicate two applets ?
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
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
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).
To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
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>
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it
is for testing purpose only.
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. */
c:\>javac First.java
c:\>appletviewer First.java
Displaying Graphics in Applet
1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.
1. import java.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>
Displaying Image in Applet
Applet is mostly used in games and animation. For this purpose image is required to be
displayed. The java.awt.Graphics class provide a method drawImage() to display the image.
The java.applet.Applet class provides getImage() method that returns the object of Image.
Syntax:
1. public URL getDocumentBase(): is used to return the URL of the document in which
applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.
1. import java.awt.*;
2. import java.applet.*;
3.
4.
5. public class DisplayImage extends Applet {
6.
7. Image picture;
8.
9. 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>
JApplet class in Applet
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of
swing. The JApplet class extends the Applet class.
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.
myapplet.html
1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Digital clock in Applet
Digital clock can be created by using the Calendar and SimpleDateFormat class. Let's see the
simple example:
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() {
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;
myapplet.html
1. <html>
2. <body>
3. <applet code="MyClock.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
1. import java.applet.Applet;
2. import java.awt.Graphics;
3.
4. public class UseParam extends Applet{
5.
6. public void paint(Graphics g){
7. String str=getParameter("msg");
8. g.drawString(str,50, 50);
9. }
10.
11. }
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
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>
Java Reflection API
Java Reflection is a process of examining or modifying the run time behavior of a class at run
time.
The java.lang.Class class provides many methods that can be used to get metadata, examine and
change the run time behavior of a class.
The java.lang and java.lang.reflect packages provide classes for java reflection.
Where it is used
Do You Know ?
1. How many ways we can get the instance of Class class ?
2. How to create the javap tool ?
3. How to create the appletviewer tool ?
4. How to access the private method from outside the class ?
java.lang.Class class
There are 3 ways to get the instance of Class class. They are as follows:
1. class Simple{}
2.
3. class Test{
4. public static void main(String args[]){
5. Class c=Class.forName("Simple");
6. System.out.println(c.getName());
7. }
8. }
Output:Simple
It returns the instance of Class class. It should be used if you know the type. Moreover, it can be
used with primitives.
1. class Simple{}
2.
3. class Test{
4. void printName(Object obj){
5. Class c=obj.getClass();
6. System.out.println(c.getName());
7. }
8. public static void main(String args[]){
9. Simple s=new Simple();
10.
11. Test t=new Test();
12. t.printName(s);
13. }
14. }
15.
Output:Simple
If a type is available but there is no instance then it is possible to obtain a Class by appending
".class" to the name of the type.It can be used for primitive data type also.
1. class Test{
2. public static void main(String args[]){
3. Class c = boolean.class;
4. System.out.println(c.getName());
5.
6. Class c2 = Test.class;
7. System.out.println(c2.getName());
8. }
9. }
Output:boolean
Test
2) public boolean isArray(): determines if this Class object represents an array class.
Let's see the simple example of reflection api to determine the object type.
1. class Simple{}
2. interface My{}
3.
4. class Test{
5. public static void main(String args[]){
6. try{
7. Class c=Class.forName("Simple");
8. System.out.println(c.isInterface());
9.
10. Class c2=Class.forName("My");
11. System.out.println(c2.isInterface());
12.
13. }catch(Exception e){System.out.println(e);}
14.
15. }
16. }
Java Date
The java.util, java.sql and java.text packages contains classes for representing date and time.
Following classes are important for dealing with date in java.
o java.util.Date class
o java.sql.Date class
o java.text.DateFormat class
o java.text.SimpleDateFormat class
o java.util.Calendar class
o java.util.GregorianCalendar class
o java.sql.Time class
o java.sql.Timestamp class
o java.util.TimeZone class
1st way:
Output:
2nd way:
Output:
3rd way:
5. long millis=System.currentTimeMillis();
6. java.sql.Date date=new java.sql.Date(millis);
7. System.out.println(date);
Output:
2015-03-27
4th way:
2. Date date=java.util.Calendar.getInstance().getTime();
3. System.out.println(date);
Output:
The java.util.Date class represents date and time in java. It provides constructors and methods to
deal with date and time in java.
After Calendar class, most of the constructors and methods of java.util.Date class has been
deprecated. Here, we are not giving list of any deprecated constructor and method.
java.util.Date Constructors
java.util.Date Methods
1) boolean after(Date date) tests if current date is after the given date.
5) boolean equals(Date date) compares current date with given date for
equality.
8) int hashCode() returns the hash code value for this date
object.
9) void setTime(long time) changes the current date and time to given
time.
java.util.Date Example
Let's see the example to print date in java using java.util.Date class.
1st way:
Output:
2nd way:
Output:
The java.sql.Date class represents only date in java. It inherits java.util.Date class.
The java.sql.Date instance is widely used in JDBC because it represents the date that can be
stored in database.
Some constructors and methods of java.sql.Date class has been deprecated. Here, we are not
giving list of any deprecated constructor and method.
java.sql.Date Constructor
java.sql.Date Methods
5) static Date valueOf(LocalDate returns sql date object for the given
date) LocalDate.
6) static Date valueOf(String date) returns sql date object for the given
String.
Let's see the example to print date in java using java.sql.Date class.
Output:
2015-03-30
Let's see the example to convert string into java.sql.Date using valueOf() method.
6. import java.sql.Date;
Uday Singh(MCA), 09199511858 / 09835613557 Page 366
JAVA
Output:
2015-03-31
java.util.Date
The java.util.Date class represents date and time in java. It provides constructors and methods to
deal with date and time in java.
After Calendar class, most of the constructors and methods of java.util.Date class has been
deprecated. Here, we are not giving list of any deprecated constructor and method.
java.util.Date Constructors
java.util.Date Methods
1) boolean after(Date date) tests if current date is after the given date.
5) boolean equals(Date date) compares current date with given date for
equality.
8) int hashCode() returns the hash code value for this date
object.
9) void setTime(long time) changes the current date and time to given
time.
java.util.Date Example
Let's see the example to print date in java using java.util.Date class.
1st way:
Output:
2nd way:
4. long millis=System.currentTimeMillis();
5. java.util.Date date=new java.util.Date(millis);
6. System.out.println(date);
Output:
The java.text.SimpleDateFormat class provides methods to format and parse date and time in
java. The SimpleDateFormat is a concrete class for formatting and parsing date which inherits
java.text.DateFormat class.
Notice that formatting means converting date to string and parsing means converting string to
date.
Let's see the simple example to format date in java using java.text.SimpleDateFormat class.
2. import java.text.SimpleDateFormat;
3. import java.util.Date;
4. public class SimpleDateFormatExample {
5. public static void main(String[] args) {
6. Date date = new Date();
7. SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
8. String strDate= formatter.format(date);
9. System.out.println(strDate);
10. }
11. }
Test it Now
Output:
13/04/2015
Let's see the full example to format date and time in java using java.text.SimpleDateFormat
class.
7. import java.text.ParseException;
8. import java.text.SimpleDateFormat;
9. import java.util.Date;
10. import java.util.Locale;
11. public class SimpleDateFormatExample2 {
12. public static void main(String[] args) {
13. Date date = new Date();
Output:
Let's see the simple example to convert string into date using java.text.SimpleDateFormat
class.
6. import java.text.ParseException;
7. import java.text.SimpleDateFormat;
8. import java.util.Date;
9. public class SimpleDateFormatExample3 {
10. public static void main(String[] args) {
11. SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
12. try {
13. Date date = formatter.parse("31/03/2015");
14. System.out.println("Date is: "+date);
Output: