Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

JAVA Notes-1 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 122

Unit-I

Object-Oriented
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behaviour.
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 is a high level, robust, secured and object-oriented programming language.
Platform: Any hardware or software environment in which a program runs, is known as a
platform. Since Java has its own runtime environment (JRE) and API, it is called platform.
Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is currently
used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as irctc.co.in, javatpoint.com etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.
Types of Java Applications
There are mainly 4 type of applications that can be created using java programming:
1) Standalone Application
It is also known as desktop application or window-based application. An application that we
need to install on every machine such as media player, antivirus etc. AWT and Swing are used in
java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates dynamic page, is called web application.
Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the advantage
of high level security, load balancing and clustering. In java, EJB is used for creating enterprise
applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used for
creating mobile applications.
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.
Currently, Java is used in internet programming, mobile devices, games, e-business
solutions etc. There are given the major points that describes the history of java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
Why sun choosed "Oak" name?
5) Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Why sun choosed "Java" name?
7) Why they choose java name for java language? The team gathered to choose a new name.
The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They wanted
something that reflected the essence of the technology: revolutionary, dynamic, lively, cool,
unique, and easy to spell and fun to say.
According to James Gosling "Java was one of the top choices along with Silk". Since java was
so unique, most of the team members preferred java.
8) Java is an island of Indonesia where first coffee was produced (called java coffee).
9) Notice that Java is just a name not an acronym.
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.
12) JDK 1.0 released in(January 23, 1996).
Java Version History
There are many java versions that has been released. Current stable release of Java is Java SE 8.
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)
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. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
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.
No need to remove unreferenced objects because there is Automatic Garbage Collection
in java.
Object-oriented
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software development
and maintenance by providing some rules.
Basic concepts of OOPs are:
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 is a software-based
platform that runs on the top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java
code is compiled by the compiler and converted into bytecode. This bytecode is a platform-
independent code because it can be run on multiple platforms i.e. Write Once and Run
Anywhere(WORA).
Secured
Java is secured because:
o No explicit pointer
o Java Programs run inside virtual machine sandbox

o Classloader: adds security by separating the package for the classes of the local file
system from those that are imported from network sources.
o Bytecode Verifier: checks the code fragments for illegal code that can violate access
right to objects.
o 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 fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory for both 32 and 64
bit architectures.
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 doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications etc.
C++ vs Java
There are many differences and similarities between C++ programming language and Java. A list
of top differences between C++ and Java are given below:
Comparison Index C++ Java
Platform- C++ is platform-dependent. Java is platform-independent.
independent
Mainly used for C++ is mainly used for Java is mainly used for application
system programming. programming. It is widely used in
window, web-based, enterprise and
mobile applications.
Goto C++ supports goto statement. Java doesn't support goto statement.
Multiple C++ supports multiple Java doesn't support multiple inheritance
inheritance inheritance. through class. It can be achieved by
interfaces in java.
Operator C++ supports operator Java doesn't support operator
Overloading overloading. overloading.
Pointers C++ supports pointers. You Java supports pointer internally. But you
can write pointer program in can't write the pointer program in java.
C++. It means java has restricted pointer
support in java.
Compiler and C++ uses compiler only. Java uses compiler and interpreter both.
Interpreter
Call by Value and C++ supports both call by Java supports call by value only. There
Call by reference value and call by reference. is no call by reference in java.
Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.
Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies
on third-party libraries for
thread support.
Documentation C++ doesn't support Java supports documentation comment
comment documentation comment. (/** ... */) to create documentation for
java source code.
Virtual Keyword C++ supports virtual keyword Java has no virtual keyword. We can
so that we can decide whether override all non-static methods by
or not override a function. default. In other words, non-static
methods are virtual by default.
unsigned right C++ doesn't support >>> Java supports unsigned right shift >>>
shift >>> operator. operator that fills zero at the top for the
negative numbers. For positive numbers,
it works same like >> operator.
Inheritance Tree C++ creates a new inheritance Java uses single inheritance tree always
tree always. because all classes are the child of
Object class in java. Object class is the
root of inheritance tree in java.
Understanding first java program
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
o class keyword is used to declare a class in java.
o public keyword is an access modifier which represents visibility, it means it is visible to
all.
o static is a keyword, if we declare any method as static, it is known as static method. The
core advantage of static method is that there is no need to create object to invoke the
static method. The main method is executed by the JVM, so it doesn't require to create
object to invoke the main method. So it saves memory.
o void is the return type of the method, it means it doesn't return any value.
o main represents startup of the program.
o String[] args is used for command line argument. We will learn it later.
o System.out.println() is used print statement. We will learn about the internal working of
System.out.println statement later.
How many ways can we write a java program
There are many ways to write a java program. The modifications that can be done in a java
program are given below:
1) By changing sequence of the modifiers, method prototype is not changed.
Let's see the simple code of main method.
1. static public void main(String args[])
2) subscript notation in java array can be used after type, before variable or after variable.
Let's see the different codes to write the main method.
1. public static void main(String[] args)
2. public static void main(String []args)
3. public static void main(String args[])
3) You can provide var-args support to main method by passing 3 ellipses (dots)
Let's see the simple code of using var-args in main method. We will learn about var-args later in
Java New Features chapter.
1. public static void main(String... args)
4) Having semicolon at the end of class in java is optional.
Let's see the simple code.
class A{
static public void main(String... args){
System.out.println("hello java4");
}
};
Valid java main method signature
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
public static void main(String... args)
static public void main(String[] args)
public static final void main(String[] args)
final public static void main(String[] args)
final strictfp public static void main(String[] args)
Invalid java main method signature
public void main(String[] args)
static void main(String[] args)
public void static main(String[] args)
abstract public static void main(String[] args)
Resolving an error "javac is not recognized as an internal or external command" ?
If there occurs a problem like displayed in the below figure, you need to set path. Since DOS
doesn't know javac or java, we need to set path. Path is not required in such a case if you save
your program inside the jdk/bin folder. But its good approach to set path. Click here for
Internal Details of Hello Java Program
In the previous page, we have learned about the first program, how to compile and how to run
the first java program. Here, we are going to learn, what happens while compiling and running
the java program. Moreover, we will see some question based on the first program.
What happens at compile time?
At compile time, java file is compiled by Java Compiler (It does not interact with OS) and
converts the java code into bytecode.

What happens at runtime?


At runtime, following steps are performed:
Classloader: is the subsystem of JVM that is used to load class files.
Bytecode Verifier: checks the code fragments for illegal code that can violate access right to
objects.
Interpreter: read bytecode stream then execute the instructions.
Q)Can you save a java source file by other name than the class name?
Yes, if the class is not public. It is explained in the figure given below:

Q)Can you have multiple classes in a java source file?


Yes, like the figure given below illustrates:
Difference between JDK, JRE and JVM
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 Virtual 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:
o Loads code
o Verifies code
o Executes code
o 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 platform dependent).
What is JVM
It is:
1. A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by
Sun and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run
the java class, an instance of JVM is created.
What it does
The JVM performs following operation:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JVM provides definitions for the:
o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
Internal Architecture of JVM
Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine 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.
6) Native Method Stack
It contains all the native methods used in the application.
7) Execution Engine
It contains:
1) A virtual processor
2) Interpreter: Read bytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler: It is used to improve the performance.JIT compiles parts of
the byte code that have similar functionality at the same time, and hence reduces the amount
of time needed for compilation.Here the term ?compiler? refers to a translator from the
instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.
variables and Data Types in Java
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.
There are two types of data types in java: primitive and non-primitive.
Variable
Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.
1. int data=50;//Here data is variable
Types of Variable
There are three types of variables in java:
o local variable
o instance variable
o static variable

1) Local Variable
A variable which is declared inside the method is called local variable.
2) Instance Variable
A variable which is declared inside the class but outside the method, is called instance variable .
It is not declared as static.
3) Static variable
A variable that is declared as static is called static variable. It cannot be local.
We will have detailed learning of these variables in next chapters.
Example to understand the types of variables in java
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
Data Types in Java
Data types represent the different values to be stored in the variable. In java, there are two types
of data types:
o Primitive data types
o Non-primitive data types
Data Type Default Value Default size
boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Why char uses 2 byte in java and what is \u0000 ?
It is because java uses Unicode system than ASCII code system. The \u0000 is the lowest range
of Unicode system. To get detail explanation about Unicode visit next page.
Java Variable Example: Narrowing (Typecasting)
class Simple{
public static void main(String[] args){
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}}
Output:
10.5
10
Java Variable Example: Overflow
class Simple{
public static void main(String[] args){
//Overflow
int a=130;
byte b=(byte)a;
System.out.println(a);
System.out.println(b);
}}
Output:
130
-126
Unicode 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:
o ASCII (American Standard Code for Information Interchange) for the United States.
o ISO 8859-1 for Western European Language.
o KOI-8 for Russian.
o GB18030 and BIG-5 for chinese, and so on.
Problem
This caused two problems:
1. A particular code value corresponds to different letters in the various language
standards.
2. The encodings for languages with large character sets have variable length.Some
common characters are encoded as single bytes, other require two or more byte.
Solution
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF
Operators in java
Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in java which are given below:
o Unary Operator,
o Arithmetic Operator,
o shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative */%
additive +-
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Java Unary Operator Example: ++ and --
class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Output:
10
12
12
10

Java Unary Operator Example: ~ and !


class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}}
Output:
-11
9
false
true
Java Arithmetic Operator Example: Expression
class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}
Output:
21
Java Shift Operator Example: Left Shift
class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
}}
Output:
40
80
Java Shift Operator Example: Right Shift
class OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Output:
2
5
2
Java Shift Operator Example: >> vs >>>
class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For nagative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}}
Output:
5
5
-5
1073741819
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check second condition if first condition is false. It checks
second condition only if first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}
Output:
false
false
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check second condition if first condition is true. It checks second
condition only if first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}}
Output:
true
true
true
10
true
11
Java Ternary Operator Example
class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
2
Java Assignment Operator Example
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
Output:
14
16
Java Assignment Operator Example: Adding short
class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}}
Output:
Compile time error
After type cast:
class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}}
Output:
20
Java If-else Statement
The Java if statement is used to test the condition. It checks boolean condition: true or false.
There are various types of if statement in java.
o if statement
o if-else statement
o nested if statement
o if-else-if ladder
Java IF Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}
Example:
public class IfExample {
public static void main(String[] args) {
int age=20;
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
Output:
Age is greater than 18
Java IF-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}

Example:
public class IfElseExample {
public static void main(String[] args) {
int number=13;
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}
Output:
odd number
Java IF-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.

Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

Example:
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;

if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Output:
C grade
Java Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Example:
public class SwitchExample {
public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output:
20
Java Switch Statement is fall-through
The java switch statement is fall-through. It means it executes all statement after first match if
break statement is not used with switch cases.
Example:
public class SwitchExample2 {
public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");
case 20: System.out.println("20");
case 30: System.out.println("30");
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output:
20
30
Not in 10, 20 or 30
Java For Loop
The Java for loop is used to iterate a part of the program several times. If the number of iteration
is fixed, it is recommended to use for loop.
There are three types of for loop in java.
o Simple For Loop
o For-each or Enhanced For Loop
o Labeled For Loop
Java Simple For Loop
The simple for loop is same as C/C++. We can initialize variable, check condition and
increment/decrement value.
Syntax:
for(initialization;condition;incr/decr){
//code to be executed
}
}

Example:
public class ForExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10

Java For-each Loop


The for-each loop is used to traverse array or collection in java. It is easier to use than simple for
loop because we don't need to increment value and use subscript notation.
It works on elements basis not index. It returns element one by one in the defined variable.
Syntax:
for(Type var:array){
//code to be executed
}
Example:
public class ForEachExample {
public static void main(String[] args) {
int arr[]={12,23,44,56,78};
for(int i:arr){
System.out.println(i);
}
}
}
Output:
12
23
44
56
78
Java Labeled For Loop
We can have name of each for loop. To do so, we use label before the for loop. It is useful if we
have nested for loop so that we can break/continue specific for loop.
Normally, break and continue keywords breaks/continues the inner most for loop only.
Syntax:
labelname:
for(initialization;condition;incr/decr){
//code to be executed
}

Example:
public class LabeledForExample {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
11
12
13
21
If you use break bb;, it will break inner loop only which is the default behavior of any loop.
public class LabeledForExample {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
11
12
13
21
31
32
33
Java While Loop
The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.
Syntax:
while(condition){
//code to be executed
}
Example:
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=5){
System.out.println(i);
i++;
}
}
}
Output:
1
2
3
4
5
Java do-while Loop
The Java do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to
use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed
}while(condition);
Example:
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=5);
}
}
Output:
1
2
3
4
5
Java Infinitive do-while Loop
If you pass true in the do-while loop, it will be infinitive do-while loop.
Syntax:
Now, you need to press ctrl+c to exit from the program.
Java Break Statement
The Java break is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop.
Syntax:
jump-statement;
break;

Java Break Statement with Loop

Example:
public class BreakExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
Java Break Statement with Switch
To understand the example of break with switch statement, please visit here: Java Switch
Statement.
Java Continue Statement
The Java continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it continues
only inner loop.
Syntax:
jump-statement;
continue;
Java Continue Statement Example
Example:
public class ContinueExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
if(i==5){
continue;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
Java OOPs Concepts
In this page, we will learn about basics of OOPs. Object Oriented Programming is a paradigm
that provides many concepts such as inheritance, data binding, polymorphism etc.
Simula is considered as the first object-oriented programming language. The programming
paradigm where everything is represented as an object, is known as truly object-oriented
programming language.
Smalltalk is considered as the first truly object-oriented programming language.
OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o 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
convince the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve 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.
Advantage of OOPs over Procedure-oriented programming language
1)OOPs makes development and maintenance easier where as in Procedure-oriented
programming language it is not easy to manage if code grows as project size grows.
2)OOPs provides data hiding whereas in Procedure-oriented programming language a global
data can be accessed from anywhere.
3)OOPs provides ability to simulate real-world event much more effectively. We can provide
the solution of real word problem if we are using the Object-Oriented Programming language.

What is difference between object-oriented programming language and object-based


programming language?
Object based programming language follows all the features of OOPs except Inheritance.
JavaScript and VBScript are examples of object based programming languages.
Java Naming conventions
Java naming convention is a rule to follow as you decide what to name your identifiers such as
class, package, variable, constant, method etc.
But, it is not forced to follow. So, it is known as convention not rule.
All the classes, interfaces, packages, methods and fields of java programming language are given
according to java naming convention.
Advantage of naming conventions in java
By using standard Java naming conventions, you make your code easier to read for yourself and
for other programmers. Readability of Java program is very important. It indicates that less
time is spent to figure out what the code does.
Name Convention

class name should start with uppercase letter and be a noun e.g. String, Color, Button,
System, Thread etc.
interface should start with uppercase letter and be an adjective e.g. Runnable, Remote,
name ActionListener etc.
method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(),
print(), println() etc.
variable should start with lowercase letter e.g. firstName, orderNumber etc.
name
package should be in lowercase letter e.g. java, lang, sql, util etc.
name
constants should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.
name
CamelCase in java naming conventions
Java follows camelcase syntax for naming the class, interface, method and variable.
If name is combined with two words, second word will start with uppercase letter always e.g.
actionPerformed(), firstName, ActionEvent, ActionListener etc.
Object and Class in Java
In this page, we will learn about java objects and classes. In object-oriented programming
technique, we design a program using objects and classes.
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 (tangible and intangible). The example of intangible object is
banking system.
An object has three characteristics:
o state: represents data (value) of an object.
o behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
o identity: Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But, it is used internally by the JVM to identify each
object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is
used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are created.
So object is the instance(result) of a class.
Object Definitions:
o Object is a real world entity.
o Object is a run time entity.
o Object is an entity which has state and behavior.
o Object is an instance of a class.
Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides
data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
1. <class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
1. 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

Rule: If there is no constructor in a class, compiler automatically creates a default


constructor.
Q) What is the purpose of default constructor?
Default constructor provides the default values to the object like 0, null etc. depending on the
type.
Example of default constructor that displays the default values
1. class Student3{
2. int id;
3. String name;
4.
5. void display(){System.out.println(id+" "+name);}
6.
7. public static void main(String args[]){
8. Student3 s1=new Student3();
9. Student3 s2=new Student3();
10. s1.display();
11. s2.display();
12. }
13. }
Test it Now
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you
a default constructor.Here 0 and null values are provided by default constructor.
Java parameterized constructor
A constructor that have parameters is known as parameterized constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
1. 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

Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
Example of Constructor Overloading
1. class Student5{
2. int id;
3. String name;
4. int age;
5. Student5(int i,String n){
6. id = i;
7. name = n;
8. }
9. Student5(int i,String n,int a){
10. id = i;
11. name = n;
12. age=a;
13. }
14. void display(){System.out.println(id+" "+name+" "+age);}
15.
16. public static void main(String args[]){
17. Student5 s1 = new Student5(111,"Karan");
18. Student5 s2 = new Student5(222,"Aryan",25);
19. s1.display();
20. s2.display();
21. }
22. }
Test it Now
Output:
111 Karan 0
222 Aryan 25

Difference between constructor and method in java


There are many differences between constructors and methods. They are given below.
Java Constructor Java Method

Constructor is used to initialize the state of an Method is used to expose


object. behaviour of an object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if Method is not provided by


you don't have any constructor. compiler in any case.
Constructor name must be same as the class name. Method name may or may not be
same as class name.

Java Copy Constructor


There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
o By constructor
o By assigning the values of one object into another
o 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
Q) Does constructor return any value?
Ans:yes, that is current class instance (You cannot use return type yet it returns a value).
Can constructor perform other tasks instead of initialization?
Yes, like object creation, starting a thread, calling method etc. You can perform any operation in
the constructor as you perform in the method.
Java static keyword
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 can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class
1) Java static variable
If you declare any variable as static, it is known static variable.
o 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.
o The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Understanding problem without static variable
1. 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.

Java static property is shared to all objects.

Example of static variable


1. //Program of static variable
2.
3. class Student8{
4. int rollno;
5. String name;
6. static String college ="ITS";
7.
8. Student8(int r,String n){
9. rollno = r;
10. name = n;
11. }
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13.
14. public static void main(String args[]){
15. Student8 s1 = new Student8(111,"Karan");
16. Student8 s2 = new Student8(222,"Aryan");
17.
18. s1.display();
19. s2.display();
20. }
21. }
Test it Now
Output:111 Karan ITS
222 Aryan ITS
Program of counter without static variable
In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object
will have the copy of the instance variable, if it is incremented, it won't reflect to other objects.
So each objects will have the value 1 in the count variable.
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
2) Java static method
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o static method can access static data member and can change the value of it.
Example of static method
1. //Program of changing the common property of all objects(static field).
2.
3. class Student9{
4. int rollno;
5. String name;
6. static String college = "ITS";
7.
8. static void change(){
9. college = "BBDIT";
10. }
11.
12. Student9(int r, String n){
13. rollno = r;
14. name = n;
15. }
16.
17. void display (){System.out.println(rollno+" "+name+" "+college);}
18.
19. public static void main(String args[]){
20. Student9.change();
21.
22. Student9 s1 = new Student9 (111,"Karan");
23. Student9 s2 = new Student9 (222,"Aryan");
24. Student9 s3 = new Student9 (333,"Sonoo");
25.
26. s1.display();
27. s2.display();
28. s3.display();
29. }
30. }
Test it Now
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Restrictions for static method
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.
1. class A{
2. 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
Q) why java main method is static?
Ans) because object is not required to call static method if it were non-static method, jvm
create object first then call main() method that will lead the problem of extra memory
allocation.
3) Java static block
o Is used to initialize the static data member.
o It is executed before main method at the time of classloading.

Q) Can we execute a program without main() method?


Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
1. class A3{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
Test it Now
Output:static block is invoked (if not JDK7)
In JDK7 and above, output will be:
Output:Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
this keyword in java
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers
to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
Suggestion: If you are beginner to java, lookup only three usage of this keyword.

1) this: to refer current class instance variable


The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display();
18. }}
Test it Now
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we
are using this keyword to distinguish local variable and instance variable.
Solution of the above problem by this keyword
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. this.rollno=rollno;
7. this.name=name;
8. this.fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis2{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
19. }}
Test it Now
Output:
111 ankit 5000
112 sumit 6000
If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword like in the following program:
2) this: to invoke current class method
You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see the
example
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.
Calling default constructor from parameterized constructor:
1. class A{
2. A(){System.out.println("hello a");}
3. A(int x){
4. this();
5. System.out.println(x);
6. }
7. }
8. class TestThis5{
9. public static void main(String args[]){
10. A a=new A(10);
11. }}
Test it Now
Output:
hello a
10
Application of this that can be passed as an argument:
In event handling (or) in a situation where we have to provide reference of a class to another one.
It is used to reuse one object in many methods.
6) this keyword can be used to return current class instance
We can return this keyword as an statement from the method. In such case, return type of the
method must be the class type (non-primitive). Let's see the example:
Syntax of this that can be returned as a statement
1. return_type method_name(){
2. return this;
3. }
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of parent
class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
Syntax of Java Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called parent or super class and the new
class is called child or subclass.
Java Inheritance Example

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
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
When a class extends multiple classes i.e. known as multiple inheritance. For Example:

Single Inheritance Example


File: TestInheritance.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:
barking...
eating...
Multilevel Inheritance Example
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
Q) Why multiple inheritances are not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If
A and B classes have same method and you call it from child class object, there will be
ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time error
now.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

Public Static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Compile Time Error
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.
class Employee{
int id;
String name;
Address address;//Address is a class
...
}
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
Why use Aggregation?
o For Code Reusability.
Simple Example of Aggregation
In this example, we have created the reference of Operation class in the Circle class.
class Operation{
int square(int n){
return n*n;
}
}

class Circle{
Operation op;//aggregation
double pi=3.14;
double area(int radius){
op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
return pi*rsquare;
}

public static void main(String args[]){


Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}
}
Output:78.5

When use Aggregation?


o Code reuse is also best achieved by aggregation when there is no is-a relationship.
o Inheritance should be used only if the relationship is-a is maintained throughout the
lifetime of the objects involved; otherwise, aggregation is the best choice.
Understanding meaningful example of Aggregation
In this example, Employee has an object of Address, address object contains its own
informations such as city, state, country etc. In such case relationship is Employee HAS-A
address.
Address.java
public class Address {
String city,state,country;

public Address(String city, String state, String country) {


this.city = city;
this.state = state;
this.country = country;
}

}
Method Overloading in Java
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand the
behavior of the method because its name differs.
So, we perform method overloading to figure out the program quickly.

Advantage of method overloading:


Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9
Q) Why Method Overloading is not possible by changing the return type of method only?
In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}
}
Output:
Compile Time Error: method add(int,int) is already defined in class Adder
System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method
should be called?
Can we overload java main() method?
Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only. Let's
see the simple example:
class TestOverloading4{
public static void main(String[] args){System.out.println("main with String[]");}
public static void main(String args){System.out.println("main with String");}
public static void main(){System.out.println("main without args");}
}
Output:
main with String[]
Method Overloading and Type Promotion
One type is promoted to another implicitly if no matching datatype is found. Let's understand the
concept by the figure given below:

As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The
short datatype can be promoted to int,long,float or double. The char datatype can be promoted to
int,long,float or double and so on.
Method Overriding in Java:

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.
Usage of Java Method Overriding
o Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
o Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).
Understanding the problem without method overriding
Let's understand the problem that we may face in the program if we don't use method overriding.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{

public static void main(String args[]){


Bike obj = new Bike();
obj.run();
}
}
Output:Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that is
why we use method overriding.
Example of method overriding
In this example, we have defined the run method in the subclass as defined in the parent class but
it has some specific implementation. The name and parameter of the method is same and there is
IS-A relationship between the classes, so there is method overriding.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();
obj.run();
}
Output:Bike is running safely
Real example of Java Method Overriding
Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of
interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%,
7% and 9% rate of interest.
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}

class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Can we override static method?
No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will
learn it later.
Why we cannot override static method?
because static method is bound with class whereas instance method is bound with object. Static
belongs to class area and instance belongs to heap area.
Can we override java main method?
No, because main is a static method.
Difference between method Overloading and Method Overriding in java
Covariant Return Type
The covariant return type specifies that the return type may vary in the same direction as the
subclass.
Before Java5, it was not possible to override any method by changing the return type. But now,
since Java5, it is possible to override method by changing the return type if subclass overrides
any method whose return type is Non-Primitive but it changes its return type to subclass type.
Let's take a simple example:
Simple example of Covariant Return Type
class A{
A get(){return this;}
}
class B1 extends A{
B1 get(){return this;}
void message(){System.out.println("welcome to covariant return type");}

public static void main(String args[]){


new B1().get().message();
}
}
Output:welcome to covariant return type

As you can see in the above example, the return type of the get() method of A class is A but the
return type of the get() method of B class is B. Both methods have different return type but it is
method overriding. This is known as covariant return type.

super keyword in java


The super keyword in java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
Usage of java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
1) super is used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
Test it Now
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property,
we need to use super keyword.
super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
Test it Now
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given to
local.
To call the parent class method, we need to use super keyword.
3) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
Dog d=new Dog();
}}
Test it Now
Output:
animal is created
dog is created

As we know well that default constructor is provided by compiler automatically if there is no


constructor. But, it also adds super() as the first statement.
super example: real use
Let's see the real use of super keyword. Here, Emp class inherits Person class so all the
properties of Person will be inherited to Emp by default. To initialize all the property, we are
using parent class constructor from child class. In such way, we are reusing the parent class
constructor.
class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
}
}
class Emp extends Person{
float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}}
Output:
1 ankit 45000
Instance initializer block

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.
What is the use of instance initializer block while we can directly assign a value in instance data
member? For example:
class Bike{
int speed=100;
}
Why use instance initializer block?
Suppose I have to perform some operations while assigning value to instance data member
e.g. a for loop to fill a complex array or error handling etc.
Example of instance initializer block
Let's see the simple example of instance initializer block the performs initialization.
class Bike7{
int speed;

Bike7(){System.out.println("speed is "+speed);}

{speed=100;}

public static void main(String args[]){


Bike7 b1=new Bike7();
Bike7 b2=new Bike7();
}
}
Output:speed is 100
speed is 100
\

There are three places in java where you can perform operations:
1. method
2. constructor
3. block
What is invoked first, instance initializer block or constructor?
class Bike8{
int speed;

Bike8(){System.out.println("constructor is invoked");}

{System.out.println("instance initializer block invoked");}

public static void main(String args[]){


Bike8 b1=new Bike8();
Bike8 b2=new Bike8();
}
}
Output:instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked

In the above example, it seems that instance initializer block is firstly invoked but NO.
Instance intializer block is invoked at the time of object creation. The java compiler copies
the instance initializer block in the constructor after the first statement super(). So firstly,
constructor is invoked. Let's understand it by the figure given below:
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.
Program of instance initializer block that is invoked after super()
class A{
A(){
System.out.println("parent class constructor invoked");
}
}
class B2 extends A{
B2(){
super();
System.out.println("child class constructor invoked");
}

{System.out.println("instance initializer block is invoked");}

public static void main(String args[]){


B2 b=new B2();
}
}
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
Final Keyword In Java
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).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can't
be changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output:Compile Time Error
2) Java final method
If you make any method as final, you cannot override it.
Example of final method
class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}

Output:Compile Time Error


3) Java final class
If you make any class as final, you cannot extend it.
Example of final class
final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
Q) Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For Example:
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Output:running...
Q) What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an employee.
It can be initialized only in constructor.
Example of blank final variable
class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
... }
static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank
final variable. It can be initialized only in static block.
Example of static blank final variable
class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}
Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it.
class Bike11{
int cube(final int n){
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}
Output:Compile Time Error

Q) Can we declare a constructor final?


No, because constructor is never inherited.
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.
Runtime Polymorphism in Java
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.
Let's first understand the upcasting before Runtime Polymorphism.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For

example:
class A{}
class B extends A{}
A a=new B();//upcasting
Example of Java Runtime Polymorphism
In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike
class and overrides its run() method. We are calling the run method by the reference variable of
Parent class. Since it refers to the subclass object and subclass method overrides the Parent class
method, subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.
class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splender();//upcasting
b.run();
}
}
Output:running safely with 60km.
Java Runtime Polymorphism Example: Bank
Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of
interest may differ according to banks. For example, SBI, ICICI and AXIS banks are providing
8.4%, 7.3% and 9.7% rate of interest.
class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7
Java Runtime Polymorphism with Data Member
Method is overridden not the datamembers, so runtime polymorphism can't be achieved by
data members.
In the example given below, both the classes have a datamember speedlimit, we are accessing
the datamember by the reference variable of Parent class which refers to the subclass object.
Since we are accessing the datamember which is not overridden, hence it will access the
datamember of Parent class always.
class Bike{
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;

public static void main(String args[]){


Bike obj=new Honda3();
System.out.println(obj.speedlimit);//90
}
Output:
90
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
Before learning java abstract class, let's understand the abstraction in java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the
internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract class in Java
A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
Example abstract class
1. abstract class A{}
abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.
Example abstract method
1. abstract void printStatus();//no body and abstract
Example of abstract class that has abstract method
In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
running safely..
Understanding the real scenario of abstract class
In this example, Shape is the abstract class, its implementation is provided by the Rectangle and
Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the end
user) and object of the implementation class is provided by the factory method.
A factory method is the method that returns the instance of the class. We will learn about the
factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.
File: TestAbstraction1.java
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape() method

s.draw();
}
}
drawing circle
UNIT-2
Java Package

A java package is a group of similar types of classes, interfaces and sub-packages. Package in
java can be categorized in two form, built-in package and user-defined package. There are many
built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Here, we will have
the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.


3) Java package removes naming collision.

Simple example of java package

The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
1. javac -d directory javafilename
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Example of package that import the packagename.*
//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.

Example of package by import fully qualified name

//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello

Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported excluding
the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.

Subpackage in java

Package inside the package is called the subpackage. It should be created to categorize the
package further.

Let's take an example, Sun Microsystem has definded a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group
e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes
are for networking etc and so on. So, Sun has subcategorized the java package into subpackages
such as lang, net, io etc. and put the Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on.

The standard of defining package is domain.company.package e.g. com.javatpoint.bean or


org.sssit.dao.

Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple

Output:Hello subpackage

How to send the class file to another directory or drive?


There is a scenario, I want to put the class file of A.java source file in classes folder of c:
drive. For example:

//save as Simple.java

package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

To Compile:
e:\sources> javac -d c:\classes Simple.java

To Run:
To run this program from e:\source directory, you need to set classpath of the directory where
the class file resides.

e:\sources> set classpath=c:\classes;.;

e:\sources> java mypack.Simple

Another way to run this program by -classpath switch of java:


The -classpath switch can be used with javac and java tool.

To run this program from e:\source directory, you can use -classpath switch of java that tells
where to look for class file. For example:

e:\sources> java -classpath c:\classes mypack.Simple

Output:Welcome to package

Ways to load the class files or jar files


There are two ways to load the class files temporary and permanent.

 Temporary
o By setting the classpath in the command prompt
o By -classpath switch
 Permanent
o By setting the classpath in the environment variables
o By creating the jar file, that contains all the class files, and copying the jar file in
the jre/lib/ext folder.

Rule: There can be only one public class in a java source file and it must be saved by the
public class name.
1. //save as C.java otherwise Compilte Time Error
2.
3. class A{}
4. class B{}
5. public class C{}
How to put two public classes in a package?
If you want to put two public classes in a package, have two java source files containing one
public class, but keep the package name same. For example:

1. //save as A.java
2.
3. package javatpoint;
4. public class A{}
1. //save as B.java
2.
3. package javatpoint;
4. public class B{}

What is static import feature of Java5?

Static Import:

The static import feature of Java 5 facilitate the java programmer to access any static member of
a class directly. There is no need to qualify it by the class name.

Advantage of static import:

 Less coding is required if you have access any static member of a class oftenly.
Disadvantage of static import:

 If you overuse the static import feature, it makes the program unreadable and
unmaintainable.

Simple Example of static import

import static java.lang.System.*;


class StaticImportExample{
public static void main(String args[]){

out.println("Hello");//Now no need of System.out


out.println("Java");

}
}
Access Modifiers in java

There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.
There are 4 types of java access modifiers:
1. private
2. default
3. protected
4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.
1) private access modifier
The private access modifier is accessible only within class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is compile time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:

class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.

2) default access modifier

If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) Protected access modifier

The protected access modifier is accessible within package and outside the package but through
inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello

4) public access modifier

The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

Example of public access modifier

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

Understanding all java access modifiers

Let's understand the access modifiers by a simple table.

Access within class within package outside package by subclass only outside package
Modifier
Private Y N N N

Default Y Y N N
Protected Y Y Y N

Public Y Y Y Y

Interface in Java

An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and
multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
 It is used to achieve fully abstraction.
 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.

The java compiler adds public and abstract keywords before the interface method and public,
static and final keywords before data members.

In other words, Interface fields are public, static and final bydefault, and methods are public and
abstract
Understanding relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.

Simple example of Java interface

In this example, Printable interface have only one method, its implementation is provided in
the A class.

interface printable{
void print();
}

class A6 implements printable{


public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}
Output:Hello

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.

interface Printable{
void print();
}

interface Showable{
void show();
}

class A7 implements Printable,Showable{

public void print(){System.out.println("Hello");}


public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:Hello
Welcome

Q) Multiple inheritance is not supported through class in java but it is possible by interface,
why?

As we have explained in the inheritance chapter, multiple inheritance is not supported in case
of class. But it is supported in case of interface because there is no ambiguity as
implementation is provided by the implementation class. For example:

interface Printable{
void print();
}

interface Showable{
void print();
}

class testinterface1 implements Printable,Showable{

public void print(){System.out.println("Hello");}

public static void main(String args[]){


testinterface1 obj = new testinterface1();
obj.print();
}
}
Hello

As you can see in the above example, Printable and Showable interface have same methods but
its implementation is provided by class A, so there is no ambiguity.

Interface inheritance

A class implements interface but one interface extends another interface .

interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class Testinterface2 implements Showable{

public void print(){System.out.println("Hello");}


public void show(){System.out.println("Welcome");}

public static void main(String args[]){


Testinterface2 obj = new Testinterface2();
obj.print();
obj.show();
}
}
Hello
Welcome

Q) What is marker or tagged interface?

An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information to the
JVM so that JVM may perform some useful operation.

1. //How Serializable interface is written?


2. public interface Serializable{
3. }

Nested Interface in Java

Note: An interface can have another interface i.e. known as nested interface. We will learn it in
detail in the nested classes chapter. For example:

interface printable{
void print();
interface MessagePrintable{
void msg();
}
}
More about Nested Interface

Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface


 Abstract class can have abstract and non-  Interface can have only
abstractmethods. abstract methods.
 Abstract class doesn't support multiple  Interface supports
inheritance. multiple inheritance.
 Abstract class can have final, non-final, static  Interface has only static
and non-static variables. and final variables.
 Abstract class can have static methods, main  Interface can't have static
method and constructor. methods, main method or
constructor.
 Abstract class can provide the implementation  Interface can't provide the
of interface. implementation of
abstract class.
 The abstract keyword is used to declare abstract  The interface keyword is
class. used to declare interface.
 Example:  Example:
public class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).

Example of abstract class and interface in Java

Let's see a simple example where we are using interface and abstract class both.

//Creating interface that has 4 methods


interface A{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}

//Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A{
public void c(){System.out.println("I am C");}
}

//Creating subclass of abstract class, now we need to provide the implementation of rest of the metho
ds
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}

//Creating a test class that calls the methods of A interface


class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Test it Now
Output:

I am a
I am b
I am c
I am d
Java I/O Tutorial
Java I/O (Input and Output) is used to process the input and produce the output.
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.
We can perform file handling in java by Java I/O API.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because
it is like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
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");
Let's see the code to get input from console.
1. int i=System.in.read();//returns ASCII code of 1st character
2. System.out.println((char)i);//will print the character
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:
OutputStream
Java application uses an output stream to write data to a destination, it may be a file, an array,
peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source, it may be a file, an array,
peripheral device or socket.
Let's understand working of Java OutputStream and InputStream by the figure given below.
OutputStream class
OutputStream class is an abstract class. It is the super class of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
Useful methods of OutputStream
Method Description

 public void write(int)throws  is used to write a byte to the current


IOException output stream.
 public void write(byte[])throws  is used to write an array of byte to the
IOException current output stream.
 public void flush()throws  flushes the current output stream.
IOException
 public void close()throws  is used to close the current output
IOException stream.
OutputStream Hierarchy
UNIT-3
Exception Handling in Java
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
In this page, we will learn about java exception, its type and the difference between checked and
unchecked exceptions.
What is exception
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.
What is exception handling
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL,
Remote etc.
Advantage of Exception Handling
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:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest
of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception
handling, rest of the statement will be executed. That is why we use exception handling in java.
Hierarchy of Java Exception classes
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
Difference between checked and unchecked exceptions
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Common scenarios where exceptions may occur
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
1. int a=50/0;//ArithmeticException
2) Scenario where NullPointerException occurs
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
3) Scenario where NumberFormatException occurs
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

4) Scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException

Java Exception Handling Keywords


There are 5 keywords used in java exception handling.
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.
Java try block must be followed by either catch or finally block.
Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw exception
}finally{}
Java catch block
Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.
Problem without exception handling
Let's try to understand the problem if we don't use try-catch block.
public class Testtrycatch1{
public static void main(String args[]){
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
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.
Solution by exception handling
Let's see the solution of above problem by java try-catch block.
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
Internal working of java try-catch block
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:
o Prints out exception description.
o Prints the stack trace (Hierarchy of methods where the exception occurred).
o Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
Java catch multiple exceptions
Java Multi catch block
If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
Let's see a simple example of java multi-catch block.
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}

System.out.println("rest of the code...");


}
}
Output:task1 completed
rest of the code...
class TestMultipleCatchBlock1{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
Output:
Compile-time error
Java Nested try block
The try block within a try block is known as nested try block in java.
Why use nested try block
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:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
Java nested try example
Let's see a simple example of java nested try block.
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}

try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}

System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}

System.out.println("normal flow..");
}
}
Java finally block
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.

Why use java finally


o Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.
Usage of Java finally
Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...
Case 3
Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
Java throw exception
Java throw keyword
The Java throw keyword is used to explicitly throw an exception.
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.
The syntax of java throw keyword is given below.
1. throw exception;
Let's see the example of throw IOException.
1. throw new IOException("sorry device error);
java throw keyword example
In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
1. }
Output:
Exception in thread main java.lang.ArithmeticException:not valid
Java Exception propagation
An exception is first thrown from the top of the stack and if it is not caught, it drops down the
call stack to the previous method,If not caught there, the exception again drops down to the
previous method, and so on until they are caught or until they reach the very bottom of the
call stack.This is called exception propagation.
Program of Exception Propagation
class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
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.
Program which describes that checked exceptions are not propagated
class TestExceptionPropagation2{
void m(){
throw new java.io.IOException("device error");//checked exception
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handeled");}
}
public static void main(String args[]){
TestExceptionPropagation2 obj=new TestExceptionPropagation2();
obj.p();
System.out.println("normal flow");
}
}
Output:Compile Time Error
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
Syntax of java throws
return_type method_name() throws exception_class_name{
//method code
}
Which exception should be declared
Ans) checked exception only, because:
o unchecked Exception: under your control so correct your code.
o error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
Java throws example
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
There are two cases:
1. Case1:You caught the exception i.e. handle the exception using try/catch.
2. Case2:You declare the exception i.e. specifying throws with the method.
Case1: You handle the exception
o In case you handle the exception, the code will be executed fine whether exception
occurs during the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}

System.out.println("normal flow...");
}
}
Output:exception handled
normal flow...

Que) Can we rethrow an exception?


Yes, by throwing same exception in catch block.
Java throw example
void m(){
throw new ArithmeticException("sorry");
}
Java throws example
void m()throws ArithmeticException{
//method code
}

Java throw and throws example


void m()throws ArithmeticException{
throw new ArithmeticException("sorry");
}
Difference between final, finally and finalize
There are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:
No. final finally finalize

1) Final is used to apply restrictions on Finally is used to place Finalize is used to


class, method and variable. Final important code, it will perform clean up
class can't be inherited, final method be executed whether processing just before
can't be overridden and final exception is handled or object is garbage
variable value can't be changed. not. collected.
2) Final is a keyword. Finally is a block. Finalize is a method.
Java final example
class FinalExample{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}}
Java finally example
class FinallyExample{
public static void main(String[] args){
try{
int x=300;
}catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
}}
Java finalize example
class FinalizeExample{
public void finalize(){System.out.println("finalize called");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}}
ExceptionHandling with MethodOverriding in Java
There are many rules if we talk about methodoverriding with exception handling. The Rules
are as follows:
o If the superclass method does not declare an exception
o If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but it can declare unchecked
exception.
o If the superclass method declares an exception
o If the superclass method declares an exception, subclass overridden method
can declare same, subclass exception or no exception but cannot declare parent
exception.
If the superclass method does not declare an exception
import java.io.*;
class Parent{
void msg(){System.out.println("parent");}
}

class TestExceptionChild extends Parent{


void msg()throws IOException{
System.out.println("TestExceptionChild");
}
public static void main(String args[]){
Parent p=new TestExceptionChild();
p.msg();
}
}
Output:Compile Time Error
1. import java.io.*;
class Parent{
void msg(){System.out.println("parent");}
}

class TestExceptionChild1 extends Parent{


void msg()throws ArithmeticException{
System.out.println("child");
}
public static void main(String args[]){
Parent p=new TestExceptionChild1();
p.msg();
}
}
Output:child
Multithreading in Java
Multithreading in java is a process of executing multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved by two ways:
o Process-based Multitasking(Multiprocessing)
o Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
o Each process have its own address in memory i.e. each process allocates separate
memory area.
o Process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
2) Thread-based Multitasking (Multithreading)
o Threads share the same address space.
o Thread is lightweight.
o Cost of communication between the thread is low.

Note: At least one process is required for each thread.

What is Thread in java


A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It
shares a common memory area.
As shown in the above figure, thread is executed inside the process. There is context-switching
between the threads. There can be multiple processes inside the OS and one process can have
multiple threads.

Note: At a time one thread is executed only.

Life cycle of a Thread (Thread States)


A thread can be in one of the five states. According to sun, there is only 4 states in thread 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
A thread is in terminated or dead state when its run() method exits.
How to create thread
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to
be executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
1) Java Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output:thread is running...
2) Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:thread is running...

If you are not extending the Thread class,your class object would not be treated as a thread
object.So you need to explicitely create Thread class object.We are passing the object of your
class that implements Runnable so that your class run() method may execute.

Thread Scheduler in Java


Thread scheduler in java is the part of the JVM that decides which thread should run.
There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.
Only one thread at a time can run in a single process.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.
Difference between preemptive scheduling and time slicing
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead
states or a higher priority task comes into existence. Under time slicing, a task executes for a
predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines
which task should execute next, based on priority and other factors.
Sleep method in java
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Syntax of sleep() method in java
The Thread class provides two methods for sleeping a thread:
o public static void sleep(long miliseconds)throws InterruptedException
o public static void sleep(long miliseconds, int nanos)throws InterruptedException
Example of sleep method in java
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();

t1.start();
t2.start();
}
}
Output:
1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time,the thread shedular picks up another thread and so on.
Can we start a thread twice
No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once but for second time,
it will throw exception.
Let's understand it by the example given below:
public class TestThreadTwice1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestThreadTwice1 t1=new TestThreadTwice1();
t1.start();
t1.start();
}
}
running
Exception in thread "main" java.lang.IllegalThreadStateException
What if we call run() method directly instead start() method?
o Each thread starts in a separate call stack.
o Invoking the run() method from main thread, the run() method goes onto the current
call stack rather than at the beginning of a new call stack.
class TestCallRun1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestCallRun1 t1=new TestCallRun1();
t1.run();//fine, but does not start a separate call stack
}
}
Output:running...
The join() method
The join() method waits for a thread to die. In other words, it causes the currently running
threads to stop executing until the thread it joins with completes its task.
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
Example of join() method
class TestJoinMethod1 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}

t2.start();
t3.start();
}
}
Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
Naming Thread
The Thread class provides methods to change and get the name of a thread. By default, each
thread has a name i.e. thread-0, thread-1 and so on. By we can change the name of the thread by
using setName() method. The syntax of setName() and getName() methods are given below:
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of a thread.
Example of naming a thread
class TestMultiNaming1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestMultiNaming1 t1=new TestMultiNaming1();
TestMultiNaming1 t2=new TestMultiNaming1();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
t1.start();
t2.start();

t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changeling name of t1:Sonoo Jaiswal
running...

Priority of a Thread (Thread Priority):


Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.
3 constants defiend in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and
the value of MAX_PRIORITY is 10.
Example of priority of a Thread:
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();

}
}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Daemon Thread in Java
Daemon thread in java is a service provider thread that provides services to the user thread. Its
life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this
thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
You can see all the detail by typing the jconsole in the command prompt. The jconsole tool
provides information about the loaded classes, memory usage, running threads etc.
Points to remember for Daemon Thread in Java
o It provides services to user threads for background supporting tasks. It has no role in life
than to serve user threads.
o Its life depends on user threads.
o It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread?


The sole purpose of the daemon thread is that it provides services to user thread for background
supporting task. If there is no user thread, why should JVM keep running this thread. That is why
JVM terminates the daemon thread if there is no user thread.

Methods for Java Daemon thread by Thread class


The java.lang.Thread class provides two methods for java daemon thread.
No. Method Description

1) public void setDaemon(boolean is used to mark the current thread as daemon thread
status) or user thread.
2) public boolean isDaemon() is used to check that current is daemon.

Simple example of Daemon thread in java


File: MyThread.java
public class TestDaemonThread1 extends Thread{
public void run(){
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();

t1.setDaemon(true);//now t1 is daemon thread

t1.start();//starting threads
t2.start();
t3.start();
}
}
Output
daemon thread work
user thread work
user thread work
Java Garbage Collection
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.
How can an object be unreferenced?
There are many ways:
o By nulling the reference
o By assigning a reference to another
o By annonymous object etc.
1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;
2) By assigning a reference to another:
1. Employee e1=new Employee();
2. Employee e2=new Employee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection
3) By annonymous object:
1. new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method
can be used to perform cleanup processing. This method is defined in Object class as:
1. protected void finalize(){}
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc()
is found in System and Runtime classes.
1. public static void gc(){}

Simple Example of garbage collection in java


public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
object is garbage collected
object is garbage collected
Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Why use Synchronization
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only thread synchronization.
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
Synchronized block in java
Synchronized block can be used to perform synchronization on any specific resource of the
method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you
can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
Points to remember for Synchronized block
o Synchronized block is used to lock an object for any shared resource.
o Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
synchronized (object reference expression) {
//code block
}

UNIT-4
Collections in Java
Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
What is Collection in java
Collection represents a single unit of objects i.e. a group.
What is framework in java
o provides readymade architecture.
o represents set of classes and interface.
o is optional.
What is Collection framework
Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:
1. Interfaces and its implementations i.e. classes
2. Algorithm
Hierarchy of Collection Framework
Let us see the hierarchy of collection framework.The java.util package contains all the classes
and interfaces for Collection framework.

Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
1. public boolean hasNext() it returns true if iterator has more elements.
2. public object next() it returns the element and moves the cursor pointer to the next
element.
3. public void remove() it removes the last elements returned by the iterator. It is rarely
used.
Java ArrayList class
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class
and implements List interface.
The important points about Java ArrayList class are:
o Java ArrayList class can contain duplicate elements.
o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurred if any element is removed from the array list.
Hierarchy of ArrayList class
As shown in above diagram, Java ArrayList class extends AbstractList class which implements
List interface. The List interface extends Collection and Iterable interfaces in hierarchical order.
ArrayList class declaration
Let's see the declaration for java.util.ArrayList class.
1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAcce
ss, Cloneable, Serializable
Java Non-generic Vs Generic Collection
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in collection. Now it is
type safe so typecasting is not required at run time.
Let's see the old non-generic example of creating java collection.
1. ArrayList al=new ArrayList();//creating old non-generic arraylist
Let's see the new generic example of creating java collection.
1. ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist
In generic collection, we specify the type in angular braces. Now ArrayList is forced to have
only specified type of objects in it. If you try to add another type of object, it gives compile time
error.
For more information of java generics, click here Java Generics Tutorial.
Java LinkedList class
Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list data
structure. It inherits the AbstractList class and implements List and Deque interfaces.
The important points about Java LinkedList are:
o Java LinkedList class can contain duplicate elements.
o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
o Java LinkedList class can be used as list, stack or queue.
Hierarchy of LinkedList class
As shown in above diagram, Java LinkedList class extends AbstractSequentialList class and
implements List and Deque interfaces.
Doubly Linked List
In case of doubly linked list, we can add or remove elements from both side.

LinkedList class declaration


Let's see the declaration for java.util.LinkedList class.
1. public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, D
eque<E>, Cloneable, Serializable
Difference between ArrayList and LinkedList
ArrayList and LinkedList both implements List interface and maintains insertion order. Both are
non synchronized classes.
But there are many differences between ArrayList and LinkedList classes that are given below.
List Interface is the subinterface of Collection.It contains methods to insert and delete elements
in index basis.It is a factory of ListIterator interface.
Java HashSet class
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the
AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
o HashSet stores the elements by using a mechanism called hashing.
o HashSet contains unique elements only.
Difference between List and Set
List can contain duplicate elements whereas Set contains unique elements only.
Hierarchy of HashSet class
The HashSet class extends AbstractSet class which implements Set interface. The Set interface
inherits Collection and Iterable interfaces in hierarchical order.
HashSet class declaration
Let's see the declaration for java.util.HashSet class.
1. public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Seria
lizable
Java HashSet Example
import java.util.*;
class TestCollection9{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ajay
Vijay
Ravi
Java LinkedHashSet class is a Hash table and Linked list implementation of the set interface. It
inherits HashSet class and implements Set interface.
The important points about Java LinkedHashSet class are:
o Contains unique elements only like HashSet.
o Provides all optional set operations, and permits null elements.
o Maintains insertion order.
Hierarchy of LinkedHashSet class
The LinkedHashSet class extends HashSet class which implements Set interface. The Set
interface inherits Collection and Iterable interfaces in hierarchical order.
Java TreeSet class

Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet
class and implements NavigableSet interface. The objects of TreeSet class are stored in
ascending order.
The important points about Java TreeSet class are:
o Contains unique elements only like HashSet.
o Access and retrieval times are quiet fast.
o Maintains ascending order.
Hierarchy of TreeSet class
As shown in above diagram, Java TreeSet class implements NavigableSet interface. The
NavigableSet interface extends SortedSet, Set, Collection and Iterable interfaces in hierarchical
order.
Java Queue Interface
Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first
element is removed first and last element is removed at last.
Queue Interface declaration
1. public interface Queue<E> extends Collection<E>
Methods of Java Queue Interface
PriorityQueue class
The PriorityQueue class provides the facility of using queue. But it does not orders the elements
in FIFO manner. It inherits AbstractQueue class.
PriorityQueue class declaration
Let's see the declaration for java.util.PriorityQueue class.
1. public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
Java Deque Interface
Java Deque Interface is a linear collection that supports element insertion and removal at both
ends. Deque is an acronym for "double ended queue".
Deque Interface declaration
1. public interface Deque<E> extends Queue<E>
Methods of Java Deque Interface

ArrayDeque class
The ArrayDeque class provides the facility of using deque and resizable-array. It inherits
AbstractCollection class and implements the Deque interface.
The important points about ArrayDeque class are:
o Unlike Queue, we can add or remove elements from both sides.
o Null elements are not allowed in the ArrayDeque.
o ArrayDeque is not thread safe, in the absence of external synchronization.
o ArrayDeque has no capacity restrictions.
o ArrayDeque is faster than LinkedList and Stack.
ArrayDeque Hierarchy
The hierarchy of ArrayDeque class is given in the figure displayed at the right side of the page.
ArrayDeque class declaration
Let's see the declaration for java.util.ArrayDeque class.
1. public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, C
loneable, Serializable
2. Java Map Interface
3. A map contains values on the basis of key i.e. key and value pair. Each key and value
pair is known as an entry. Map contains only unique keys.
4. Map is useful if you have to search, update or delete elements on the basis of key.
Java HashMap class

Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap
class and implements Map interface.
The important points about Java HashMap class are:
o A HashMap contains values based on the key.
o It contains only unique elements.
o It may have one null key and multiple null values.
o It maintains no order.
Hierarchy of HashMap class
As shown in the above figure, HashMap class extends AbstractMap class and implements Map
interface.
HashMap class declaration
Let's see the declaration for java.util.HashMap class.
1. public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Clo
neable, Serializable
HashMap class Parameters
Let's see the Parameters for java.util.HashMap class.
o K: It is the type of keys maintained by this map.
o V: It is the type of mapped values.
Java LinkedHashMap class
Java LinkedHashMap class is Hash table and Linked list implementation of the Map interface,
with predictable iteration order. It inherits HashMap class and implements the Map interface.
The important points about Java HashMap class are:
o A LinkedHashMap contains values based on the key.
o It contains only unique elements.
o It may have one null key and multiple null values.
o It is same as HashMap instead maintains insertion order.
LinkedHashMap class declaration
Let's see the declaration for java.util.LinkedHashMap class.
1. public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
LinkedHashMap class Parameters
Let's see the Parameters for java.util.LinkedHashMap class.
o K: It is the type of keys maintained by this map.
o V: It is the type of mapped values.
Java TreeMap class

Java TreeMap class implements the Map interface by using a tree. It provides an efficient means
of storing key/value pairs in sorted order.
The important points about Java TreeMap class are:
o A TreeMap contains values based on the key. It implements the NavigableMap interface
and extends AbstractMap class.
o It contains only unique elements.
o It cannot have null key but can have multiple null values.
o It is same as HashMap instead maintains ascending order.
TreeMap class declaration
Let's see the declaration for java.util.TreeMap class.
1. public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<
K,V>, Cloneable, Serializable
Java Hashtable class
Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary
class and implements the Map interface.
The important points about Java Hashtable class are:
o A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is
identified by calling the hashcode() method. A Hashtable contains values based on the
key.
o It contains only unique elements.
o It may have not have any null key or value.
o It is synchronized.
Hashtable class declaration
Let's see the declaration for java.util.Hashtable class.
1. public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Clone
able, Serializable
2. Java EnumSet class
Java EnumSet class is the specialized Set implementation for use with enum types. It inherits
AbstractSet class and implements the Set interface.
EnumSet class hierarchy
The hierarchy of EnumSet class is given in the figure given below.

Java Collections class


Java collection class is used exclusively with static methods that operate on or return collections.
It inherits Object class.
The important points about Java Collections class are:
o Java Collection class supports the polymorphic algorithms that operate on collections.
o Java Collection class throws a NullPointerException if the collections or class objects
provided to them are null.
Collections class declaration
Let's see the declaration for Java.util.Collections class.
1. public class Collections extends Object
Sorting in Collection
We can sort the elements of:
1. String objects
2. Wrapper class objects
3. User-defined class objects
Collections class provides static methods for sorting the elements of collection.If collection
elements are of Set type, we can use TreeSet.But We cannot sort the elements of
List.Collections class provides methods for sorting the elements of List type elements.
Method of Collections class for sorting List elements
public void sort(List list): is used to sort the elements of List.List elements must be of
Comparable type.
ava Comparable interface
Java Comparable interface is used to order the objects of user-defined class.This interface is
found in java.lang package and contains only one method named compareTo(Object). It provide
single sorting sequence only i.e. you can sort the elements on based on single data member only.
For example it may be rollno, name, age or anything else.
compareTo(Object obj) method
public int compareTo(Object obj): is used to compare the current object with the specified
object.
We can sort the elements of:
1. String objects
2. Wrapper class objects
3. User-defined class objects
Collections class
Collections class provides static methods for sorting the elements of collections. If collection
elements are of Set or Map, we can use TreeSet or TreeMap. But We cannot sort the elements of
List. Collections class provides methods for sorting the elements of List type elements.
Method of Collections class for sorting List elements
Java Comparator interface
Java Comparator interface is used to order the objects of user-defined class.
This interface is found in java.util package and contains 2 methods compare(Object obj1,Object
obj2) and equals(Object element).
It provides multiple sorting sequence i.e. you can sort the elements on the basis of any data
member, for example rollno, name, age or anything else.
compare() method
public int compare(Object obj1,Object obj2): compares the first object with second object.
Collections class
Collections class provides static methods for sorting the elements of collection. If collection
elements are of Set or Map, we can use TreeSet or TreeMap. But we cannot sort the elements of
List. Collections class provides methods for sorting the elements of List type elements also.
Method of Collections class for sorting List elements
public void sort(List list, Comparator c): is used to sort the elements of List by the given
Comparator.
Properties class in Java
The properties object contains key and value pair both as a string. The java.util.Properties class
is the subclass of Hashtable.
It can be used to get property value based on the property key. The Properties class provides
methods to get data from properties file and store data into properties file. Moreover, it can be
used to get properties of system.
Advantage of properties file
Recompilation is not required, if information is changed from properties file: If any
information is changed from the properties file, you don't need to recompile the java class. It is
used to store information which is to be changed frequently.
Methods of Properties class
The commonly used methods of Properties class are given below.
Java JDBC Tutorial
Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc
drivers to connect with the database.

Why use JDBC


Before JDBC, ODBC API was the database API to connect and execute query with the database.
But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and
unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers
(written in Java language).
What is API
API (Application programming interface) is a document that contains description of all the
features of a product or software. It represents classes and interfaces that software programs can
follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database.There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function
calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.

Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That
is why it is known as thin driver. It is fully written in Java language.

Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
o Drivers depends on the Database.
5 Steps to connect to the database in java
There are 5 steps to connect any java application with the database in java using JDBC. They
are as follows:
o Register the driver class
o Creating connection
o Creating statement
o Executing queries
o Closing connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used
to dynamically load the driver class.
Syntax of forName() method
1. public static void forName(String className)throws ClassNotFoundException
Example to register the OracleDriver class
1. Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the
database.
Syntax of getConnection() method
1. 1) public static Connection getConnection(String url)throws SQLException
2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException
Example to establish connection with the Oracle database
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.
Syntax of createStatement() method
1. public Statement createStatement()throws SQLException
Example to create the statement object
1. Statement stmt=con.createStatement();
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.
Syntax of executeQuery() method
1. public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
1. ResultSet rs=stmt.executeQuery("select * from emp");
2.
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.
Syntax of close() method
1. public void close()throws SQLException
Example to close connection
1. con.close();
Example to connect to the Oracle database in java
For connecting java application with the oracle database, you need to follow 5 steps to
perform database connectivity. In this example we are using Oracle10g as the database. So we
need to know following information for the oracle database:
1. Driver class: The driver class for the oracle database
is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database,
thin is the driver, localhost is the server name on which oracle is running, we may also
use IP address, 1521 is the port number and XE is the Oracle service name. You may
get all these information from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: Password is given by the user at the time of installing the oracle database.

Let's first create a table in oracle database.


1. create table emp(id number(10),name varchar2(40),age number(3));
Example to Connect Java Application with Oracle database
In this example, system is the username and oracle is the password of the Oracle database.
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//step3 create the statement object


Statement stmt=con.createStatement();

//step4 execute query


ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

//step5 close the connection object


con.close();

}catch(Exception e){ System.out.println(e);}

}
}
download this example
The above example will fetch all the records of emp table.

To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
download the jar file ojdbc14.jar
Two ways to load the jar file:
1. paste the ojdbc14.jar file in jre/lib/ext folder
2. set classpath
1) paste the ojdbc14.jar file in JRE/lib/ext folder:
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.
2) set classpath:
There are two ways to set the classpath:
o temporary
o permanent
How to set the temporary classpath:
Firstly, search the ojdbc14.jar file then open command prompt and write:
1. C:>set classpath=c:\folder\ojdbc14.jar;.;
How to set the permanent classpath:
Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to ojdbc14.jar by appending ojdbc14.jar;.; as
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;
To see the slides of seting parmanent path click here
Example to connect to the mysql database in java
For connecting java application with the mysql database, you need to follow 5 steps to perform
database connectivity.
In this example we are using MySql as the database. So we need to know following informations
for the mysql database:
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address, 3306
is the port number and sonoo is the database name. We may use any database, in such
case, you need to replace the sonoo with your database name.
3. Username: The default username for the mysql database is root.
4. Password: Password is given by the user at the time of installing the mysql database. In
this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create
database first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));

UNIT-5
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
Who is responsible to manage the life cycle of an applet?
Java Plug-in software.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}

}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Example of displaying image in applet:
import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"sonoo.jpg");
}

public void paint(Graphics g) {


g.drawImage(picture, 30,30, this);
}

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.
No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components


are platform-independent.
2) AWT components are heavyweight. Swing components are lightweight.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and
feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.
5) AWT doesn't follows MVC(Model View Swing follows MVC.
Controller) where model represents data, view
represents presentation and controller acts as an
interface between model and view.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.
Commonly used Methods of Component class
The methods of Component class are widely used in java swing that are given below.
Method Description

public void add(Component c) add a component on another component.


public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager sets the layout manager for the component.
m)
public void setVisible(boolean b) sets the visibility of the component. It is by default
false.

Java Swing Examples


There are two ways to create a frame:
o By creating the object of Frame class (association)
o By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.
Simple Java Swing Example
Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.
File: FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
Important Questions Unit-Wise

UNIT-1

1. What Kind things can become objects in OOP?


2. List few areas of application of OOP technology?
3. Explain different types of class hierarchies?
4. What makes java a robust language?
5. Explain about the class hierarchies?
6. Explain about the method overriding in Java?
7. Write a java program to implement the method overriding?
8. Explain the way of viewing the world agents to oops?
9. What are the advantages of an object – oriented programming paradigm?
10. Explain the fundamental characteristics of OOPS?
11. Explain briefly the main concepts of object-oriented programming?
12. What is inheritance? Explain the member access mechanism in inheritance with
an example.
13. Explain about final classes, final methods and final variables?

UNIT-2

1. Explain about packages?


2. Define a package and Explain about accessing package?
3. Explain about multiple packages ?
4. Explain about interfaces in java?
5. Explain about nested interface ?
6. Explain about stream I/O?
7. Explain about file input reader and writer?
8. Explain about buffer input reader and writer?
9. Explain about file reader and writer?
10. Explain about console class?
11. Difference between Serialization, Enumerations, auto boxing, generics?
UNIT-3
1. Explain about exception handling in java?
2. Explain about fundamental of exception handling?
3. Explain about Exception types?
4. Difference between Termination or resumptive models?
5. Briefly explain about try-catch and finally block with suitable examples?
6. Explain about built in exceptions?
7. Create an own exception sub classes?
8. Explain about Multi threading?
9. Difference between process based multi tasking and thread based multi tasking?
10. Explain about thread priorities?
11. Explain about inter thread communication?

UNIT-4
1. What is a framework and Explain about collection framework?
2. What is meant by collection interfaces?
3. Define a collection class and differentiate ArrayList and Linked List?
4. Differentiate between Hash Set, Tree Set, Priority Queue, Array Deque?
5. Define an iteration ?Explain how accessing an collection using iterator?
6. Explain about map interfaces and classes?
7. Explain about collection algorithm?
8. Explain about string tokenizer with an example program?
9. Differentiate between hash and vector with an example?
10. Explain in detail about Date, Calendar, Random, Formatter, Scanner?

You might also like