Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: A Complete Java Study Material
Description: A Complete notes for Java programming for beginners Contents included: An overview of Java – Data Types – Variables and Arrays – Operators – Control Statements – Classes – Objects – Methods – Inheritance - Packages – Abstract classes – Interfaces and Inner classes – Exception handling - Introduction to Threads – Multithreading – String handling – Streams and I/O – Applets. Easily understandable for beginners.

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


JAVA PROGRAMMING
CONTENTS:
An overview of Java – Data Types – Variables and Arrays – Operators – Control Statements –
Classes – Objects – Methods – Inheritance - Packages – Abstract classes – Interfaces and Inner
classes – Exception handling - Introduction to Threads – Multithreading – String handling –
Streams and I/O – Applets
...
0 [J2SE])
...

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991
...

2) Originally designed for small, embedded systems in electronic appliances like set-top boxes
...
gt
...

Why Oak name for java language?
5) Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries like
U
...
A
...

6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies
...

The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc
...

According to James Gosling "Java was one of the top choices along with Silk"
...

8) Java is an island of Indonesia where first coffee was produced (called java coffee)
...

10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995
...

12) JDK 1
...


Java Version History
There are many java versions that has been released
...

1
...
JDK 1
...
JDK 1
...
J2SE 1
...
J2SE 1
...
J2SE 1
...
J2SE 5
...
Java SE 6 (11th Dec, 2006)
9
...
Java SE 8 (18th March, 2014)

Where it is used?
According to Sun, 3 billion devices run java
...
Some of them are as follows:
1
...

3
...

5
...

7
...


Desktop Applications such as acrobat reader, media player, antivirus etc
...
co
...
com etc
...

Mobile
Embedded System
Smart Card
Robotics
Games etc
...
An application that we
need to install on every machine such as media player, antivirus etc
...

2) Web Application
An application that runs on the server side and creates dynamic page, is called web application
...
technologies are used for creating web applications in java
...
It has the advantage
of high level security, load balancing and clustering
...


4) Mobile Application
An application that is created for mobile devices
...

Features of Java
There is given many features of java
...
The Java Features
given below are simple and easy to understand
...
Simple
2
...
Platform independent
4
...
Robust
6
...
Portable
8
...
Interpreted
10
...
Multithreaded
12
...

removed many confusing and/or rarely-used features e
...
, explicit pointers, operator
overloading etc
...

Object-oriented
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behaviour
...

Basic concepts of OOPs are:
1
...

3
...

5
...


Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation

Platform Independent
A platform is the hardware or software environment in which a program runs
...
Java provides software-based
platform
...
It has two components:
1
...
API(Application Programming Interface)

java code can be run on multiple platforms e
...
Windows,Linux,Sun Solaris,Mac/OS etc
...
This bytecode is a platform
independent code because it can be run on multiple platforms i
...
Write Once and Run

Anywhere(WORA)
...


Classloader- adds security by separating the package for the classes of the local file
system from those that are imported from network sources
...

Security Manager- determines what resources a class can access such as reading and
writing to the local disk
...
Some security can also be provided by
application developer through SSL,JAAS,cryptography etc
...
Java uses strong memory management
...
There is automatic garbage collection in java
...
All these points makes java robust
...
g
...

Portable
We may carry the java bytecode to any platform
...
g
...
RMI and EJB are used for creating distributed
applications
...

Multi-threaded
A thread is like a separate program, executing concurrently
...
The main advantage of multithreading is that it shares the same memory
...

Requirement for Hello Java Example
For executing any java program, you need to





install the JDK if you don't have installed it, download the JDK and install it
...
http://www
...
com/how-to-set-path-in-java
create the java program
compile and run the java program

Creating hello java example
Let's create the hello java program:
1
...

public static void main(String args[]){
3
...
out
...

}
5
...
java

To compile:

javac Simple
...
out
...










class keyword is used to declare a class in java
...

static is a keyword, if we declare any method as static, it is known as static method
...
The main method is executed by the JVM, so it doesn't require to create
object to invoke the main method
...

void is the return type of the method, it means it doesn't return any value
...

String[] args is used for command line argument
...

System
...
println() is used print statement
...
out
...


To write the simple program, open notepad by start menu -> All Programs -> Accessories ->
notepad and write simple program as displayed below:

As displayed in the above diagram, write the simple program of java in notepad and saved it
as Simple
...
To compile and run this program, you need to open command prompt by start
menu -> All Programs -> Accessories -> command prompt
...


What happens at runtime?
At runtime, following steps are performed:

Classloader: is the subsystem of JVM that is used to load class files
...

Interpreter: read bytecode stream then execute the instructions
...
It is explained in the figure given below:

To compile:

javac Hard
...
It is a specification that provides
runtime environment in which java bytecode can be executed
...
JVM, JRE and JDK are
platform dependent because configuration of each OS differs
...

The JVM performs following main tasks:





Loads code
Verifies code
Executes code
Provides runtime environment

JRE
JRE is an acronym for Java Runtime Environment
...
It is the implementation of JVM
...
It contains set of libraries +

other files that JVM uses at runtime
...


JDK
JDK is an acronym for Java Development Kit
...
It contains JRE +
development tools
...
There are three types of variables: local, instance
and static
...


Variable
Variable is name of reserved area allocated in memory
...
int data=50;//Here data is variable

Types of Variable
There are three types of variables in java




local variable
instance variable
static variable

Local Variable
A variable that is declared inside the method is called local variable
...

It is not declared as static
...
It cannot be local
...


1
...

3
...

5
...

7
...
0f

4 byte

double

0
...
\u0000 is the lowest range of
unicode system
...
We can divide all the Java
operators into the following groups:


Arithmetic Operators



Relational Operators



Bitwise Operators



Logical Operators



Assignment Operators



Misc Operators

The Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra
...


becomes true
...


(A != B) is true
...


(A > B) is not true
...


(A < B) is true
...


(A >= B) is not true
...


(A <= B) is true
...

Bitwise operator works on bits and performs bit-by-bit operation
...


(A & B) will give 12 which is 0000 1100

|

Binary OR
Operator
copies a bit
if it exists in
either
operand
...


~

Binary Ones
Complement
Operator is
unary and
has
the
effect
of
'flipping'
bits
...


<<

Binary Left A << 2 will give 240 which is 1111 0000
Shift
Operator
...

The
left
operands
value
is
moved right
by
the
number of
bits
specified by

the
right
operand
...

The
left
operands
value
is
moved right
by
the
number of
bits
specified by
the
right
operand and
shifted
values are
filled
up
with zeros
...
If both the
operands are non-zero, then the condition
becomes true
...


||

Called Logical OR Operator
...


(A || B) is true
...
Use to
reverses the logical state of its operand
...


!(A && B) is true
...

Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator
...
The goal of the operator is to decide
which value should be assigned to the variable
...
out
...
out
...
This is mainly used for Arrays
...
The variable will be available within the for
block and its value would be the same as the current array element
...
The expression can be
an array variable or method call that returns an array
...
out
...
out
...
out
...
out
...
out
...
The break keyword must be used inside any
loop or a switch statement
...

Syntax:
The syntax of a break is a single statement inside any loop:
break;
Example:
public class Test {

public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
break;
}
System
...
print( x );
System
...
print("\n");

}
}
}
This would produce the following result:
10
20
The continue Keyword:
The continue keyword can be used in any of the loop control structures
...



In a for loop, the continue keyword causes flow of control to immediately jump to the
update statement
...


Syntax:
The syntax of a continue is a single statement inside any loop:
continue;
Example:
public class Test {

public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System
...
print( x );
System
...
print("\n");
}
}
}
This would produce the following result:
10
20
40
50

Java Programs
Java programs are frequently asked in the interview
...
Let's see the list of java programs
...


Input: 10
Output: 0 1 1 2 3 5 8 13 21 34

2) Prime number
Write a java program to check prime number
...

Input: 329
Output: not palindrome number
Input: 12321
Output: palindrome number

4) Factorial number
Write a java program to print factorial of a number
...

Input: 153
Output: Armstrong number
Input: 22
Output: not Armstrong number
ARRAYS

Java Array
Normally, array is a collection of similar type of elements that have contiguous memory location
...
It is a data structure where we
store similar elements
...

Array in java is index based, first element of the array is stored at 0 index
...

Random access: We can get any data located at any index position
...
It doesn't grow its size at
runtime
...


Types of Array in java

There are two types of array
...
dataType[] arr; (or)
2
...
dataType arr[];
Instantiation of an Array in java
1
...

1
...

3
...

5
...

7
...

9
...

11
...


class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i ...
System
...
println(a[i]);
14
...
}}
Output: 10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:
1
...

1
...

3
...

5
...

7
...

9
...


class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i ...
out
...

Syntax to Declare Multidimensional Array in java
1
...

3
...


dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in java
1
...

2
...

4
...

6
...

8
...


arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example of Multidimensional java array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array
...

2
...

4
...

6
...

8
...

10
...

12
...

14
...


class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System
...
print(arr[i][j]+" ");
}
System
...
println();
}
}}
Output:1 2 3
2 4 5
4 4 5

Copying a java array

We can copy an array to another by the arraycopy method of System class
...
public static void arraycopy(

2
...
)
Example of arraycopy method
1
...

public static void main(String[] args) {
3
...

'i', 'n', 'a', 't', 'e', 'd' };
5
...

7
...
arraycopy(copyFrom, 2, copyTo, 0, 7);
8
...
out
...

}
10
...

1
...

3
...

5
...

7
...

9
...

11
...

13
...

15
...

17
...

19
...
out
...
out
...
5 introduced a new for loop known as foreach loop or enhanced for loop, which enables
you to traverse the complete array sequentially without using an index variable
...
9, 2
...
4, 3
...
out
...
9
2
...
4
3
...
You can use one of the following three loops:


while Loop



do
...
It is a template or blueprint from
which objects are created
...
class {
2
...

method;
4
...
We
are creating the object of the Student class by new keyword and printing the objects value
...
class Student1{
2
...
String name;//data member(also instance variable)
4
...
public static void main(String args[]){
6
...
System
...
println(s1
...
System
...
println(s1
...
}
10
...
g
...
It can be physical or logical (tengible and intengible)
...

An object has three characteristics:




state: represents data (value) of an object
...

identity: Object identity is typically implemented via a unique ID
...
But,it is used internally by the JVM to identify each
object uniquely
...
Its name is Reynolds, color is white etc
...
It
is used to write, so writing is its behavior
...
Class is a template or blueprint from which objects are
created
...

Instance variable in Java
A variable that is created inside the class but outside the method, is known as instance
variable
...
It gets memory at runtime
when object(instance) is created
...

Method in Java
In java, a method is like function i
...
used to expose behaviour of an object
...


Example of Object and class that maintains the records of students
In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method on it
...

1
...
int rollno;
3
...

5
...
rollno=r;
7
...
}
9
...
void displayInformation(){System
...
println(rollno+" "+name);}//method
11
...
public static void main(String args[]){
13
...
Student2 s2=new Student2();
15
...
s1
...
s2
...

19
...
displayInformation();
20
...
displayInformation();
21
...
}
23
...
Here, s1 and s2 both are reference
variables that refer to the objects allocated in memory
...
Its exaplanation
is same as in the above Student class example
...
class Rectangle{
2
...
int width;
4
...
void insert(int l,int w){
6
...
width=w;
8
...

10
...
out
...

12
...
Rectangle r1=new Rectangle();
14
...

16
...
insert(11,5);
17
...
insert(3,15);
18
...
r1
...
r2
...
}
22
...
They are:
 By new keyword
 By newInstance() method




By clone() method
By factory method etc
...

When you call the System
...
println method, for example, the system actually executes several
statements in order to display a message on the console
...




int: return type



funcName: function name



a, b: formal parameters



int a, int b: list of parameters

Methods are also known as Procedures or Functions:


Procedures: They don't return any value
...


Method definition consists of a method header and a method body
...




returnType: Method may return a value
...
The method signature consists of the method
name and the parameter list
...
These are optional, method may contain zero parameters
...


If a class have multiple methods by same name but different parameters, it is known
as Method Overloading
...


Different ways to overload the method
There are two ways to overload the method in java
1
...
By changing the data type

In java, Methood Overloading is not possible by changing the return type of the method
...
of
arguments
In this example, we have created two overloaded methods, first sum method performs
addition of two numbers and second sum method performs addition of three numbers
...
class Calculation{

2
...
out
...

void sum(int a,int b,int c){System
...
println(a+b+c);}
4
...

public static void main(String args[]){
6
...

obj
...

obj
...

10
...
}
Output:30
40

2)Example of Method Overloading by changing data type of
argument
In this example, we have created two overloaded methods that differs in data type
...

1
...

void sum(int a,int b){System
...
println(a+b);}
3
...
out
...

5
...

Calculation2 obj=new Calculation2();
7
...
sum(10
...
5);
8
...
sum(20,20);
9
...
}
11
...
0
40

Can we overload main() method?
Yes, by method overloading
...
Let's see the simple example:
1
...

public static void main(int a){
3
...
out
...

}

5
...

public static void main(String args[]){
7
...
out
...

main(10);
9
...
}
Output:main() method invoked
10

CONSTRUCTORS
Constructor in java is a special type of method that is used to initialize the object
...
It constructs the values i
...
provides
data for the object that is why it is known as constructor
...

1
...
Constructor must have no explicit return type
Types of java constructors

There are two types of constructors:
1
...
Parameterized constructor

Java Default Constructor
A constructor that have no parameter is known as default constructor
...
(){}

Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class
...


1
...

3
...

5
...


class Bike1{
Bike1(){System
...
println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}

Test it Now

Output:
Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default constructor
...
depending on the
type
...
class Student3{
2
...
String name;

4
...

6
...

8
...

10
...

12
...


void display(){System
...
println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1
...
display();
}
}

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
...


Java parameterized constructor
A constructor that have parameters is known as parameterized constructor
...

Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters
...


1
...

int id;
3
...

5
...

id = i;
7
...

}
9
...
out
...

11
...

13
...

15
...

17
...
display();
s2
...
The compiler differentiates these constructors by taking into account the
number of parameters in the list and their type
...
class Student5{
2
...

String name;
4
...

Student5(int i,String n){
6
...

name = n;
8
...

Student5(int i,String n,int a){
10
...
name = n;
12
...
}
14
...
out
...

16
...
Student5 s1 = new Student5(111,"Karan");
18
...
s1
...
s2
...
}

22
...
They are given below
...


Method is used to expose behaviour of
an object
...


Method must have return type
...


Method is invoked explicitly
...

any case
...


Method name may or may not be same
as class name
...
But, we can copy the values of one object to another like
copy constructor in C++
...
They are:




By constructor
By assigning the values of one object into another
By clone() method of Object class

In this example, we are going to copy the values of one object into another using java
constructor
...
class Student6{
2
...

String name;
4
...

id = i;
6
...

}
8
...

Student6(Student6 s){
10
...
id;
11
...
name;
12
...
void display(){System
...
println(id+" "+name);}
14
...
public static void main(String args[]){
16
...
Student6 s2 = new Student6(s1);
18
...
display();
19
...
display();
20
...
}
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)
...
You can perform any operation in
the constructor as you perform in the method
...
We can apply java static
keyword with variables, methods, blocks and nested class
...

The static can be:
1
...

3
...


variable (also known as class variable)
method (also known as class method)
block
nested class

1) Java static variable
If you declare any variable as static, it is known static variable
...
g
...

The static variable gets memory only once in class area at the time of class loading
...

You can access other static methods or fields from a static method
...

You cannot declare local static variables even if the method is static
...
e it saves memory)
...
class Student{
2
...

String name;
4
...
}

Suppose there are 500 students in my college, now all instance data members will get memory
each time when object is created
...
Here, college refers to the common property of all objects
...

Java static property is shared to all objects
...

2
...

4
...

6
...

8
...

10
...

12
...

14
...

16
...

18
...

20
...


//Program of static variable
class Student8{
int rollno;
String name;
static String college ="ITS";
Student8(int r,String n){
rollno = r;
name = n;
}
void display (){System
...
println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1
...
display();
}
}

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
...

So each objects will have the value 1 in the count variable
...

2
...

4
...

6
...

8
...

10
...

12
...

14
...

16
...
out
...


1
...

3
...

5
...

7
...

9
...

11
...


class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;
System
...
println(count);
}
public static void main(String args[]){
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();

13
...

15
...
}
Test it Now
Output:1
2
3

2) Java static method
If you apply static keyword with any method, it is known as static method
...

A static method can be invoked without the need for creating an instance of a class
...


Example of static method
1
...

2
...
class Student9{
4
...

String name;
6
...

8
...

college = "BBDIT";
10
...

12
...
rollno = r;
14
...
}
16
...
void display (){System
...
println(rollno+" "+name+" "+college);}
18
...
public static void main(String args[]){
20
...
change();
21
...
Student9 s1 = new Student9 (111,"Karan");
23
...
Student9 s3 = new Student9 (333,"Sonoo");
25
...
s1
...
s2
...
s3
...
}
30
...

2
...

4
...

6
...

8
...

10
...

12
...
cube(5);
System
...
println(result);
}
}

Output:125

Restrictions for static method
There are two main restrictions for the static method
...
The static method can not use non static data member or call non-static method directly
...
this and super cannot be used in static context
...
class A{
2
...

4
...
System
...
println(a);
6
...
}
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
...

It is executed before main method at the time of classloading
...
class A2{
2
...
out
...
public static void main(String args[]){
4
...
out
...
}
6
...
7
...
class A3{
2
...
System
...
println("static block is invoked");
4
...
exit(0);
5
...
}
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)

Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object
...
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
...

Why use inheritance in java



For Method Overriding (so runtime polymorphism can be achieved)
...


Syntax of Java Inheritance
1
...
{
3
...
}
The extends keyword indicates that you are making a new class that derives from an existing
class
...
The new class is called
a subclass
...

Relationship between two classes is Programmer IS-A Employee
...


1
...
float salary=40000;
3
...
class Programmer extends Employee{
5
...
public static void main(String args[]){
7
...

System
...
println("Programmer salary is:"+p
...

System
...
println("Bonus of Programmer is:"+p
...
}
11
...
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
...
code reusability
...

In java programming, multiple and hybrid inheritance is supported through interface only
...


Note: Multiple inheritance is not supported in java through class
...
e
...
For Example:

Q) Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java
...
The C class inherits A and B classes
...

Since compile time errors are better than runtime errors, java renders compile time error if you
inherit 2 classes
...

1
...
void msg(){System
...
println("Hello");}
3
...
class B{
5
...
out
...
}
7
...

9
...
C obj=new C();
11
...
msg();//Now which msg() method would be invoked?
12
...
}
: output
Compile Time Error

ABSTRACT CLASS
1
...

2
...

3
...

4
...
It cannot be instantiated
...
Abstract methods must be implemented in the child class (if the class is not abstract) otherwise
program will throw compilation error
...
Abstraction is a process of hiding the implementation details and showing only functionality to
thE USER
...
Abstract class (0 to 100%)
2
...
out
...
out
...
display();
}
}

Output:
Unresolved compilation problem: Cannot instantiate the type AbstractEx1

Note: The class that extends the abstract class, have to implement all the abstract methods of
abstract class, else they can be declared abstract in the class as well
...

2) Always end the declaration with a semicolon(;)
...
An abstract class must be extended and in a same way abstract method
must be overridden
...

Note: The class which is extending abstract class must override (or implement) all the abstract
methods
...
out
...
out
...
disp2();
}
}

Output:
I'm overriding abstract method

An abstract class can have data member, abstract method, method body, constructor and even main()
method
...
//example of abstract class that have method body
2
...

Bike(){System
...
println("bike is created");}
4
...

void changeGear(){System
...
println("gear changed");}
6
...

8
...

10
...

12
...

14
...

16
...


void run(){System
...
println("running safely
...
run();
obj
...

gear changed

Rule: If there is any abstract method in a class, that class must be abstract
...
class Bike12{
2
...
}
OUTPUT:
compile time error

Rule: If you are extending any abstract class that have abstract method, you must either
provide the implementation of the method or make this class abstract
...
It has static constants and abstract methods only
...
There can be only abstract
methods in the java interface not method body
...

Understanding relationship between classes and interfaces

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


1
...

3
...

5
...

7
...

9
...

11
...


interface printable{
void print();
}
class A6 implements printable{
public void print(){System
...
println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj
...
e
...


1
...

3
...

5
...

7
...

9
...

11
...

13
...

15
...

17
...

19
...
out
...
out
...
print();
obj
...

But it is supported in case of interface because there is no ambiguity as implementation is provided by
the implementation class
...

2
...

4
...

6
...

8
...

10
...

12
...

14
...
out
...
obj
...
}
17
...


Interface inheritance
A class implements interface but one interface extends another interface
...

2
...

4
...

6
...

8
...

10
...

12
...

14
...

16
...


interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class Testinterface2 implements Showable{
public void print(){System
...
println("Hello");}
public void show(){System
...
println("Welcome");}
public static void main(String args[]){
Testinterface2 obj = new Testinterface2();
obj
...
show();
}
}
Hello
Welcome

KEY POINTS
1)We can’t instantiate an interface in java
...
On the other
hand, abstract class provides partial abstraction as it can have abstract and concrete(methods with
body) methods both
...

4) While providing implementation in class of any method of an interface, it needs to be
mentioned as public
...

6) Interface cannot be declared as private, protected or transient
...

8) Variables declared in interface are public, static and final by default
...

We can’t instantiate an interface in java
...
On the other
hand, abstract class provides partial abstraction as it can have abstract and concrete(methods with
body) methods both
...

4) While providing implementation in class of any method of an interface, it needs to be
mentioned as public
...

6) Interface cannot be declared as private, protected or transient
...

8) Variables declared in interface are public, static and final by default
...

9) Interface variables must be initialized at the time of declaration otherwise compiler will
through an error
...

10) Inside any implementation class, you cannot change the variables declared in interface
because by default, they are public, static and final
...
When we tried to set the value for variable x we got compilation
error as the variable x is public static final by default and final variables can not be re-initialized
...
Class implements
interface and interface extends interface
...

13) If there are having two or more same methods in two interfaces and a class implements
both interfaces, implementation of one method is enough
...

interface
{
public
}
interface
{
public
}

A
void aaa();
B
int aaa();

class Central implements A,B
{
public void aaa() // error
{
}
public int aaa() // error
{
}
public static void main(String arg[])
{
}
}

15) Variable names conflicts can be resolved by interface name e
...
out
...
out
...
x);
System
...
println(B
...

2) Abstract class doesn't support multiple
inheritance
...

4) Abstract class can have static methods, main
method and constructor
...

6) The abstract keyword is used to declare
abstract class
...

Interface supports multiple inheritance
...

Interface can't have static methods, main
method or constructor
...

The interface keyword is used to declare
interface
...

1
...

3
...

5
...

7
...

9
...

11
...

13
...


//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
...
println("I am C");}
}
//Creating subclass of abstract class, now we need to provide the implementation of rest of the
methods
class M extends B{
public void a(){System
...
println("I am a");}
public void b(){System
...
println("I am b");}
public void d(){System
...
println("I am d");}
}

15
...

17
...

19
...

21
...

23
...

25
...

27
...

29
...
a();
a
...
c();
a
...
e
...


Additionally, it can access all the members of outer class including private data members and
methods
...
class Java_Outer_class{
2
...
class Java_Inner_class{
4
...
}
6
...
They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private
...

3) Code Optimization: It requires less code to write
...
The non-static nested classes
are also known as inner classes
...
Non-static nested class(inner class)
o a)Member inner class
o b)Annomynous inner class
o c)Local inner class
2
...

Syntax:
1
...
//code
3
...
//code
5
...
}
EXAMPLE:

class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System
...
println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1
...
new Inner();
in
...
In such
case, instance of inner class is created inside the instance of outer class
...
It should be used if you
have to override method of class or interface
...
Class (may be abstract or concrete)
...
Interface
Java anonymous inner class example using class
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System
...
println("nice fruits");}
};
p
...
Person p=new Person(){
2
...
out
...
};
1
...


2
...


Java Local inner class
A class i
...
created inside a method is called local inner class in java
...


Java local inner class example
public class localInner1{
private int data=30;//instance variable
void display(){
class Local{
void msg(){System
...
println(data);}
}
Local l=new Local();
l
...
display();
}
}

Rule: Local variable can't be private, public or protected
...


2) Local inner class cannot access non-final local variable till JDK 1
...
Since JDK 1
...


Java static nested class
A static class i
...
created inside a class is called static nested class in java
...
It can be accessed by outer class name
...

Static nested class cannot access non-static (instance) data member or method
...
out
...
Inner obj=new TestOuter1
...
msg();
}
}
In this example, you need to create the instance of static nested class because it has instance method
msg()
...


Java static nested class example with static method
If you have the static member inside static nested class, you don't need to create instance of static
nested class
...
class TestOuter2{
2
...
static class Inner{
4
...
out
...
}
6
...
TestOuter2
...
msg();//no need to create the instance of static nested class
8
...
}

PACKAGES IN JAVA





A java package is a group of similar types of classes, interfaces and sub-packages
...

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc
...


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

3) Java package removes naming collision
...
lang
java
...
util
java
...
awt
java
...
g classes which defines primitive data
types, math operations, etc
...

Contains classes for supporting input / output operations
...

Contains classes for creating Applets
...

Contains classes for supporting networking operations
...
Suppose, we want to create a package
named relational which contains a class named Compare
...
Then create the
Compare class with the first statement being package relational;
...
Following program shows the creation and use of Compare class
...

* this must be same as the directory under
* which this file is saved */
public class Compare {
public int getMax(int x, int y) {
if ( x > y ) {
return x;
}
else {
return y;
}

}
}
Use 'Compare' class to get the maximum of two values

import relational
...
getMax(val1, val2); // get the max value
System
...
println("Maximum value is " + max);
}
}
Please note that PackageDemo
...
java must be saved inside relational directory since it is a part of the package
...
When we import a
package, subpackages are not imported by default
...
In the
following statement :
import java
...
*;
util is a subpackage created inside java package
...
It facilitates accessing any static member of
an imported class directly i
...

Following program differentiates between import and static import :
import the ' Math ' class in ' java
...
lang
...
0;
double sqroot = Math
...
out
...
root of " + val + " is " + sqroot);
}
}
static import all the members of ' Math' class

import static java
...
Math
...
0;
double sqroot = sqrt(val); // Access sqrt() method directly
System
...
println("Sq
...


Simple example of java package
The package keyword is used to create a package in java
...
//save as Simple
...
package mypack;
3
...
public static void main(String args[]){
5
...
out
...

}

7
...

1
...
*;
2
...
classname;
3
...

1) Using packagename
...
* then all the classes and interfaces of this package will be accessible but not
subpackages
...


Example of package that import the packagename
...

2
...

4
...

6
...
java

1
...

3
...

5
...

7
...

9
...

11
...
java

package pack;
public class A{
public void msg(){System
...
println("Hello");}
}

package mypack;
import pack
...
msg();
}
}

Output:Hello

2) Using packagename
...
classname then only declared class of this package will be accessible
...
classname
1
...

3
...

5
...


//save by A
...

2
...

4
...

6
...

8
...

10
...


//save by B
...
out
...
A;
class B{
public static void main(String args[]){
A obj = new A();
obj
...
Now
there is no need to import
...

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

2
...

4
...

6
...
java
package pack;
public class A{
public void msg(){System
...
println("Hello");}
}

1
...

3
...

5
...

7
...

9
...
java
package mypack;
class B{
public static void main(String args[]){
pack
...
A();//using fully qualified name
obj
...


EXCEPTIONAL HANDLING
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 java, exception is an event that disrupts the normal flow of the program
...

The core advantage of exception handling is to maintain the normal flow of the application
...

It throws an exception whenever a calling method encounters an error providing that the
calling method takes care of that error
...
This is done with the help of try-catch blocks
...
The sun microsystem says there are three types of exceptions:
1
...
Unchecked Exception
3
...
If these exceptions
are not handled/declared in the program, it will give compilation error
...


:-

Unchecked
Exceptions
Runtime Exceptions are also known as Unchecked Exceptions as the compiler do not check
whether the programmer has handled them or not but it’s the duty of the programmer to handle
these
exceptions
and
provide
a
safe
exit
...

ExamplesofUncheckedExceptions:ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
NegativeArraySizeException etc
...
g
...


There are given some scenarios where unchecked exceptions can occur
...

1
...

1
...
System
...
println(s
...
Suppose I have a
string variable that have characters, converting this variable into digit will occur
NumberFormatException
...
String s="abc";
2
...
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
...
a[10]=50; //ArrayIndexOutOfBoundsException

Java Exception Handling Keywords
There are 5 keywords used in java exception handling
...

2
...

4
...


try
catch
finally
throw
throws

Java try block
Java try block is used to enclose the code that might throw an exception
...

Java try block must be followed by either catch or finally block
...
try{
2
...
}catch(Exception_class_Name ref){}
Syntax of try-finally block
1
...
//code that may throw exception
3
...
It must be used after the try block only
...


Problem without exception handling
Let's try to understand the problem if we don't use try-catch block
...
public class Testtrycatch1{
2
...

int data=50/0;//may throw exception
4
...
out
...
");
5
...
}

Output:
Exception in thread main java
...
ArithmeticException:/ by zero

As displayed in the above example, rest of the code is not executed (in such case, rest of the
code
...

There can be 100 lines of code after exception
...


Solution by exception handling
Let's see the solution of above problem by java try-catch block
...
public class Testtrycatch2{
2
...

try{
4
...

}catch(ArithmeticException e){System
...
println(e);}
6
...
out
...
");
7
...
}

Output:
Exception in thread main java
...
ArithmeticException:/ by zero
rest of the code
...
e
...

statement is printed
...
The syntax for multiple catch blocks looks
like the following:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}

1
...
public static void main(String args[]){
3
...

int a[]=new int[5];
5
...
}
7
...
out
...
catch(ArrayIndexOutOfBoundsException e){System
...
println("task 2 completed");}
9
...
out
...

11
...
out
...
");
12
...
}
Output:task1 completed
rest of the code
...
e
...

1
...
public static void main(String args[]){
3
...

int a[]=new int[5];
5
...

}
7
...
out
...

catch(ArithmeticException e){System
...
println("task1 is completed");}

9
...
out
...
System
...
println("rest of the code
...
}
12
...


Syntax of Nested try Catch

...


Nested try catch example – explanation

1
...
public static void main(String args[]){
3
...

try{
5
...
out
...

int b =39/0;
7
...
out
...

9
...
int a[]=new int[5];
11
...
}catch(ArrayIndexOutOfBoundsException e){System
...
println(e);}
13
...
System
...
println("other statement”);
15
...
out
...

17
...
out
...
");
18
...
}

Java finally block is a block that is used to execute important code such as closing
connection, stream etc
...

Java finally block must be followed by try or catch block
...
A finally statement must be associated with a try statement
...

2
...
It is
not mandatory to include a finally block at all, but if you do, it will run regardless of whether an
exception was thrown and handled by the try and catch parts of the block
...
In normal execution the finally block is executed after try block
...

4
...

5
...

To understand above concepts better refer the below examples
...
exit() method
...

Finally block and Return statement

Finally block executes even if there is a return statement in try-catch block
...
out
...
myMethod());
}
public static int myMethod()
{
try {
return 112;
}
finally {
System
...
println("This is Finally block");
System
...
println("Finally block ran even after return statement");
}
}
}

Output of above program:
This is Finally block
Finally block ran even after return statement
112

Examples of Try catch finally blocks
Example 1: Below example illustrates finally block when no exception occurs in try block
class Example1{
public static void main(String args[]){
try{

System
...
println("First statement of try block");
int num=45/3;
System
...
println(num);
}
catch(ArrayIndexOutOfBoundsException e){
System
...
println("ArrayIndexOutOfBoundsException");
}
finally{
System
...
println("finally block");
}
System
...
println("Out of try-catch-finally block");
}
}

Output:
First statement of try block
15
finally block
Out of try-catch-finally block

Example 2:Below example illustrates finally block execution when exception occurs in try block
but doesn’t get handled in catch block
...
out
...
out
...
out
...
out
...
out
...
lang
...
com
...
main(Details
...


class Example3{
public static void main(String args[]){
try{
System
...
println("First statement of try block");
int num=45/0;
System
...
println(num);
}
catch(ArithmeticException e){
System
...
println("ArithmeticException");
}
finally{
System
...
println("finally block");
}
System
...
println("Out of try-catch-finally block");
}
}

Output:
First statement of try block
ArithmeticException
finally block
Out of try-catch-finally block

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
...

Rule: By default Unchecked Exceptions are forwarded in calling chain (propagated)
...

2
...

4
...

6
...

8
...

10
...

12
...

14
...


class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System
...
println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj
...
System
...
println("normal flow
...
}
18
...
Output:exception handled
20
...


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
...


THROW AND THROWS
No
...

Checked exception cannot be propagated
using throw only
...

Throw is used within the method
...


throws
Java throws keyword is used to declare an
exception
...

Throws is followed by class
...

You can declare multiple exceptions e
...

public void method()throws
IOException,SQLException
...
void m(){
2
...
}

Java throws example
1
...
//method code
3
...
void m()throws ArithmeticException{
2
...
}
The Java throw keyword is used to explicitly throw an exception
...
out
...
out
...
");
}

}
Output:
Exception in thread main java
...
ArithmeticException:not valid

Example demonstrating throw Keyword

class Test
{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
System
...
println("Exception caught");
}
}
public static void main(String args[])
{
avg();
}
}

In the above example the avg() method throw an instance of ArithmeticException, which
is successfully handled using the catch statement
...
io
...
out
...
p();
System
...
println("normal flow");
}
}

The Java throws keyword is used to declare an exception
...

Syntax of java throws
1
...
//method code
3
...

error: beyond your control e
...
you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError
...

It provides information to the caller of the method about the exception
...

import java
...
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
...
println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj
...
out
...
");

} }

Output:
exception handled
normal flow
...
The java final keyword can be
used in many context
...
variable
2
...
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
...




The blank final variable can be static also which will be initialized in the static block only
...


1
...
final int speedlimit=90;//final variable
3
...
speedlimit=400;
5
...
public static void main(String args[]){
7
...
obj
...
}
10
...

Example of final method
class Bike{
final void run(){System
...
println("running");}
}
class Honda extends Bike{
void run(){System
...
println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda
...

Example of final class
final class Bike{}
class Honda1 extends Bike{
void run(){System
...
println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda();
honda
...
For Example:
class Bike{
final void run(){System
...
println("running
...
run();
}
}
Output:running
...
For example:
class Bike10{
final int speedlimit;//blank final variable
Bike10(){
speedlimit=70;
System
...
println(speedlimit);
}
public static void main(String args[]){
new Bike10();
}
}

Output:70

static blank final variable

A static final variable that is not initialized at the time of declaration is known as static blank
final variable
...

Example of static blank final variable
1
...
static final int data;//static blank final variable
3
...
public static void main(String args[]){
5
...
out
...
data);
6
...
}
What is final parameter?

If you declare any parameter as final, you cannot change the value of it
...

2
...

4
...

6
...

8
...

10
...
cube(5);
}
}

Output:Compile Time Error

Java finalize example
1
...

3
...

5
...

7
...

9
...
out
...
gc();
}}

THREADS
Multitasking

Multitasking is a process of executing multiple tasks simultaneously
...
Multitasking can be achieved by two ways:



Process-based Multitasking(Multiprocessing)
Thread-based Multitasking(Multithreading)

1) Process-based Multitasking (Multiprocessing)





Each process have its own address in memory i
...
each process allocates separate memory area
...

Cost of communication between the process is high
...


2) Thread-based Multitasking (Multithreading)




Threads share the same address space
...

Cost of communication between the thread is low
Title: A Complete Java Study Material
Description: A Complete notes for Java programming for beginners Contents included: An overview of Java – Data Types – Variables and Arrays – Operators – Control Statements – Classes – Objects – Methods – Inheritance - Packages – Abstract classes – Interfaces and Inner classes – Exception handling - Introduction to Threads – Multithreading – String handling – Streams and I/O – Applets. Easily understandable for beginners.