Java Tutorial
Java Tutorial
Java Tutorial or Core Java Tutorial or Java Programming Tutorial is a widely used robust
technology. Let's start learning of java from basic questions like what is java tutorial, core
java, where it is used, what type of applications are created in java and why use java.
What is Java
Java is a programming language and a platform.
Java Example
Let's have a quick look at java programming example. A detailed description of hello java
example is given in next page.
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is currently
used. Some of them are as follows:
1) Standalone Application
2) Web Application
An application that runs on the server side and creates dynamic page, is called web
application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web
applications in java.
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 application
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.
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.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
According to James Gosling "Java was one of the top choices along with Silk". Since java
was so unique, most of the team members preferred java.
8) Java is an island of Indonesia where first coffee was produced (called java coffee).
10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary
of Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
Features of Java
There is given many features of java. They are also 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
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behaviour.
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
A platform is the hardware or software environment in which a program runs. There are
two types of platforms software-based and hardware-based. Java provides software-
based platform. The Java platform differs from most other platforms in the sense that it's
a software-based platform that runs on top of other hardware-based platforms.It has two
components:
1. Runtime Environment
2. API(Application Programming Interface)
Secured
Java is secured because:
No explicit pointer
Programs run inside virtual machine sandbox.
Classloader- adds security by separating the package for the classes of the local
file system from those that are imported from network sources.
Bytecode Verifier- checks the code fragments for illegal code that can violate
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.
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
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. JVM, JRE and JDK are
platform dependent because configuration of each OS differs. But, Java is platform
independent.
The JVM performs following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime
environment.It is the implementation of JVM.It physically exists.It contains set of
libraries + other files that JVM uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun
Micro Systems.
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.
JVM (Java Virtual Machine)
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e.JVM is plateform
dependent).
What is JVM?
It is:
What it does?
The JVM performs following operation:
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:
Classloader is a subsystem of JVM that is used to load class files.
2) Class(Method) Area:
Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.
3) Heap:
It is the runtime data area in which objects are allocated.
4) Stack:
Java Stack stores frames.It holds local variables and partial results, and plays a part in
method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its
method invocation completes.
5) Program Counter Register:
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
In this page, we will learn about the variable and java data types. 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.
Types of Variable
There are three types of variables in java
local variable
instance variable
static variable
Local Variable
Instance Variable
A variable that is declared inside the class but outside the method is called instance
variable . It is not declared as static.
Static variable
boolean false 1 bi
char '\u0000' 2 by
byte 0 1 by
short 0 2 by
int 0 4 by
long 0L 8 by
float 0.0f 4 by
double 0.0d 8 by
U
nicode System
Unicode is a universal international standard character encoding that is capable of
representing most of the world's written languages.
Why java uses Unicode System?
Before Unicode, there were many language standards:
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
Object
Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e.
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For
example: to convense the customer differently, to draw something e.g. shape or rectangle
etc.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
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.
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e.
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For
example: to convense the customer differently, to draw something e.g. shape or rectangle
etc.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
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.
All the classes, interfaces, packages, methods and fields of java programming language are
given according to java naming convention.
Name Convention
class name should start with uppercase letter and be a noun
e.g. String, Color, Button, System, Thread etc.
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.
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
1. class Student1{
2. int id;//data member (also instance variable)
3. String name;//data member(also instance variable)
4.
5. public static void main(String args[]){
6. Student1 s1=new Student1();//creating an object of Student
7. System.out.println(s1.id);
8. System.out.println(s1.name);
9. }
10. }
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.
1. class Student2{
2. int rollno;
3. String name;
4.
5. void insertRecord(int r, String n){ //method
6. rollno=r;
7. name=n;
8. }
9.
10. void displayInformation(){System.out.println(rollno+" "+name);}//method
11.
12. public static void main(String args[]){
13. Student2 s1=new Student2();
14. Student2 s2=new Student2();
15.
16. s1.insertRecord(111,"Karan");
17. s2.insertRecord(222,"Aryan");
18.
19. s1.displayInformation();
20. s2.displayInformation();
21.
22. }
23. }
Test it Now
Output:111 Karan
222 Aryan
As you see in the above figure, object gets the memory in Heap area and reference
variable refers to the object allocated in the Heap memory area. Here, s1 and s2 both
are reference variables that refer to the objects allocated in memory.
1. class Rectangle{
2. int length;
3. int width;
4.
5. void insert(int l,int w){
6. length=l;
7. width=w;
8. }
9.
10. void calculateArea(){System.out.println(length*width);}
11.
12. public static void main(String args[]){
13. Rectangle r1=new Rectangle();
14. Rectangle r2=new Rectangle();
15.
16. r1.insert(11,5);
17. r2.insert(3,15);
18.
19. r1.calculateArea();
20. r2.calculateArea();
21. }
22. }
Output:55
45
What are the different ways to create an object in Java?
There are many ways to create an object in java. They are:
By new keyword
By newInstance() method
By clone() method
By factory method etc.
Annonymous object
Annonymous simply means nameless.An object that have no reference is known as
annonymous object.
If you have to use an object only once, annonymous object is a good approach.
1. class Calculation{
2.
3. void fact(int n){
4. int fact=1;
5. for(int i=1;i<=n;i++){
6. fact=fact*i;
7. }
8. System.out.println("factorial is "+fact);
9. }
10.
11. public static void main(String args[]){
12. new Calculation().fact(5);//calling method with annonymous object
13. }
14. }
Output:Factorial is 120
1. class Rectangle{
2. int length;
3. int width;
4.
5. void insert(int l,int w){
6. length=l;
7. width=w;
8. }
9.
10. void calculateArea(){System.out.println(length*width);}
11.
12. public static void main(String args[]){
13. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
14.
15. r1.insert(11,5);
16. r2.insert(3,15);
17.
18. r1.calculateArea();
19. r2.calculateArea();
20. }
21. }
Output:55
45
If a class have multiple methods by same name but different parameters, it is known
asMethod Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behaviour of the method because its name differs. So, we
perform method overloading to figure out the program quickly.
In java, Methood Overloading is not possible by changing the return type of the method.
1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10,10,10);
8. obj.sum(20,20);
9.
10. }
11. }
Test it Now
Output:30
40
1. class Calculation2{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(double a,double b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation2 obj=new Calculation2();
7. obj.sum(10.5,10.5);
8. obj.sum(20,20);
9.
10. }
11. }
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:
1. class Calculation3{
2. int sum(int a,int b){System.out.println(a+b);}
3. double sum(int a,int b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation3 obj=new Calculation3();
7. int result=obj.sum(20,20); //Compile Time Error
8.
9. }
10. }
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:
1. class Overloading1{
2. public static void main(int a){
3. System.out.println(a);
4. }
5.
6. public static void main(String args[]){
7. System.out.println("main() method invoked");
8. main(10);
9. }
10. }
Test it Now
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.
Output:40
60
1. class OverloadingCalculation2{
2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b){System.out.println("long arg method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation2 obj=new OverloadingCalculation2();
7. obj.sum(20,20);//now int arg sum() method gets invoked
8. }
9. }
Test it Now
1. class OverloadingCalculation3{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation3 obj=new OverloadingCalculation3();
7. obj.sum(20,20);//now ambiguity
8. }
9. }
Test it Now
One type is not de-promoted implicitly for example double cannot be depromoted
to any type implicitely.
Constructor in Java
1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value
4. Copying the values of one object into another
5. Does constructor perform other task instead initialization
Constructor 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.
1. class Bike1{
2. Bike1(){System.out.println("Bike is created");}
3. public static void main(String args[]){
4. Bike1 b=new Bike1();
5. }
6. }
Test it Now
Output:
Bike is created
Default constructor provides the default values to the object like 0, null etc. depending
on the type.
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.
1. class Student4{
2. int id;
3. String name;
4.
5. Student4(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student4 s1 = new Student4(111,"Karan");
13. Student4 s2 = new Student4(222,"Aryan");
14. s1.display();
15. s2.display();
16. }
17. }
Test it Now
Output:
111 Karan
222 Aryan
Output:
111 Karan 0
222 Aryan 25
The java compiler provides a default constructor if you don't have any constructor. Method is n
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.
1. class Student6{
2. int id;
3. String name;
4. Student6(int i,String n){
5. id = i;
6. name = n;
7. }
8.
9. Student6(Student6 s){
10. id = s.id;
11. name =s.name;
12. }
13. void display(){System.out.println(id+" "+name);}
14.
15. public static void main(String args[]){
16. Student6 s1 = new Student6(111,"Karan");
17. Student6 s2 = new Student6(s1);
18. s1.display();
19. s2.display();
20. }
21. }
Test it Now
Output:
111 Karan
111 Karan
1. class Student7{
2. int id;
3. String name;
4. Student7(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student7(){}
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student7 s1 = new Student7(111,"Karan");
13. Student7 s2 = new Student7();
14. s2.id=s1.id;
15. s2.name=s1.name;
16. s1.display();
17. s2.display();
18. }
19. }
Test it Now
Output:
111 Karan
111 Karan
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.
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }
Suppose there are 500 students in my college, now all instance data members will get
memory each time when object is created.All student have its unique rollno and name so
instance data member is good.Here, college refers to the common property of all objects.If
we make it static,this field will get memory only once.
1. class Counter{
2. int count=0;//will get memory when instance is created
3.
4. Counter(){
5. count++;
6. System.out.println(count);
7. }
8.
9. public static void main(String args[]){
10.
11. Counter c1=new Counter();
12. Counter c2=new Counter();
13. Counter c3=new Counter();
14.
15. }
16. }
Test it Now
Output:1
1
1
1. class Counter2{
2. static int count=0;//will get memory only once and retain its value
3.
4. Counter2(){
5. count++;
6. System.out.println(count);
7. }
8.
9. public static void main(String args[]){
10.
11. Counter2 c1=new Counter2();
12. Counter2 c2=new Counter2();
13. Counter2 c3=new Counter2();
14.
15. }
16. }
Test it Now
Output:1
2
3
Output:125
1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.
1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
Test it Now
Output:Compile Time Error
Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
1. class A3{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
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
variablethat refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
Suggestion: If you are beginner to java, lookup only two usage of this keyword.
Let's understand the problem if we don't use this keyword by the example given below:
1. class Student10{
2. int id;
3. String name;
4.
5. Student10(int id,String name){
6. id = id;
7. name = name;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student10 s1 = new Student10(111,"Karan");
13. Student10 s2 = new Student10(321,"Aryan");
14. s1.display();
15. s2.display();
16. }
17. }
Test it Now
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
1. class Student12{
2. int id;
3. String name;
4.
5. Student12(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10. public static void main(String args[]){
11. Student12 e1 = new Student12(111,"karan");
12. Student12 e2 = new Student12(222,"Aryan");
13. e1.display();
14. e2.display();
15. }
16. }
Test it Now
Output:111 Karan
222 Aryan
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
1. class Student14{
2. int id;
3. String name;
4. String city;
5.
6. Student14(int id,String name){
7. this.id = id;
8. this.name = name;
9. }
10. Student14(int id,String name,String city){
11. this(id,name);//now no need to initialize id and name
12. this.city=city;
13. }
14. void display(){System.out.println(id+" "+name+" "+city);}
15.
16. public static void main(String args[]){
17. Student14 e1 = new Student14(111,"karan");
18. Student14 e2 = new Student14(222,"Aryan","delhi");
19. e1.display();
20. e2.display();
21. }
22. }
Test it Now
1. class Student15{
2. int id;
3. String name;
4. Student15(){System.out.println("default constructor is invoked");}
5.
6. Student15(int id,String name){
7. id = id;
8. name = name;
9. this ();//must be the first statement
10. }
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[]){
14. Student15 e1 = new Student15(111,"karan");
15. Student15 e2 = new Student15(222,"Aryan");
16. e1.display();
17. e2.display();
18. }
19. }
Test it Now
1. class S{
2. void m(){
3. System.out.println("method is invoked");
4. }
5. void n(){
6. this.m();//no need because compiler does it for you.
7. }
8. void p(){
9. n();//complier will add this to invoke n() method as this.n()
10. }
11. public static void main(String args[]){
12. S s1 = new S();
13. s1.p();
14. }
15. }
Test it Now
Output:method is invoked
1. class S2{
2. void m(S2 obj){
3. System.out.println("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8.
9. public static void main(String args[]){
10. S2 s1 = new S2();
11. s1.p();
12. }
13. }
Test it Now
Output:method is invoked
1. class B{
2. A4 obj;
3. B(A4 obj){
4. this.obj=obj;
5. }
6. void display(){
7. System.out.println(obj.data);//using data member of A4 class
8. }
9. }
10.
11. class A4{
12. int data=10;
13. A4(){
14. B b=new B(this);
15. b.display();
16. }
17. public static void main(String args[]){
18. A4 a=new A4();
19. }
20. }
Test it Now
Output:10
Output:Hello java
1. class A5{
2. void m(){
3. System.out.println(this);//prints same reference ID
4. }
5.
6. public static void main(String args[]){
7. A5 obj=new A5();
8. System.out.println(obj);//prints the reference ID
9.
10. obj.m();
11. }
12. }
Test it Now
Output:A5@22b3ea59
A5@22b3ea59
Inheritance in Java
1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in java in case of class?
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.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
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.
In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.
Note: Multiple inheritance is not supported in java through class.
When a class extends multiple classes i.e. known as multiple inheritance. For Example:
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.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Test it Now
Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents
HAS-A relationship.
Consider a situation, Employee object contains many informations such as id, name,
emailId etc. It contains one more object named address, which contains its own
informations such as city, state, country, zipcode etc. as given below.
1. class Employee{
2. int id;
3. String name;
4. Address address;//Address is a class
5. ...
6. }
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
In this example, we have created the reference of Operation class in the Circle class.
1. class Operation{
2. int square(int n){
3. return n*n;
4. }
5. }
6.
7. class Circle{
8. Operation op;//aggregation
9. double pi=3.14;
10.
11. double area(int radius){
12. op=new Operation();
13. int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
14. return pi*rsquare;
15. }
16.
17.
18.
19. public static void main(String args[]){
20. Circle c=new Circle();
21. double result=c.area(5);
22. System.out.println(result);
23. }
24. }
Test it Now
Output:78.5
Address.java
Emp.java
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.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike extends Vehicle{
5.
6. public static void main(String args[]){
7. Bike obj = new Bike();
8. obj.run();
9. }
10. }
Test it Now
Output:Vehicle is running
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike2 extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6.
7. public static void main(String args[]){
8. Bike2 obj = new Bike2();
9. obj.run();
10. }
Test it Now
1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 8;}
7. }
8.
9. class ICICI extends Bank{
10. int getRateOfInterest(){return 7;}
11. }
12. class AXIS extends Bank{
13. int getRateOfInterest(){return 9;}
14. }
15.
16. class Test2{
17. public static void main(String args[]){
18. SBI s=new SBI();
19. ICICI i=new ICICI();
20. AXIS a=new AXIS();
21. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
22. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
23. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
24. }
25. }
Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Whenever you create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.
1. class Vehicle{
2. int speed=50;
3. }
4. class Bike3 extends Vehicle{
5. int speed=100;
6. void display(){
7. System.out.println(speed);//will print speed of Bike
8. }
9. public static void main(String args[]){
10. Bike3 b=new Bike3();
11. b.display();
12. }
13. }
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.
Output:50
1. class Vehicle{
2. Vehicle(){System.out.println("Vehicle is created");}
3. }
4.
5. class Bike5 extends Vehicle{
6. Bike5(){
7. super();//will invoke parent class constructor
8. System.out.println("Bike is created");
9. }
10. public static void main(String args[]){
11. Bike5 b=new Bike5();
12.
13. }
14. }
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.
1. class Vehicle{
2. Vehicle(){System.out.println("Vehicle is created");}
3. }
4.
5. class Bike6 extends Vehicle{
6. int speed;
7. Bike6(int speed){
8. this.speed=speed;
9. System.out.println(speed);
10. }
11. public static void main(String args[]){
12. Bike6 b=new Bike6(10);
13. }
14. }
Test it Now
Output:Vehicle is created
10
1. class Person{
2. void message(){System.out.println("welcome");}
3. }
4.
5. class Student16 extends Person{
6. void message(){System.out.println("welcome to java");}
7.
8. void display(){
9. message();//will invoke current class message() method
10. super.message();//will invoke parent class message() method
11. }
12.
13. public static void main(String args[]){
14. Student16 s=new Student16();
15. s.display();
16. }
17. }
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.
Output:welcome
Instance Initializer block is used to initialize the instance data member. It run each
time when object of the class is created.
The initialization of the instance variable can be directly but there can be performed
extra operations while 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:
1. class Bike{
2. int speed=100;
3. }
1. class Bike7{
2. int speed;
3.
4. Bike7(){System.out.println("speed is "+speed);}
5.
6. {speed=100;}
7.
8. public static void main(String args[]){
9. Bike7 b1=new Bike7();
10. Bike7 b2=new Bike7();
11. }
12. }
Test it Now
Output:speed is 100
speed is 100
There are three places in java where you can perform operations:
1. method
2. constructor
3. block
Note: The java compiler copies the code of instance initializer block in
every constructor.
Rules for instance initializer block :
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.
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.
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now
1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
7. }
8. }
Test it Now
Output:running...
If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an
employee.
1. class Bike10{
2. final int speedlimit;//blank final variable
3.
4. Bike10(){
5. speedlimit=70;
6. System.out.println(speedlimit);
7. }
8.
9. public static void main(String args[]){
10. new Bike10();
11. }
12. }
Test it Now
Output:70
If you declare any parameter as final, you cannot change the value of it.
1. class Bike11{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final
4. n*n*n;
5. }
6. public static void main(String args[]){
7. Bike11 b=new Bike11();
8. b.cube(5);
9. }
10. }
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.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting
Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.
1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splender extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splender();//upcasting
9. b.run();
10. }
11. }
Test it Now
1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 8;}
7. }
8.
9. class ICICI extends Bank{
10. int getRateOfInterest(){return 7;}
11. }
12. class AXIS extends Bank{
13. int getRateOfInterest(){return 9;}
14. }
15.
16. class Test3{
17. public static void main(String args[]){
18. Bank b1=new SBI();
19. Bank b2=new ICICI();
20. Bank b3=new AXIS();
21. System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
22. System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
23. System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());
24. }
25. }
Test it Now
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.
1. class Bike{
2. int speedlimit=90;
3. }
4. class Honda3 extends Bike{
5. int speedlimit=150;
6.
7. public static void main(String args[]){
8. Bike obj=new Honda3();
9. System.out.println(obj.speedlimit);//90
10. }
Test it Now
Output:90
1. class Animal{
2. void eat(){System.out.println("eating");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("eating fruits");}
7. }
8.
9. class BabyDog extends Dog{
10. void eat(){System.out.println("drinking milk");}
11.
12. public static void main(String args[]){
13. Animal a1,a2,a3;
14. a1=new Animal();
15. a2=new Dog();
16. a3=new BabyDog();
17.
18. a1.eat();
19. a2.eat();
20. a3.eat();
21. }
22. }
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
Let's understand the type of instance.
1. int data=30;
1. class Dog{
2. public static void main(String args[]){
3. Dog d1;//Here d1 is a type of Dog
4. }
5. }
1. class Animal{}
2.
3. class Dog extends Animal{
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. }
7. }
Here d1 is an instance of Dog class, but it is also an instance of Animal.
static binding
When type of the object is determined at compiled time(by the compiler), it is known as
static binding.
If there is any private, final or static method in a class, there is static binding.
Example of static binding
1. class Dog{
2. private void eat(){System.out.println("dog is eating...");}
3.
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. d1.eat();
7. }
8. }
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Output:dog is eating...
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.
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
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
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
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
2 4 5
4 4 5
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
1. class Operation2{
2. int data=50;
3.
4. void change(Operation2 op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7.
8.
9. public static void main(String args[]){
10. Operation2 op=new Operation2();
11.
12. System.out.println("before change "+op.data);
13. op.change(op);//passing object
14. System.out.println("after change "+op.data);
15.
16. }
17. }
download this example
Output:before change 50
after change 150
strictfp keyword
The strictfp keyword ensures that you will get the same result on every platform if you
perform operations in the floating-point variable. The precision may differ from
platform to platform that is why java programming language have provided the
strictfp keyword, so that you get same result on every platform. So, now you have
better control over the floating-point arithmetic.
1. class B{
2. strictfp abstract void m();//Illegal combination of modifiers
3. }
1. class B{
2. strictfp int data=10;//modifier strictfp not allowed here
3. }
1. class B{
2. strictfp B(){}//modifier strictfp not allowed here
3. }
1. package com.abc;
2. /** This class is a user-defined class that contains one methods cube.*/
3. public class M{
4.
5. /** The cube method prints cube of the given number */
6. public static void cube(int n){System.out.println(n*n*n);}
7. }
To create the document API, you need to use the javadoc tool followed by java file name.
There is no need to compile the javafile.
javadoc M.java
to generate the document api. Now, there will be created a lot of html files. Open
The 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
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.
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
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.
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
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.
Why string objects are immutable in java?
Because java uses the concept of string literal.Suppose there are 5 reference
variables,all referes to one object "sachin".If one reference variable changes the value
of the object, it will be affected to all the reference variables. That is why string
objects are immutable in java.
1. By equals() method
2. By = = operator
3. By compareTo() method
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)
7. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
8. }
9. }
Test it Now
Output:true
false
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
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
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.
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.
Note: Index starts from 0.
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
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.
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
Sachin
Sachin
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
1. int a=10;
2. String s=String.valueOf(a);
3. System.out.println(s+10);
Output:
1010
Java String replace() method
The string replace() method replaces all occurrence of first sequence of character with
second sequence of character.
Output:
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.
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. }
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }
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. }
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. }
6) StringBuffer capacity() method
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. }
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. }
public int length() is used to return the length of the string i.e.
total number of characters.
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. }
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. }
3) StringBuilder replace() method
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. }
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. }
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. }
10. }
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. }
In this page, we will learn about java exception, its type and the difference between
checked and unchecked exceptions.
What is exception
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
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;
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
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3) Error
1. int a=50/0;//ArithmeticException
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
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
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{}
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.
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
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. }
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;
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. }
13. public static void main(String args[]){
14. TestExceptionPropagation1 obj=new TestExceptionPropagation1();
15. obj.p();
16. System.out.println("normal flow...");
17. }
18. }
Test it Now
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
Output:Compile Time Error
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
1. 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.
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...
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
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.
6. class TestExceptionChild1 extends Parent{
7. void msg()throws ArithmeticException{
8. System.out.println("child");
9. }
10. public static void main(String args[]){
11. Parent p=new TestExceptionChild1();
12. p.msg();
13. }
14. }
Test it Now
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
By the help of custom exception, you can have your own exception and message.
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. }
1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer classincluding 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 ?
o Can we define a class within the interface ?
Type Description
Syntax:
1. class Outer{
2. //code
3. class Inner{
4. //code
5. }
6. }
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
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. }
Output:
nice fruits
Output:
nice fruits
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
Output:
data is 30
In this example, you need to create the instance of static nested class because it has
instance method msg(). But you don't need to create the object of Outer class because
nested class is static and static properties, methods or classes can be accessed without
object.
1. 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
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
As you can see in the above example, we are acessing the Message interface by its outer
interface Showable because it cannot be accessed directly. It is just like almirah inside
the room, we cannot access the almirah directly because we must enter the room first.
In collection frameword, sun microsystem has provided a nested interface Entry. Entry is
the subinterface of Map i.e. accessed by Map.Entry.
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.
10. public static void main(String args[]){
11. A.Message message=new TestNestedInterface2();//upcasting here
12. message.msg();
13. }
14. }
Test it Now
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. }
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
As you can see in the above example, we are acessing the Message interface by its outer
interface Showable because it cannot be accessed directly. It is just like almirah inside
the room, we cannot access the almirah directly because we must enter the room first.
In collection frameword, sun microsystem has provided a nested interface Entry. Entry is
the subinterface of Map i.e. accessed by Map.Entry.
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.
10. public static void main(String args[]){
11. A.Message message=new TestNestedInterface2();//upcasting here
12. message.msg();
13. }
14. }
Test it Now
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. }
A thread can be in one of the five states. According to sun, there is only 4 states
inthread life cycle in java new, runnable, non-runnable and terminated. There is no
running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread 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:
If you are not extending the Thread class,your class object would not be treated as a
thread object.So you need to explicitely create Thread class object.We are passing the
object of your class that implements Runnable so that your class run() method may
execute.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the
threads.
Output:
2
3
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.
running
Output:running...
Problem if you direct call run() method
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...
After changling name of t1:Sonoo Jaiswal
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.
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changeling name of t1:Sonoo Jaiswal
running...
Output:Thread-0
Thread-1
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.
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.
Methods for Java Daemon thread by Thread class
The java.lang.Thread class provides two methods for java daemon thread.
File: MyThread.java
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
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 = "+messag
e);
10. processmessage();//call processmessage method that sleeps the thread for 2 seconds
12. }
13. private void processmessage() {
14. try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }
15. }
16. }
File: JavaThreadPoolExample.java
Output:
pool-1-thread-2 (End)
pool-1-thread-1 (End)
pool-1-thread-3 (End)
pool-1-thread-4 (End)
pool-1-thread-5 (End)
pool-1-thread-2 (End)
pool-1-thread-1 (End)
pool-1-thread-4 (End)
pool-1-thread-3 (End)
pool-1-thread-5 (End)
Output:task one
task one
task one
Program of performing single task by multiple threads
Output:task one
task one
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
Output:task one
task two
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;
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.
Java uses the concept of stream to make I/O operation fast. The java.io package contains
all the classes required for input and output operations.
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
InputStream class
1) public abstract int read()throws reads the next byte of data from the input strea
IOException:
2) public int available()throws IOException: returns an estimate of the number of bytes that
stream.
3) public void close()throws IOException: is used to close the current input stream.
FileInputStream and FileOutputStream (File
Handling)
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.
It should be used to read byte-oriented data for example to read image, audio, video etc.
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. }
download this example
ByteArrayOutputStream() creates a new byte array output stream with the initial capacity of 3
necessary.
ByteArrayOutputStream(int creates a new byte array output stream, with a buffer capacity of th
size)
1) public synchronized void writeTo(OutputStream out) throws writes the complete contents of this b
IOException specified output stream.
2) public void write(byte b) throws IOException writes byte into this stream.
3) public void write(byte[] b) throws IOException writes byte array into this stream.
4) public void flush() flushes this stream.
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...
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.
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. }
download this example of SequenceInputStream
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...
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 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...
1) public int read() returns a character in ASCII form. It returns -1 at the end
of 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. }
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.
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
data is: stop
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 con
2) public String readLine(String fmt,Object... args) it provides a formatted prompt then reads the s
3) public char[] readPassword() is used to read password that is not being displa
4) public char[] readPassword(String fmt,Object... it provides a formatted prompt then reads the p
args) the console.
System class provides a static method console() that returns the unique instance of Console
class.
1. Console c=System.console();
Output:
Output:
Enter password:
Password is: sonoo
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.
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:
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