0% found this document useful (0 votes)
53 views177 pages

Java Notes

Notes

Uploaded by

likithbas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
53 views177 pages

Java Notes

Notes

Uploaded by

likithbas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 177

MR20-1CS0106

JAVA PROGRAMMING

DIGITAL NOTES
B. TECH II YEAR – II SEM (2022-23)

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AI & ML)


B.TECH CSE (AI&ML) R-20

MALLAREDDY UNIVERSITY

II Year B.Tech – II Semester L/T/P/C


3/-/-/3

(MR20-1CS0106) JAVA PROGRAMMING

Course Objectives:
 To introduce the object-oriented programming concepts.
 To understand object-oriented programming concepts, and apply them in solving
problems and to introduce the principles of inheritance and polymorphism; and
demonstrate howthey relate to the design of abstract classes
 To introduce the implementation of packages and interfaces
 To introduce the concepts of exception handling and multithreading.
 To introduce the design of Graphical User Interface using applets and swing controls.

UNIT I - JAVA PROGRAMMING


History of Java, comments, Java Buzz words, Data types, Variables, Constants, Scope and Lifetime of
variables, Operators, Type conversion and casting, Enumerated types, Control flow- block scope,
conditional statements, loops, break and continue statements, arrays.
Classes and Objects: class, object, and its methods constructors and methods, access control, this
reference, overloading constructors, recursion, exploring string class, garbage collection.
[REFERENCE – III]

UNIT II – INHERITANCE, POLYMORPHISM


Inheritance – Inheritance types, super keyword, preventing inheritance: final classes andmethods.
Polymorphism – method overloading and method overriding, abstract classes and methods.
[REFERENCE – IV]

UNIT III – INTERFACES AND PACKAGES


Interfaces- Interfaces vs Abstract classes, defining an interface, implement interfaces, accessing
implementations through interface references, extending interface, inner class.
Packages- Defining, creating and accessing a package, importing packages.
[REFERENCE – II]
UNIT IV - EXCEPTION HANDLING
Exception handling- Benefits of exception handling, the classification of exceptions - exception
hierarchy, checked exceptions and unchecked exceptions, usage of try, catch, throw, throws and
finally, creating own exception subclasses.
B.TECH CSE (AI&ML) R-20

Multithreading – Differences between multiple processes and multiple threads, thread life cycle,
creating threads, interrupting threads, thread priorities, synchronizing threads, inter- thread
communication, producer consumer problem.
[REFERENCE – I]

UNIT V - EVENT HANDLING AND GUI PROGRAMMING WITH JAVA


Collection Framework in Java – Introduction to java collections, Overview of java collection framework,
commonly used collection classes- Array List, Vector, Hash table, Stack.
Files- Streams- Byte streams, Character streams, Text input/output, Binary input/output, File management
using File class.
[REFERENCE – III]

REFERENCE BOOKS:
1. Java for Programmers, P.J.Deitel and H.M.Deitel.
2. Object Oriented Programming through Java, P. RadhaKrishna, CRC Press.
3. Java Fundamentals–A Comprehensive Introduction, Herbert Schildt and Dale Skrien, TMH.
4. Programming in Java, S. Malhotra and S. Choudhary, Oxford Universities Press.

COURSE OUTCOMES:

 Understand the use of OOP’s Concepts


 To understand the Object-Oriented Programming Principles to develop java programs.
 Design and develop user defined classes using packages and interfaces.
 To use advanced java programming concepts AWT, Swings and applets to develop
complex user interface applications.
 Analyze Inheritance, Exception Handling mechanisms for implement applications.
Unit-1

OOP Concepts

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.

PROGRAMMING IN JAVA Page 2


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.

Benefits of Inheritance
 One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent code
exists in two related classes, the hierarchy can usually be refactored to move the common
code up to a mutual superclass. This also tends to result in a better organization of code and
smaller, simpler compilation units.
 Inheritance can also make application code more flexible to change because classes that
inherit from a common superclass can be used interchangeably. If the return type of a
method is superclass
 Reusability - facility to use public methods of base class without rewriting the same.
 Extensibility - extending the base class logic as per business logic of the derived class.

 Data hiding - base class can decide to keep some data private so that it cannot be
altered by the derived class

PROGRAMMING IN JAVA Page 3


Procedural and object oriented programming paradigms

Java Programming- History of Java

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.
PROGRAMMING IN JAVA Page 4
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.

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
PROGRAMMING IN JAVA Page 5
Java Comments
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement. It can also be used to hide program code for specific time.

Types of Java Comments

There are 3 types of comments in java.

1. Single Line Comment


2. Multi Line Comment
3. Documentation Comment
Java Single Line Comment
The single line comment is used to comment only one line.
Syntax:
1. //This is single line comment

Example:
public class CommentExample1 {
public static void main(String[] args) {
int i=10;//Here, i is a variable
System.out.println(i);
}
}
Output:

10
Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

Syntax:

/*
This
is
multi line
comment
*/
Example:
public class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
PROGRAMMING IN JAVA Page 6
print variable in java. */
int i=10;
System.out.println(i);
}}
Output:

10
Java Documentation Comment
The documentation comment is used to create documentation API. To create documentation API, you need
to use javadoc tool.
Syntax:
/**
This
is
documentation
comment
*/
Example:
/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
public class Calculator {
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b){return a+b;}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b){return a-b;}
}
Compile it by javac tool:

javac Calculator.java

Create Documentation API by javadoc tool:

javadoc Calculator.java

Now, there will be HTML files created for your Calculator class in the current directory. Open the HTML
files and see the explanation of Calculator class provided through documentation comment.

Data Types
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

PROGRAMMING IN JAVA Page 7


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

Java Variable Example: Add Two Numbers


class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}}

Output:20

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.

Types of Variable
There are three types of variables in java:

o local variable
o instance variable
PROGRAMMING IN JAVA Page 8
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

Constants in Java

A constant is a variable which cannot have its value changed after declaration. It uses the 'final'
keyword.

Syntax
modifier final dataType variableName = value; //global constant

modifier static final dataType variableName = value; //constant within a c

Scope and Life Time of Variables


The scope of a variable defines the section of the code in which the variable is visible. As a
general rule, variables that are defined within a block are not accessible outside that block.
The lifetime of a variable refers to how long the variable exists before it is destroyed.
Destroying variables refers to deallocating the memory that was allotted to the variables when
declaring it. We have written a few classes till now. You might have observed that not all
variables are the same. The ones declared in the body of a method were different from those
that were declared in the class itself. There are three types of variables: instance variables,
formal parameters or local variables and local variables.

Instance variables

Instance variables are those that are defined within a class itself and not in any method or
constructor of the class. They are known as instance variables because every instance of the

PROGRAMMING IN JAVA Page 9


class (object) contains a copy of these variables. The scope of instance variables is determined
by the access specifier that is applied to these variables. We have already seen about it earlier.
The lifetime of these variables is the same as the lifetime of the object to which it belongs.
Object once created do not exist for ever. They are destroyed by the garbage collector of Java
when there are no more reference to that object. We shall see about Java's automatic garbage
collector later on.

Argument variables

These are the variables that are defined in the header oaf constructor or a method. The scope
of these variables is the method or constructor in which they are defined. The lifetime is
limited to the time for which the method keeps executing. Once the method finishes
execution, these variables are destroyed.

Local variables

A local variable is the one that is declared within a method or a constructor (not in the
header). The scope and lifetime are limited to the method itself.

One important distinction between these three types of variables is that access specifiers can
be applied to instance variables only and not to argument or local variables.

In addition to the local variables defined in a method, we also have variables that are defined
in bocks life an if block and an else block. The scope and is the same as that of the block
itself.

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 Hierarchy
PROGRAMMING IN JAVA Page 10
Expressions
Expressions are essential building blocks of any Java program, usually created to produce a new
value, although sometimes an expression simply assigns a value to a variable. Expressions are
built using values, variables, operators and method calls.

Types of Expressions

While an expression frequently produces a result, it doesn't always. There are three types of
expressions in Java:

 Those that produce a value, i.e. the result of (1 + 1)


 Those that assign a variable, for example (v = 10)
 Those that have no result but might have a "side effect" because an expression can include
a wide range of elements such as method invocations or increment operators that modify
the state (i.e. memory) of a program.

Java Type casting and Type conversion

Widening or Automatic Type Conversion


Widening conversion takes place when two data types are automatically converted. This happens
when:

PROGRAMMING IN JAVA Page 11


 The two data types are compatible.
 When we assign value of a smaller data type to a bigger data type.

For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.

Narrowing or Explicit Conversion


If we want to assign a value of larger data type to a smaller data type we perform explicit type
casting or narrowing.
 This is useful for incompatible data types where automatic conversion cannot be done.
 Here, target-type specifies the desired type to convert the specified value to.



Java Enum

Enum in java is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST)
etc. The java enum constants are static and final implicitly. It is available from JDK 1.5.

Java Enums can be thought of as classes that have fixed set of constants.

Simple example of java enum


class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }

public static void main(String[] args) {


for (Season s : Season.values())
System.out.println(s);
}}
Output:
WINTER
SPRING
SUMMER
FALL

PROGRAMMING IN JAVA Page 12


Control Flow Statements

The control flow statements in Java allow you to run or skip blocks of code when special
conditions are met.

The “if” Statement


The “if” statement in Java works exactly like in most programming languages. With the help of
“if” you can choose to execute a specific block of code when a predefined condition is met. The
structure of the “if” statement in Java looks like this:

if (condition) {
// execute this code
}

The condition is Boolean. Boolean means it may be true or false. For example you may put a
mathematical equation as condition. Look at this full example:

Creating a Stand-Alone Java Application


1. Write a main method that runs your program. You can write this method anywhere. In this
example, I'll write my main method in a class called Main that has no other methods. For
example:
2. public class Main
3. {
4. public static void main(String[] args)
5. {
6. Game.play();
7. }}
8. Make sure your code is compiled, and that you have tested it thoroughly.
9. If you're using Windows, you will need to set your path to include Java, if you haven't
done so already. This is a delicate operation. Open Explorer, and look inside
C:\ProgramFiles\Java, and you should see some version of the JDK. Open this folder, and
then open the bin folder. Select the complete path from the top of the Explorer window, and
press Ctrl-C to copy it.

PROGRAMMING IN JAVA Page 13


Next, find the "My Computer" icon (on your Start menu or desktop), right-click it, and select
properties. Click on the Advanced tab, and then click on the Environment variables button.
Look at the variables listed for all users, and click on the Path variable. Do not delete the
contents of this variable! Instead, edit the contents by moving the cursor to the right end,
entering a semicolon (;), and pressing Ctrl-V to paste the path you copied earlier. Then go
ahead and save your changes. (If you have any Cmd windows open, you will need to close
them.)

10. If you're using Windows, go to the Start menu and type "cmd" to run a program that
brings up a command prompt window. If you're using a Mac or Linux machine, run the
Terminal program to bring up a command prompt.
11. In Windows, type dir at the command prompt to list the contents of the current directory.
On a Mac or Linux machine, type ls to do this.

12. Now we want to change to the directory/folder that contains your compiled code. Look at
the listing of sub-directories within this directory, and identify which one contains your code.
Type cd followed by the name of that directory, to change to that directory. For example, to
change to a directory called Desktop, you would type:

cd Desktop

To change to the parent directory, type:

cd ..

Every time you change to a new directory, list the contents of that directory to see where to go
next. Continue listing and changing directories until you reach the directory that contains
your .class files.

13. If you compiled your program using Java 1.6, but plan to run it on a Mac, you'll need to
recompile your code from the command line, by typing:

javac -target 1.5 *.java

14. Now we'll create a single JAR file containing all of the files needed to run your program.

Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.

This tutorial introduces how to declare array variables, create arrays, and process arrays using
indexed variables.
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:

PROGRAMMING IN JAVA Page 14


dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Note: The style dataType[] arrayRefVar is preferred. The style dataType
arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate
C/C++ programmers.

Example:

The following code snippets are examples of this syntax:

double[] myList; // preferred way.


or
double myList[]; // works but not preferred way.

Creating Arrays:

PROGRAMMING IN JAVA Page 15


You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];


The above statement does two things:

 It creates an array using new dataType[arraySize];

 It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];


Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, ..., valuek};


The array elements are accessed through the index. Array indices are 0-based; that is, they start
from 0 to arrayRefVar.length-1.

Example:
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:

double[] myList = new double[10];


Following picture represents array myList. Here, myList holds ten double values and the indices
are from 0 to 9.

Processing Arrays:
When processing array elements, we often use either for loop or for each loop because all of the
elements in an array are of the same type and the size of the array is known.

Example:
Here is a complete example of showing how to create, initialize and process arrays:
PROGRAMMING IN JAVA Page 16
public class TestArray
{
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

This would produce the following result:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}}}

Java Console Class


PROGRAMMING IN JAVA Page 17
The Java Console class is be used to get input from console. It provides methods to read texts and
passwords.

If you read password using Console class, it will not be displayed to the user.

The java.io.Console class is attached with system console internally. The Console class is
introduced since 1.5.

Let's see a simple example to read text from console.

1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);

Java Console Example

import java.io.Console;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n); } }

Output

Enter your name: Nakul Jain


Welcome Nakul Jain

Constructors
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.
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
PROGRAMMING IN JAVA Page 18
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.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}}
Output: Bike is created

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.
class Student4{
int id;
String name;

Student4(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}}

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


class Student5{
PROGRAMMING IN JAVA Page 19
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}}

Output:

111 Karan 0
222 Aryan 25
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.
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}

Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
PROGRAMMING IN JAVA Page 20
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}}
Output:

111 Karan
111 Karan

Java-Methods
A Java method is a collection of statements that are grouped together to perform an operation.
When you call the System.out.println() method, for example, the system actually executes
several statements in order to display a message on the console.

Now you will learn how to create your own methods with or without return values, invoke a
method with or without parameters, and apply method abstraction in the program design.

CreatingMethod
Considering the following example to explain the syntax of a method −

Syntax

Here,

 public static − modifier

 int − return type

 methodName − name of the method

 a, b − formal parameters

 int a, int b − list of parameters

Method definition consists of a method header and a method body. The same is shown in the
following syntax −

Syntax

The syntax shown above includes −

 modifier − It defines the access type of the method and it is optional to use.

 returnType − Method may return a value.

 nameOfMethod − This is the method name. The method signature consists of the method
name and the parameter list.

PROGRAMMING IN JAVA Page 21


 Parameter List − The list of parameters, it is the type, order, and number of parameters
of a method. These are optional, method may contain zero parameters.

 method body − The method body defines what the method does with the statements.
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it
is known as call by value. The changes being done in the called method, is not affected in the
calling method.

Example of call by value in java


In case of call by value original value is not changed. Let's take a simple example:
class Operation{
int data=50;
void change(int data){
data=data+100;//changes will be in the local variable only
}
public static void main(String args[]){
Operation op=new Operation();
System.out.println("before change "+op.data);
op.change(500);
System.out.println("after change "+op.data);
}
}

In Java, parameters are always passed by value. For example, following program prints
i = 10, j = 20.
// Test.java
class Test {
// swap() doesn't swap i and j
public static void swap(Integer i, Integer j) {
Integer temp = new Integer(i);
i = j;
j = temp;
}
public static void main(String[] args) {
Integer i = new Integer(10);
Integer j = new Integer(20);
swap(i, j);
System.out.println("i = " + i + ", j = " + j);

PROGRAMMING IN JAVA Page 22


}
}

Static Fields and Methods

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

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

Example of static variable


//Program of static variable
class Student8{
int rollno;

PROGRAMMING IN JAVA Page 23


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

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


//Program of changing the common property of all objects(static field).

class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;

PROGRAMMING IN JAVA Page 24


}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}}

Java static block

o Is used to initialize the static data member.


o It is executed before main method at the time of class loading.

Example of static block


class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}}

Access Control

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

private access modifier


The private access modifier is accessible only within class.

Simple example of private access modifier


PROGRAMMING IN JAVA Page 25
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
}}

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
PROGRAMMING IN JAVA Page 26
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();
}}

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();
}}

PROGRAMMING IN JAVA Page 27


Understanding all java access modifiers

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

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

this keyword in java

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.

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:
PROGRAMMING IN JAVA Page 28
Difference between constructor and method in java

Java Constructor Java Method

Constructor is used to initialize the state of an object. Method is used to expose behaviour
of an object.

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

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if you Method is not provided by compiler in
don't have any constructor. any case.

PROGRAMMING IN JAVA Page 29


Constructor name must be same as the class name. Method name may or may not be

same as class name.

There are many differences between constructors and methods. They are given belo

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


class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

JAVA PROGRAMMING Page 30


UNIT – II
Inheritance : Inheritance types, super keyword, preventing inheritance: final classes and methods.

Polymorphism : Method overloading and method overriding, abstract classes and methods.

Interfaces : Interfaces vs Abstract classes, defining an interface, implement interfaces, accessing


implementations through interface references, extending interface, inner class.

Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

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 the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.

Why use inheritance in java

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


o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.

JAVA PROGRAMMING
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

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.

Java Inheritance Example:

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new
class is called child or subclass.

As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee. It means
that Programmer is a type of Employee.

class Employee
{
float salary=40000;
}
class Programmer extends Employee
{

JAVA PROGRAMMING
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

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.

Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

JAVA PROGRAMMING
Single Inheritance Example:

When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}

Output:

barking...
eating...

JAVA PROGRAMMING
Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.

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

JAVA PROGRAMMING
Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

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

JAVA PROGRAMMING
Hybrid Inheritance in Java

In Java, inheritance is the most important OOPs concept that allows to inherit the properties of a
class into another class. in general, it defines Is-A relationship. By using the inheritance feature,
we can derive a new class from an existing one. Java supports the following four types of
inheritance:

o Single Inheritance
o Multi-level Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance

In this section, we will discuss only the hybrid inheritance in Java with proper example and
different approaches for hybrid inheritance implementation.

Hybrid Inheritance:
In general, the meaning of hybrid (mixture) is made of more than one thing. In Java, the hybrid
inheritance is the composition of two or more types of inheritance. The main purpose of using
hybrid inheritance is to modularize the code into well-defined classes. It also provides the code
reusability. The hybrid inheritance can be achieved by using the following combinations:

o Single and Multiple Inheritance (not supported but can be achieved through interface)
o Multilevel and Hierarchical Inheritance
o Hierarchical and Single Inheritance
o Multiple and Multilevel Inheritance

How hybrid inheritance works in Java?

For example, there are four classes say A, B, C, and D. Assume that the class "A" and "B"
extends the class "C". Also, another class, "D," extends the class "A". Here, the class "A" is a
parent class for child class "D" and is also a child class for parent class "C". we can understand
the example through pictorial representation.

JAVA PROGRAMMING
Single and Multiple Inheritance

In the following Java program, we have achieved the hybrid inheritance by implementing the
combination of single and multiple inheritance (through interfaces).

In this program, we have taken the example of Human body that performs different
functionalities like eating, walking, talking, dancing etc. Human body may be either Male or
Female. So, Male and Female are the two interfaces of the HumanBody class. Both the child
class inherits the functionalities of the HumanBody class that represents the single Inheritance.

Suppose, Male and Female may have child. So, the Child class also inherits the functionalities of
the Male, Female interfaces. It represents the multiple inheritance.

The composition of single and multiple inheritance represents the hybrid inheritance.

Let's see the implementation.

Child.java

class HumanBody
{
public void displayHuman()
{
System.out.println("Method defined inside HumanBody class");
}
}
interface Male
{
public void show();
}
interface Female

JAVA PROGRAMMING
{
public void show();
}
public class Child extends HumanBody implements Male, Female
{
public void show()
{
System.out.println("Implementation of show() method defined in interfaces Male
and Female");
}
public void displayChild()
{
System.out.println("Method defined inside Child class");
}
public static void main(String args[])
{
Child obj = new Child();
System.out.println("Implementation of Hybrid Inheritance in Java");
obj.show();
obj.displayChild();
}
}

Output:

Implementation of Hybrid Inheritance in Java


Implementation of show() method defined in interfaces Male and Female
Method defined inside Child class

Using Multilevel and Hierarchical Inheritance

In the following figure, GrandFather is a super class. The Father class inherits the properties of
the GrandFather class. Since Father and GrandFather represents single inheritance. Further, the
Father class is inherited by the Son and Daughter class. Thus, the Father becomes the parent
class for Son and Daughter. These classes represent the hierarchical inheritance. Combinedly, it
denotes the hybrid inheritance.

JAVA PROGRAMMING
Let's implement the hybrid inheritance mechanism in a Java program.

Dauhter.java

//parent class
class GrandFather
{
public void showG()
{
System.out.println("He is grandfather.");
}
}
//inherits GrandFather properties
class Father extends GrandFather
{
public void showF()
{
System.out.println("He is father.");
}
}
//inherits Father properties
class Son extends Father
{
public void showS()
{
System.out.println("He is son.");
}
}
//inherits Father properties
public class Daughter extends Father
{
public void showD()

JAVA PROGRAMMING
{
System.out.println("She is daughter.");
}
public static void main(String args[])
{
//Daughter obj = new Daughter();
//obj.show();
Son obj = new Son();
obj.showS(); // Accessing Son class method
obj.showF(); // Accessing Father class method
obj.showG(); // Accessing GrandFather class method
Daughter obj2 = new Daughter();
obj2.showD(); // Accessing Daughter class method
obj2.showF(); // Accessing Father class method
obj2.showG(); // Accessing GrandFather class method
}
}

Output:

He is son.
He is father.
He is grandfather.
She is daughter.
He is father.
He is grandfather.

Hierarchical and Single Inheritance


In the following Java program, we have achieved the hybrid inheritance by
implementing the combination of hierarchical and single inheritance.
Here class A and class B extends the class C that represents the hierarchical inheritance.
On the other hand, class D extends the class A that represents the single inheritance.

D.java

class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");

JAVA PROGRAMMING
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
}
}
public class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[])
{
D obj = new D();
obj.disp();
}
}

Output:

Multiple and Multilevel Inheritance

We can also achieve hybrid inheritance by implementing the multiple and multilevel inheritance.
Consider the following figure that depicts an example of hybrid inheritance.

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

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

JAVA PROGRAMMING
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}
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.

2) 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();
b
ark();
}
}

JAVA PROGRAMMING
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}

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
{
public static void main(String args[])
{
Dog d=new Dog();
}
}
Output:

JAVA PROGRAMMING
animal is created
dog is created

Note: super() is added in each class constructor automatically by compiler if there is no super()
or this().

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.

Another example of super keyword where super() is provided by the compiler implicitly.

class Animal
{
Animal()
{
System.out.println("animal is created");}
}
class Dog extends Animal
{
Dog()
{
System.out.println("dog is created");
}
}
class TestSuper4
{
public static void main(String args[])
{
Dog d=new Dog();
}}

Output:

animal is created
dog is created

JAVA PROGRAMMING
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

JAVA PROGRAMMING
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in
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 a static method in Java, it is the example of compile time


polymorphism. Here, we will focus on runtime polymorphism in java.

Types of polymorphism in java:

There are two types of polymorphism in java:

1) Static Polymorphism also known as compile time polymorphism


2) Dynamic Polymorphism also known as runtime polymorphism

Compile time Polymorphism (or Static polymorphism):

Polymorphism that is resolved during compiler time is known as static polymorphism. Method
overloading is an example of compile time polymorphism.

Method Overloading: This allows us to have more than one method having the same name, if the
parameters of methods are different in number, sequence and data types of parameters. We have
already discussed Method overloading here: If you didn’t read that guide, refer: Method
Overloading 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.

JAVA PROGRAMMING
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

If the 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

For upcasting, we can use the reference variable of class type or an interface type. For Example:

interface I
{
}
class A
{
}
class B extends A implements I{}

Here, the relationship of B class would be:

B IS-A A
B IS-A I
B IS-A Object

Since Object is the root class of all classes in Java, so we can write B IS-A Object.

Example of Java Runtime Polymorphism

JAVA PROGRAMMING
In this example, we are creating two classes Bike and Splendor. Splendor 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, the 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 Splendor extends Bike
{
void run()
{
System.out.println("running safely with 60km");
}

public static void main(String args[])


{
Bike b = new Splendor();//upcasting
b.run();
}
}

Output:

1. running safely with 60km.

Java Runtime Polymorphism Example: Bank

Consider a scenario where Bank is a class that provides a method to get the rate of interest.
However, the 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.

JAVA PROGRAMMING
Note: This example is also given in method overriding but there was no upcasting.

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
{

JAVA PROGRAMMING
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 Example: Shape

class Shape
{
void draw()
{
System.out.println("drawing...");
}
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle...");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("drawing circle...");
}
}
class Triangle extends Shape
{
void draw()
{

JAVA PROGRAMMING
System.out.println("drawing triangle...");
}
}
class TestPolymorphism2
{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}
Output:
drawing rectangle...
drawing circle...
drawing triangle...

Java Runtime Polymorphism Example: Animal

class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
}
class Cat extends Animal
{
void eat()
{
System.out.println("eating rat...");
}
}
class Lion extends Animal
{
void eat()

JAVA PROGRAMMING
{
System.out.println("eating meat...");
}
}
class TestPolymorphism3
{
public static void main(String[] args)
{
Animal a;
a=new Dog();
a.eat();
a=new Cat();
a.eat();
a=new Lion();
a.eat();
}
}
Output:

eating bread...
eating rat...
eating meat...

Java Runtime Polymorphism with Data Member

A method is overridden, not the data members, so runtime polymorphism can't be achieved by
data members.

In the example given below, both the classes have a data member speedlimit. We are accessing
the data member by the reference variable of Parent class which refers to the subclass object.
Since we are accessing the data member which is not overridden, hence it will access the data
member of the Parent class always.

Rule: Runtime polymorphism can't be achieved by data members.


class Bike
{
int speedlimit=90;
}
class Honda3 extends Bike
{
int speedlimit=150;
}
public static void main(String args[])

JAVA PROGRAMMING
{
Bike obj=new Honda3();
System.out.println(obj.speedlimit);//90
}

Output:

90

Java Runtime Polymorphism with Multilevel Inheritance

Let's see the simple example of Runtime Polymorphism with multilevel inheritance.

class Animal
{
void eat()
{
System.out.println("eating");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating fruits");
}
}
class BabyDog extends Dog
{
void eat()
{
System.out.println("drinking milk");
}
public static void main(String args[])
{
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}

JAVA PROGRAMMING
Output:

eating
eating fruits
drinking Milk

Try for Output

class Animal
{
void eat()
{
System.out.println("animal is eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("dog is eating...");
}
}
class BabyDog1 extends Dog
{
public static void main(String args[])
{
Animal a=new BabyDog1();
a.eat();
}
}

Output:

Dog is eating

Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.

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.

JAVA PROGRAMMING
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
1. By changing number of arguments
2. By changing the data type

In Java, Method Overloading is not possible by changing the return type of the method only.

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

JAVA PROGRAMMING
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;

JAVA PROGRAMMING
}
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?

Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler
time error if you declare the same method having same parameters.

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[]

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

Example of Method Overloading with TypePromotion

class OverloadingCalculation1
{
void sum(int a,long b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}

public static void main(String args[])


{
OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);

}
}

JAVA PROGRAMMING
Output:40
60

Example of Method Overloading with Type Promotion if matching found


If there are matching type arguments in the method, type promotion is not performed.

class OverloadingCalculation2
{
void sum(int a,int b)
{
System.out.println("int arg method invoked");
}
void sum(long a,long b)
{
System.out.println("long arg method invoked");
}

public static void main(String args[])


{
OverloadingCalculation2 obj=new OverloadingCalculation2();
obj.sum(20,20);//now int arg sum() method gets invoked
}
}

Output:int arg method invoked

Example of Method Overloading with Type Promotion in case of ambiguity

If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.

class OverloadingCalculation3
{
void sum(int a,long b)
{
System.out.println("a method invoked");
}
void sum(long a,int b)
{
System.out.println("b method invoked");
}

JAVA PROGRAMMING
public static void main(String args[])
{
OverloadingCalculation3 obj=new OverloadingCalculation3();
obj.sum(20,20);//now ambiguity
}
}

Output:Compile Time Error

One type is not de-promoted implicitly for example double cannot be depromoted to any type
implicitly.
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 a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

o Method overriding is used to provide the specific implementation of a method which is


already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an 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.

//Java Program to demonstrate why we need method overriding


//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}

JAVA PROGRAMMING
}
//Creating a child class
class Bike extends Vehicle
{
public static void main(String args[])
{
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
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 are the same, and
there is IS-A relationship between the classes, so there is method overriding.

//Java Program to illustrate the use of Java Method Overriding


//Creating a parent class.
class Vehicle
{
//defining a method
void run()
{
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike2 extends Vehicle
{
//defining the same method as in the parent class
void run()
{
System.out.println("Bike is running safely");
}

public static void main(String args[])


{

JAVA PROGRAMMING
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

Output:

Bike is running safely

A real example of Java Method Overriding

Consider a scenario where Bank is a class that provides functionality to get the rate of interest.
However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS
banks could provide 8%, 7%, and 9% rate of interest.

Java method overriding is mostly used in Runtime Polymorphism which we will learn in next
pages.
//Java Program to demonstrate the real scenario of Java Method Overriding
//where three classes are overriding the method of a parent class.
//Creating a parent class.
class Bank
{
int getRateOfInterest()
{
return 0;
}
}
//Creating child classes.
class SBI extends Bank
{
int getRateOfInterest()
{
return 8;

JAVA PROGRAMMING
}
}

class ICICI extends Bank


{
int getRateOfInterest()
{return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest()
{
return 9;
}
}
//Test class to create objects and call the methods
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

Note 1: Can we override static method?


No, a static method cannot be overridden. It can be proved by runtime polymorphism.
Note 2 : Why can we not override static method?
It is because the static method is bound with class whereas instance method is bound with an
object. Static belongs to the class area, and an instance belongs to the heap area.
Note 3: Can we override java main method?
No, because the main is a static method.

JAVA PROGRAMMING
Note 4: Difference between method Overloading and Method Overriding in java

There are many differences between method overloading and method overriding in java. A list of
differences between method overloading and method overriding are given below:

Difference between method overloading and method overriding in java:


There are many differences between method overloading and method overriding in java. A list of
differences between method overloading and method overriding are given below:

A list of differences between overloading and overriding in Java is given below for quick
revision in tabular form.

SN Property Overloading Overriding

Must be different (at


1 Argument type Must be the same (including order).
least order).

2 Method signatures Must be different. Must be the same.

Must be the same until Java 1.4 version


3 Return type Same or different. only. Java 1.5 onwards, Covariant return
type is allowed.

Generally performed in Performed in two classes through


4 Class
the same class. Inheritance (Is-A relationship).

Private/Static/Final
5 Can be overloaded. Cannot be overridden.
method

Subclass method’s access modifier must


6 Access modifiers Anything or different. be same or higher than superclass
method access modifier.

If child class method throws any


checked exception compulsory parent
class method should throw the same
7 Throws clause Anything
exception is its parent otherwise we will
get compile-time error but there is no
restriction for an unchecked exception.

Always take care by


Always take care by JVM based on
8 Method resolution java compiler based on
runtime object.
reference type.

Also known as Also known as runtime polymorphism,


9 Polymorphism
compile-time dynamic polymorphism, or late binding.

JAVA PROGRAMMING
polymorphism, static
polymorphism, or early
binding.

10 Performance Better Less

Java Method Overloading example


class OverloadingExample
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
Java Method Overriding example
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
}

Static Binding and Dynamic Binding

JAVA PROGRAMMING
Connecting a method call to the method body is known as binding.

There are two types of binding

1. Static Binding (also known as Early Binding).


2. Dynamic Binding (also known as Late Binding).

Understanding Type

Let's understand the type of instance.

1) variables have a type


Each variable has a type, it may be primitive and non-primitive.

int data=30;

Here data variable is a type of int.

2) References have a type


class Dog
{
public static void main(String args[])
{
Dog d1;//Here d1 is a type of Dog
}
}

3) Objects have a type


An object is an instance of particular java class,but it is also an instance of its superclass.

JAVA PROGRAMMING
class Animal
{
}

class Dog extends Animal


{
public static void main(String args[])
{
Dog d1=new Dog();
}
}
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding:
When type of the object is determined at compiled time(by the compiler), it is known as static
binding. If there is any private, final or static method in a class, there is static binding.

Example of static binding

class Dog
{
private void eat()
{
System.out.println("dog is eating...");
}
public static void main(String args[])
{
Dog d1=new Dog();
d1.eat();
}
}

Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding

class Animal
{
void eat()
{

JAVA PROGRAMMING
System.out.println("animal is eating...");
}
}

class Dog extends Animal


{
void eat()
{
System.out.println("dog is eating...");
}

public static void main(String args[])


{
Animal a=new Dog();
a.eat();
}
}

Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the instance of Dog
is also an instance of Animal.So compiler doesn't know its type, only its base type.

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).

Before learning the 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 essential things to the user and hides the internal details, for
example, sending SMS where you 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 Abstraction

JAVA PROGRAMMING
There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.

Example of abstract class

1. abstract class A{}


Abstract Method in Java
A method which is declared as abstract and does not have implementation is known as an
abstract method.

Example of abstract method

1. abstract void printStatus();//no method body and abstract

JAVA PROGRAMMING
Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method run. Its
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();
}
}
Output:

running safely

Understanding the real scenario of Abstract class

In this example, Shape is the abstract class, and its implementation is provided by the Rectangle
and Circle classes.

Mostly, we don't know about the implementation class (which is hidden to the end user), and an
object of the implementation class is provided by the factory method.

A factory method is a 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();
}

JAVA PROGRAMMING
//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 a real scenario, object is provided through method, e.g., getSh
ape() method
s.draw();
}
}
Output:

drawing circle

Another example of Abstract class in java

File: TestBank.java

abstract class Bank


{
abstract int getRateOfInterest();
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class PNB extends Bank
{

JAVA PROGRAMMING
int getRateOfInterest()
{
return 8;
}
}

class TestBank
{
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}

Output:

Rate of Interest is: 7 %


Rate of Interest is: 8 %

Abstract class having constructor, data member and methods

An abstract class can have a data member, abstract method, method body (non-abstract method),
constructor, and even main() method.

File: TestAbstraction2.java

//Example of an abstract class that has abstract and non-abstract methods


abstract class Bike
{
Bike()
{
System.out.println("bike is created");
}
abstract void run();
void changeGear()
{
System.out.println("gear changed");
}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike

JAVA PROGRAMMING
{
void run()
{
System.out.println("running safely..");
}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2
{
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}

bike is created
running safely..
gear changed

Rule: If there is an abstract method in a class, that class must be abstract.


class Bike12{
abstract void run();
}
compile time error

Rule: If you are extending an abstract class that has an abstract method, you must either provide
the implementation of the method or make this class abstract.

Another real scenario of abstract class

The abstract class can also be used to provide some implementation of the interface. In such
case, the end user may not be forced to override all the methods of the interface.

Note: If you are beginner to java, learn interface first and skip this example.
interface A
{
void a();
void b();
void c();
void d();
}

abstract class B implements A


{

JAVA PROGRAMMING
public void c()
{
System.out.println("I am c");
}
}

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");
}
}

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

Output:I am a
I am b
I am c
I am d

Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.

It cannot be instantiated just like the abstract class.

JAVA PROGRAMMING
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public, static
and final by default. A class that implements an interface must implement all the methods
declared in the interface.

Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Java 8 Interface Improvement
Since Java 8, interface can have default and static methods which is discussed later.

JAVA PROGRAMMING
Internal addition by the compiler
The Java compiler adds public and abstract keywords before the interface method. Moreover, it
adds public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the methods are public
and abstract.

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

Java Interface Example:

In this example, the Printable interface has only one method, and its implementation is provided
in the A6 class.

interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}

JAVA PROGRAMMING
public static void main(String args[])
{
A6 obj = new A6();
obj.print();
}
}

Output:

Hello

Java Interface Example: Drawable

In this example, the Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used by
someone else. The implementation part is hidden by the user who uses the interface.

File: TestInterface1.java

//Interface declaration: by first user


interface Drawable
{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable
{
public void draw()
{
System.out.println("drawing circle");
}
}
//Using interface: by third user
class TestInterface1
{
public static void main(String args[])
{

JAVA PROGRAMMING
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}
}

Output:

drawing circle

Java Interface Example: Bank

Let's see another example of java interface which provides the implementation of Bank interface.

File: TestInterface2.java

interface Bank
{
float rateOfInterest();
}
class SBI implements Bank
{
public float rateOfInterest()
{
return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest()
{
return 9.7f;
}
}
class TestInterface2
{
public static void main(String[] args)
{
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}

Output:

ROI: 9.15

JAVA PROGRAMMING
Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is 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();
}
}
Test it Now
Output:Hello
Welcome

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

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

interface Printable
{
void print();
}
interface Showable
{
void print();
}

class TestInterface3 implements Printable, Showable


{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
TestInterface3 obj = new TestInterface3();
obj.print();
}
}

Output:

Hello

Interface inheritance:

A class implements an interface, but one interface extends another interface.

interface Printable
{
void print();
}
interface Showable extends Printable
{

JAVA PROGRAMMING
void show();
}
class TestInterface4 implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

public static void main(String args[])


{
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}

Output:

Hello
Welcome

Difference between Abstract class and Interface

Abstract class Interface

It is collection of abstract method and concrete


1 It is collection of abstract method.
methods.

There properties can be reused commonly in a There properties commonly usable in any
2
specific application. application of java environment.

3 It does not support multiple inheritance. It support multiple inheritance.

4 Abstract class is preceded by abstract keyword. It is preceded by Interface keyword.

5 Which may contain either variable or constants. Which should contains only constants.

6 The default access specifier of abstract class There default access specifier of interface

JAVA PROGRAMMING
methods are default. method are public.

These class properties can be reused in other These properties can be reused in any other
7
class using extend keyword. class using implements keyword.

8 Inside abstract class we can take constructor. Inside interface we can not take any constructor.

For the abstract class there is no restriction like For the interface it should be compulsory to
9 initialization of variable at the time of variable initialization of variable at the time of variable
declaration. declaration.

There are no any restriction for abstract class For the interface variable can not declare
10
variable. variable as private, protected, transient, volatile.

There are no any restriction for abstract class For the interface method can not declare method
11 method modifier that means we can use any as strictfp, protected, static, native, private,
modifiers. final, synchronized.

JAVA PROGRAMMING
Malla Reddy University

UNIT - III

Packages : Defining, creating and accessing a package, importing packages.


Exception handling: Benefits of exception handling, the classification of exceptions - exception
hierarchy, checked exceptions and unchecked exceptions, usage of try, catch, throw, throws and
finally, creating own exception subclasses.

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.

1|P a ge
JAVA PROGRAMMING
Malla Reddy University

Simple example of java package

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

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }

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.

2|P a ge
JAVA PROGRAMMING
Malla Reddy University

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


1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
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


1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }

3|P a ge
JAVA PROGRAMMING
Malla Reddy University

1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
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


1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
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.

4|P a ge
JAVA PROGRAMMING
Malla Reddy University

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
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java

5|P a ge
JAVA PROGRAMMING
Malla Reddy University

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:

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }

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.

6|P a ge
JAVA PROGRAMMING
Malla Reddy University

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.

o Temporary
o By setting the classpath in the command prompt
o By -classpath switch
o 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:

7|P a ge
JAVA PROGRAMMING
Malla Reddy University

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?


Click Static Import feature of Java5.

What about package class?

Package class:

The package class provides methods to get information about the specification and
implementation of a package. It provides methods such as getName(), getImplementationTitle(),
getImplementationVendor(), getImplementationVersion() etc.

Example of Package class

In this example, we are printing the details of java.lang package by invoking the methods of
package class.

1. class PackageInfo{
2. public static void main(String args[]){
3.
4. Package p=Package.getPackage("java.lang");
5.
6. System.out.println("package name: "+p.getName());
7.
8. System.out.println("Specification Title: "+p.getSpecificationTitle());
9. System.out.println("Specification Vendor: "+p.getSpecificationVendor());
10. System.out.println("Specification Version: "+p.getSpecificationVersion());
11.
12. System.out.println("Implementaion Title: "+p.getImplementationTitle());
13. System.out.println("Implementation Vendor: "+p.getImplementationVendor());
14. System.out.println("Implementation Version: "+p.getImplementationVersion());

8|P a ge
JAVA PROGRAMMING
Malla Reddy University

15. System.out.println("Is sealed: "+p.isSealed());


16.
17.
18. }
19. }
Output:package name: java.lang
Specification Title: Java Plateform API Specification
Specification Vendor: Sun Microsystems, Inc.
Specification Version: 1.6
Implemenation Title: Java Runtime Environment
Implemenation Vendor: Sun Microsystems, Inc.
Implemenation Version: 1.6.0_30
IS sealed: false

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.

In this tutorial, we will learn about Java exceptions, it's types, and the difference between
checked and unchecked exceptions.

What is Exception in Java?

Dictionary Meaning: Exception is an abnormal condition.

In Java, an 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 ClassNotFoundException,


IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions. Let's consider a scenario:

1. statement 1;

9|P a ge
JAVA PROGRAMMING
Malla Reddy University

2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the
rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However,
when we perform exception handling, the rest of the statements will be executed. That is why we
use exception handling in Java.

Do You Know?

o What is the difference between checked and unchecked exceptions?


o What happens behind the code int data=50/0;?
o Why use multiple catch block?
o Is there any possibility when the finally block is not executed?
o What is exception propagation?
o What is the difference between the throw and throws keyword?
o What are the 4 rules for using exception handling with method overriding?

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:

10 | P a g e
JAVA PROGRAMMING
Malla Reddy University

Types of Java Exceptions:

There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:

1. Checked Exception
2. Unchecked Exception
3. Error

11 | P a g e
JAVA PROGRAMMING
Malla Reddy University

Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,


AssertionError etc.

Java Exception Keywords

Java provides five keywords that are used to handle the exception. The following table describes
each.

12 | P a g e
JAVA PROGRAMMING
Malla Reddy University

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by either
catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may occur
an exception in the method. It doesn't throw an exception. It is always used with
method signature.

Java Exception Handling Example

Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.

JavaExceptionExample.java

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }
Test it Now

Output:

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


rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch


block.

13 | P a g e
JAVA PROGRAMMING
Malla Reddy University

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

String s=null;
System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException. Suppose we have a string variable that has characters; converting this
variable into digit will cause NumberFormatException.

String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be
other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException

Java Exceptions Index

1. Java Try-Catch Block


2. Java Multiple Catch Block
3. Java Nested Try
4. Java Finally Block
5. Java Throw Keyword
6. Java Exception Propagation

14 | P a g e
JAVA PROGRAMMING
Malla Reddy University

7. Java Throws Keyword


8. Java Throw vs Throws
9. Java Final vs Finally vs Finalize
10. Java Exception Handling with Method Overriding
11. Java Custom Exceptions

1.Java try-catch block:

Java try block

Java try block is used to enclose the code that might throw an exception. It must be used within
the method.

If an exception occurs at the particular statement in the try block, the rest of the block code will
not execute. So, it is recommended not to keep the code in try block that will not throw an
exception.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}

Syntax of try-finally block


1. try{
2. //code that may throw an exception
3. }finally{}

Java catch block

Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.

The catch block must be used after the try block only. You can use multiple catch block with a
single try block.

Internal Working of Java try-catch block

15 | P a g e
JAVA PROGRAMMING
Malla Reddy University

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 the application programmer handles the exception, the normal flow of the application is
maintained, i.e., rest of the code is executed.

Problem without exception handling

Let's try to understand the problem if we don't use a try-catch block.

Example 1

TryCatchExample1.java

1. public class TryCatchExample1 {


2.
3. public static void main(String[] args) {
4.
5. int data=50/0; //may throw exception
6.

16 | P a g e
JAVA PROGRAMMING
Malla Reddy University

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


8.
9. }
10.
11. }

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

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

There might be 100 lines of code after the exception. If the exception is not handled, all the code
below the exception won't be executed.

Solution by exception handling

Let's see the solution of the above problem by a java try-catch block.

Example 2

TryCatchExample2.java

1. public class TryCatchExample2 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. //handling the exception
9. catch(ArithmeticException e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }

17 | P a g e
JAVA PROGRAMMING
Malla Reddy University
Output:

java.lang.ArithmeticException: / by zero
rest of the code

As displayed in the above example, the rest of the code is executed, i.e., the rest of the
code statement is printed.

2. Java Catch Multiple Exceptions

Java Multi-catch block

A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.

Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

Flowchart of Multi-catch Block

Example 1

Let's see a simple example of java multi-catch block.

MultipleCatchBlock1.java

18 | P a g e
JAVA PROGRAMMING
Malla Reddy University

1. public class MultipleCatchBlock1 {


2.
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.println("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. System.out.println("ArrayIndexOutOfBounds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. System.out.println("Parent Exception occurs");
20. }
21. System.out.println("rest of the code");
22. }
23. }

Output:

Arithmetic Exception occurs


rest of the code

3.Java Nested try block:

In Java, using a try block inside another try block is permitted. It is called as nested try block.
Every statement that we enter a statement in try block, context of that exception is pushed onto
the stack.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).

19 | P a g e
JAVA PROGRAMMING
Malla Reddy University

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:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....

20 | P a g e
JAVA PROGRAMMING
Malla Reddy University

Java Nested try Example

Example 1

Let's see an example where we place a try block within another try block for two different
exceptions.

NestedTryBlock.java

1. public class NestedTryBlock{


2. public static void main(String args[]){
3. //outer try block
4. try{
5. //inner try block 1
6. try{
7. System.out.println("going to divide by 0");
8. int b =39/0;
9. }
10. //catch block of inner try block 1
11. catch(ArithmeticException e)
12. {
13. System.out.println(e);
14. }
15.
16.
17. //inner try block 2
18. try{
19. int a[]=new int[5];
20.
21. //assigning the value out of array bounds
22. a[5]=4;
23. }
24.
25. //catch block of inner try block 2
26. catch(ArrayIndexOutOfBoundsException e)
27. {
28. System.out.println(e);
29. }
30.
31.
32. System.out.println("other statement");
33. }

21 | P a g e
JAVA PROGRAMMING
Malla Reddy University

34. //catch block of outer try block


35. catch(Exception e)
36. {
37. System.out.println("handled the exception (outer catch)");
38. }
39.
40. System.out.println("normal flow..");
41. }
42. }

Output:

When any try block does not have a catch block for a particular exception, then the catch block
of the outer (parent) try block are checked for that exception, and if it matches, the catch block of
outer try block is executed.

If none of the catch block specified in the code is unable to handle the exception, then the Java
runtime system will handle the exception. Then it displays the system generated message for that
exception.

Java finally block

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

Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception occurs or
not.

The finally block follows the try-catch block.

22 | P a g e
JAVA PROGRAMMING
Malla Reddy University

Flowchart of finally block

Note: If you don't handle the exception, before terminating the program, JVM executes finally
block (if any).

Why use Java finally block?


o finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
o The important statements to be printed can be placed in the finally block.

Usage of Java finally

Let's see the different cases where Java finally block can be used.

Case 1: When an exception does not occur

Let's see the below example where the Java program does not throw any exception, and the
finally block is executed after the try block.

TestFinallyBlock.java

23 | P a g e
JAVA PROGRAMMING
Malla Reddy University

1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. System.out.println(data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. System.out.println(e);
11. }
12. //executed regardless of exception occurred or not
13. finally {
14. System.out.println("finally block is always executed");
15. }
16.
17. System.out.println("rest of phe code...");
18. }
19. }

Output:

Case 2: When an exception occurr but not handled by the catch block

Let's see the the fillowing example. Here, the code throws an exception however the catch block
cannot handle it. Despite this, the finally block is executed after the try block and then the
program terminates abnormally.

TestFinallyBlock1.java

1. public class TestFinallyBlock1{


2. public static void main(String args[]){
3.
4. try {
5.
6. System.out.println("Inside the try block");

24 | P a g e
JAVA PROGRAMMING
Malla Reddy University

7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. System.out.println(data);
11. }
12. //cannot handle Arithmetic type exception
13. //can only accept Null Pointer type exception
14. catch(NullPointerException e){
15. System.out.println(e);
16. }
17.
18. //executes regardless of exception occured or not
19. finally {
20. System.out.println("finally block is always executed");
21. }
22.
23. System.out.println("rest of the code...");
24. }
25. }

Output:

Case 3: When an exception occurs and is handled by the catch block

Example:

Let's see the following example where the Java code throws an exception and the catch block
handles the exception. Later the finally block is executed after the try-catch block. Further, the
rest of the code is also executed normally.

TestFinallyBlock2.java

1. public class TestFinallyBlock2{


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

25 | P a g e
JAVA PROGRAMMING
Malla Reddy University

4. try {
5.
6. System.out.println("Inside try block");
7.
8. //below code throws divide by zero exception
9. int data=25/0;
10. System.out.println(data);
11. }
12.
13. //handles the Arithmetic Exception / Divide by zero exception
14. catch(ArithmeticException e){
15. System.out.println("Exception handled");
16. System.out.println(e);
17. }
18.
19. //executes regardless of exception occured or not
20. finally {
21. System.out.println("finally block is always executed");
22. }
23.
24. System.out.println("rest of the code...");
25. }
26. }

Output:

Rule: For each try block there can be zero or more catch blocks, but only one finally block.

Note: The finally block will not be executed if the program exits (either by calling System.exit()
or by causing a fatal error that causes the process to abort).

Java throw Exception

26 | P a g e
JAVA PROGRAMMING
Malla Reddy University
In Java, exceptions allows us to write good quality codes where the errors are checked at the
compile time instead of runtime and we can create custom exceptions making the code recovery
and debugging easier.

Java throw keyword

The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has some message with it
that provides the error description. These exceptions may be related to user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly
used to throw a custom exception. We will discuss custom exceptions later in this section.

We can also define our own set of conditions and throw an exception explicitly using throw
keyword. For example, we can throw ArithmeticException if we divide a number by another
number. Here, we just need to set the condition and throw exception using throw keyword.

The syntax of the Java throw keyword is given below.

throw Instance i.e.,

1. throw new exception_class("error message");

Let's see the example of throw IOException.

1. throw new IOException("sorry device error");

Where the Instance must be of type Throwable or subclass of Throwable. For example,
Exception is the sub class of Throwable and the user-defined exceptions usually extend the
Exception class.

Java throw keyword Example

Example 1: Throwing Unchecked Exception

In this example, we have created a method named validate() that accepts an integer as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a
message welcome to vote.

TestThrow1.java

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.

27 | P a g e
JAVA PROGRAMMING
Malla Reddy University

1. public class TestThrow1 {


2. //function to check if person is eligible to vote or not
3. public static void validate(int age) {
4. if(age<18) {
5. //throw Arithmetic exception if not eligible to vote
6. throw new ArithmeticException("Person is not eligible to vote");
7. }
8. else {
9. System.out.println("Person is eligible to vote!!");
10. }
11. }
12. //main method
13. public static void main(String args[]){
14. //calling the function
15. validate(13);
16. System.out.println("rest of the code...");
17. }
18. }

Output:

The above code throw an unchecked exception. Similarly, we can also throw unchecked and user
defined exceptions.

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.

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

Exception Propagation Example

TestExceptionPropagation1.java

28 | P a g e
JAVA PROGRAMMING
Malla Reddy University

1. class TestExceptionPropagation1{
2. void m(){
3. int data=50/0;
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation1 obj=new TestExceptionPropagation1();
15. obj.p();
16. System.out.println("normal flow...");
17. }
18. }
Test it Now

Output:

exception handled
normal flow...

In the above example exception occurs in the m() method where it is not handled, so it is
propagated to the previous n() method where it is not handled, again it is propagated to the p()
method where exception is handled.

Exception can be handled in any method in call stack either in the main() method, p() method,
n() method or m() method.

29 | P a g e
JAVA PROGRAMMING
Malla Reddy University

Note: By default, Checked Exceptions are not forwarded in calling chain (propagated).

Exception Propagation Example

TestExceptionPropagation1.java

1. class TestExceptionPropagation2{
2. void m(){
3. throw new java.io.IOException("device error");//checked exception
4. }
5. void n(){
6. m();
7. }
8. void p(){
9. try{
10. n();
11. }catch(Exception e){System.out.println("exception handeled");}
12. }
13. public static void main(String args[]){
14. TestExceptionPropagation2 obj=new TestExceptionPropagation2();
15. obj.p();
16. System.out.println("normal flow");
17. }
18. }

Output:

Compile Time Error

30 | P a g e
JAVA PROGRAMMING
Malla Reddy University

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 the normal flow of the program 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
checking the code before it being used.

Syntax of Java throws


1. return_type method_name() throws exception_class_name{
2. //method code
3. }

Which exception should be declared?

Ans: Checked exception only, because:

o unchecked exception: under our control so we can correct our code.


o error: beyond our control. For example, we 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.

Testthrows1.java

1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }

31 | P a g e
JAVA PROGRAMMING
Malla Reddy University

9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }

Output:

exception handled
normal flow...
Rule: If we are calling a method that declares an exception, we must either caught or declare the
exception.

There are two cases:

1. Case 1: We have caught the exception i.e. we have handled the exception using try/catch
block.
2. Case 2: We have declared the exception i.e. specified throws keyword with the method.

Case 1: Handle Exception Using try-catch block

In case we handle the exception, the code will be executed fine whether exception occurs during
the program or not.

Testthrows2.java

1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();

32 | P a g e
JAVA PROGRAMMING
Malla Reddy University

11. m.method();
12. }catch(Exception e){System.out.println("exception handled");}
13.
14. System.out.println("normal flow...");
15. }
16. }

Output:

exception handled
normal flow...

Case 2: Declare Exception


o In case we declare the exception, if exception does not occur, the code will be executed
fine.
o In case we declare the exception and the exception occurs, it will be thrown at runtime
because throws does not handle the exception.

Let's see examples for both the scenario.

A) If exception does not occur

Testthrows3.java

1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Test it Now

Output:

device operation performed


33 | P a g e
JAVA PROGRAMMING
Malla Reddy University
normal flow...

B) If exception occurs

Testthrows4.java

1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. class Testthrows4{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Test it Now

Output:

Difference between throw and throws in Java

The throw and throws is the concept of exception handling where the throw keyword throw the
exception explicitly from a method or a block of code whereas the throws keyword is used in
signature of the method.

There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:

Sr. Basis of Differences throw throws


no.

1. Definition Java throw keyword is Java throws keyword is used

34 | P a g e
JAVA PROGRAMMING
Malla Reddy University

used throw an exception in the method signature to


explicitly in the code, declare an exception which
inside the function or the might be thrown by the
block of code. function while the execution
of the code.

2. Type of exception Using Using throws keyword, we


throw keyword, we can only can declare both checked
propagate unchecked and unchecked exceptions.
exception i.e., the checked However, the throws
exception cannot be keyword can be used to
propagated using throw only. propagate checked
exceptions only.

3. Syntax The throw keyword is The throws keyword is


followed by an instance of followed by class names of
Exception to be thrown. Exceptions to be thrown.

4. Declaration throw is used within the throws is used with the


method. method signature.

5. Internal implementation We are allowed to throw We can declare multiple


only one exception at a exceptions using throws
time i.e. we cannot throw keyword that can be thrown
multiple exceptions. by the method. For example,
main() throws IOException,
SQLException.

Java throw Example

TestThrow.java

1. public class TestThrow {


2. //defining a method
3. public static void checkNum(int num) {
4. if (num < 1) {
5. throw new ArithmeticException("\nNumber is negative, cannot calculate square");
6. }
7. else {
8. System.out.println("Square of " + num + " is " + (num*num));
9. }
10. }
11. //main method
12. public static void main(String[] args) {
13. TestThrow obj = new TestThrow();

35 | P a g e
JAVA PROGRAMMING
Malla Reddy University

14. obj.checkNum(-3);
15. System.out.println("Rest of the code..");
16. }
17. }

Output:

Java throws Example

TestThrows.java

1. public class TestThrows {


2. //defining a method
3. public static int divideNum(int m, int n) throws ArithmeticException {
4. int div = m / n;
5. return div;
6. }
7. //main method
8. public static void main(String[] args) {
9. TestThrows obj = new TestThrows();
10. try {
11. System.out.println(obj.divideNum(45, 0));
12. }
13. catch (ArithmeticException e){
14. System.out.println("\nNumber cannot be divided by 0");
15. }
16.
17. System.out.println("Rest of the code..");
18. }
19. }

Output:

36 | P a g e
JAVA PROGRAMMING
Malla Reddy University

Java throw and throws Example

TestThrowAndThrows.java

1. public class TestThrowAndThrows


2. {
3. // defining a user-defined method
4. // which throws ArithmeticException
5. static void method() throws ArithmeticException
6. {
7. System.out.println("Inside the method()");
8. throw new ArithmeticException("throwing ArithmeticException");
9. }
10. //main method
11. public static void main(String args[])
12. {
13. try
14. {
15. method();
16. }
17. catch(ArithmeticException e)
18. {
19. System.out.println("caught in main() method");
20. }
21. }
22. }

Output:

37 | P a g e
JAVA PROGRAMMING
Malla Reddy University

Difference between final, finally and finalize:

The final, finally, and finalize are keywords in Java that are used in exception handling. Each of
these keywords has a different functionality. The basic difference between final, finally and
finalize is that the final is an access modifier, finally is the block in Exception Handling
and finalize is the method of object class.

Along with this, there are many differences between final, finally and finalize. A list of
differences between final, finally and finalize are given below:

Sr. Key final finally finalize


no.

1. Definition final is the keyword finally is the block in finalize is the method in
and access modifier Java Exception Java which is used to
which is used to apply Handling to execute the perform clean up
restrictions on a class, important code whether processing just before
method or variable. the exception occurs or object is garbage
not. collected.

2. Applicable Final keyword is used Finally block is always finalize() method is used
to with the classes, related to the try and with the objects.
methods and variables. catch block in
exception handling.

3. Functionality (1) Once declared, final (1) finally block runs finalize method performs
variable becomes the important code even the cleaning activities
constant and cannot be if exception occurs or with respect to the object
modified. not. before its destruction.
(2) final method cannot (2) finally block cleans
be overridden by sub up all the resources
class. used in try block
(3) final class cannot
be inherited.

4. Execution Final method is Finally block is finalize method is


executed only when we executed as soon as the executed just before the
call it. try-catch block is object is destroyed.
executed.

It's execution is not


dependant on the
exception.

38 | P a g e
JAVA PROGRAMMING
Malla Reddy University

Java final Example

Let's consider the following example where we declare final variable age. Once declared it
cannot be modified.

FinalExampleTest.java

1. public class FinalExampleTest {


2. //declaring final variable
3. final int age = 18;
4. void display() {
5.
6. // reassigning value to age variable
7. // gives compile time error
8. age = 55;
9. }
10.
11. public static void main(String[] args) {
12.
13. FinalExampleTest obj = new FinalExampleTest();
14. // gives compile time error
15. obj.display();
16. }
17. }

Output:

In the above example, we have declared a variable final. Similarly, we can declare the methods
and classes final using the final keyword.

Java finally Example

Let's see the below example where the Java code throws an exception and the catch block
handles that exception. Later the finally block is executed after the try-catch block. Further, the
rest of the code is also executed normally.

FinallyExample.java

39 | P a g e
JAVA PROGRAMMING
Malla Reddy University

1. public class FinallyExample {


2. public static void main(String args[]){
3. try {
4. System.out.println("Inside try block");
5. // below code throws divide by zero exception
6. int data=25/0;
7. System.out.println(data);
8. }
9. // handles the Arithmetic Exception / Divide by zero exception
10. catch (ArithmeticException e){
11. System.out.println("Exception handled");
12. System.out.println(e);
13. }
14. // executes regardless of exception occurred or not
15. finally {
16. System.out.println("finally block is always executed");
17. }
18. System.out.println("rest of the code...");
19. }
20. }

Output:

Java finalize Example

FinalizeExample.java

1. public class FinalizeExample {


2. public static void main(String[] args)
3. {
4. FinalizeExample obj = new FinalizeExample();
5. // printing the hashcode
6. System.out.println("Hashcode is: " + obj.hashCode());
7. obj = null;
8. // calling the garbage collector using gc()

40 | P a g e
JAVA PROGRAMMING
Malla Reddy University

9. System.gc();
10. System.out.println("End of the garbage collection");
11. }
12. // defining the finalize method
13. protected void finalize()
14. {
15. System.out.println("Called the finalize() method");
16. }
17. }

Output:

41 | P a g e
JAVA PROGRAMMING
UNIT–IV
Multithreading:
Differences between multiple processes and multiple threads, thread life cycle, creating
threads, interrupting threads, thread priorities, synchronizing threads, inter- thread
communication, producer consumer problem.
Applets:
Concepts of Applets, differences between applets and applications, life cycle of an applet,
types of applets, creating applets, passing parameters to applets.

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.

Differences between multiple processes and multiple threads:


Advantage of Multiprocessing:

 The biggest advantage of a multiprocessor system is that it helps you to get more
work done in a shorter period.
 The code is usually straight forward.
 Takes advantage of multiple CPU & cores
 Remove synchronization primitives unless if you use shared memory.
 Child processes are mostly interruptible/killable
 It helps you to get work done in a shorter period.
 These types of systems should be used when very high speed is required to process a
large volume of data.
 Multiprocessing systems save money compared to single processor systems as
processors can share peripherals and power supplies.

Advantage of Multithreading:

 Threads share the same address space.


 Threads are lightweight which has a low memory footprint.
 The cost of communication between threads is low.
 Access to memory state from another context is easier
 Threads are faster to start than processes and also faster in task-switching.
 All Threads share a process memory pool that is very beneficial.
 Takes lesser time to create a new thread in the existing process than a new process

THREAD LIFE CYCLE:

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
New State:

 A thread enters the newly created by using a new operator.


 It is new state or born state immediately after creation. i.e. when a
constructor is called the Thread is created but is not yet to run()
method will not begin until it start() method is called.
 After the start() method is called, the thread will go to the next state, Runnable state.
Runnable State:

 Once we invoke the start() method, the thread is runnable.


 It is divided into two states:
A. The running state:
When the thread is running state, it assigned by CPU cycles
and isactually running.

B. The Queued state:


 When the thread is in Queued state, it is waiting in
the Queue and competing for its turn to spend CPU cycles
 When we use yield() method it makes sure other threads of the same
priority have chance to run.
 This method cause voluntary move itself to the queued state from the
running state.
Blocked State:
The blocked state is entered when one of the following events occurs:
 The thread itself or another thread calls the suspend() method (it is deprecated)
 The thread calls an object’s wait() method.
 The thread itself calls the sleep() method.
 The thread is waiting for some I/O operations to complete.
 The thread will join() another thread.

Dead State:
A thread is dead for any one of the following reasons:
 It dies a natural death because the run method exists normally.
 It dies abruptly because an uncaught exception terminates the run method.
 In particular stop() is used to kill the thread. This is depricated.
 To find whether thread is alive i.e. currently running or blocked
Use isAlive() method
 If it returns true the thread is alive.

CREATING THREADS:

There are two ways to create a thread:


1. By extending Thread class
2. By implementing Runnable interface.

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


 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.

2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.

3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.

4. public void join(): waits for a thread to die.

5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.

6. public int getPriority(): returns the priority of the thread.

7. public int setPriority(int priority): changes the priority of the thread.

8. public String getName(): returns the name of the thread.


9. public void setName(String name): changes the name of the thread.

10. public Thread currentThread(): returns the reference of currently executing thread.

11. public int getId(): returns the id of the thread.

12. public Thread.State getState(): returns the state of the thread.

13. public boolean isAlive(): tests if the thread is alive.

14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.

15. public void suspend(): is used to suspend the thread(depricated).

16. public void resume(): is used to resume the suspended thread(depricated).

17. public void stop(): is used to stop the thread(depricated).

18. public boolean isDaemon(): tests if the thread is a daemon thread.

19. public void setDaemon(boolean b): marks the thread as daemon or user thread.

20. public void interrupt(): interrupts the thread.

21. public boolean isInterrupted(): tests if the thread has been interrupted.

22. public static boolean interrupted(): tests if the current thread has been interrupted.

2. 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().

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:

 A new thread starts(with new callstack).


 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method will run.
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...

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

INTERRUPTING THREADS:

If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling
the interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException. If the thread is not in the sleeping or waiting state, calling the
interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the
interrupt flag to true. Let's first see the methods provided by the Thread class for thread
interruption.

The 3 Methods Provided By The Thread Class For Interrupting A Thread:


public void interrupt()
public static boolean interrupted()
public boolean isInterrupted()
Example of interrupting a thread that stops working:
In this example, after interrupting the thread, we are propagating it, so it will stop
working. If we don't want to stop the thread, we can handle it where sleep() or wait() method
is invoked. Let's first see the example where we are propagating the exception.

class TestInterruptingThread1 extends Thread{


public void run(){
try{
Thread.sleep(1000);
System.out.println("task");
}catch(InterruptedException e){
throw new RuntimeException("Thread
interrupted..."+e);
}}
public static void main(String args[]){
TestInterruptingThread1 t1=new TestInterruptingThread1();
t1.start();
try{
t1.interrupt();
}catch(Exception e){System.out.println("Exception handled "+e);}
}}
Output:
Exception in thread-0
java.lang.RuntimeException: Thread interrupted...
java.lang.InterruptedExce tion: sleep interrupted at A.run(A.java:7)

Example of interrupting a thread that doesn't stop working:


In this example, after interrupting the thread, we handle the exception, so it will break
out the sleeping but will not stop working.

class TestInterruptingThread2 extends Thread{


public void run(){
try{
Thread.sleep(1000);
System.out.println("task");
}catch(InterruptedException e){
System.out.println("Exception handled "+e);}
System.out.println("thread is running...");
public static void main(String args[]){
TestInterruptingThread2 t1=new TestInterruptingThread2();
t1.start();
t1.interrupt();
}}

Output: Exception handled

java.lang.InterruptedException: sleep interrupted thread is running...


Example of interrupting thread that behaves normally:

If thread is not in sleeping or waiting state, calling the interrupt() method sets the
interrupted flag to truethat can be used to stop the thread by the java programmer later.

class TestInterruptingThread3 extends Thread{


public void run(){
for(int i=1;i<=5;i++)
System.out.println(i); }
public static void main(String args[]){
TestInterruptingThread3 t1=new TestInterruptingThread3();
t1.start();
t1.interrupt();
}
}

Output:
1
2
3
4
5
What About Isinterrupted And Interrupted Method?
The isInterrupted() method returns the interrupted flag either true or false. The static
interrupted() method returns the interrupted flag afterthat it sets the flag to false if it is true.

public class TestInterruptingThread4 extends Thread{


public void run(){
for(int i=1;i<=2;i++){
if(Thread.interrupted()){
System.out.println("code for interrupted thread"); }
else{
System.out.println("code for normal thread");
} 11.
}//end of for loop
}
public static void main(String args[]){
TestInterruptingThread4 t1=new TestInterruptingThread4();
TestInterruptingThread4 t2=new TestInterruptingThread4();
t1.start();
t1.interrupt();
t2.start();
}
}
Output: Code for interrupted thread code for normal thread
code for normal thread code for normal thread
THREAD PRIORITIES:

Each thread has a priority. Priorities are represented by a number between 1 and 10.
In most cases, thread scheduler 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 defined 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

SYNCHRONIZING THREADS:

When two or more threads need access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by which this
is achieved is called synchronization. As you will see, Java provides unique, language-level
support for it. Key to synchronization is the concept of the monitor (also called a semaphore).

A monitor is an object that is used as a mutually exclusive lock, or mutex. Only one
thread can own a monitor at a given time. When a thread acquires a lock, it is said to have
entered the monitor. All other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor. These other threads are said to be waiting
for the monitor. A thread that owns a monitor can reenter the same monitor if it so desires.

You can synchronize your code in either of two ways. Both involve the use of the
synchronized keyword, and both are examined here.

This is the general form of the synchronized statement:


synchronized(object) {

// statements to be synchronized
}
Here, object is a reference to the object being synchronized. A synchronized block ensures
that a call to a method that is a member of object occurs only after the current thread has
successfully entered object’s monitor.
Here is an alternative version of the preceding example, using a synchronized block within
the run( ) method:

// This program uses a synchronized block.


class Callme {
void call(String msg) {System.out.print("[" + msg);
try { Thread.sleep(1000);
}
catch (InterruptedException e) {System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable
{
String msg;
Callme target;Thread t;
public Caller(Callme targ, String s)
{ target = targ;msg = s;
t = new Thread(this);t.start();
}
// synchronize calls to call() public void run() {
synchronized(target)
{ // synchronizedblock target.call(msg);
}}}
class Synch1 {
public static void main(String args[])
{
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads toend
try { ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{ System.out.println("Interrupted");
}
}
}

Here, the call( ) method is not modified by synchronized. Instead, the synchronized
statement is used inside Caller’s run( ) method. This causes the same correct output as the
preceding example, because each thread waits for the prior one to finish before proceeding.

Daemon Threads:

A ―daemon‖ thread is one that is supposed to as the program is running, but is not
part of the essence of the program. Thus when all of the non-daemon threads complete, the
program is terminated. you can find out if a thread is a daemon

by calling isDaemon(), and you can turn the setDaemon().if a thread is a daemon, then
any threads it createswill automatically be daemons.

INTER- THREAD COMMUNICATION:

Inter-thread communication or Co-operation is all about allowing synchronized


threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused


running in its critical section and another thread is allowed to enter (or lock) in the same
critical section tobe executed.

It is implemented by following methods of Object class:


 wait()
 notify()
 notifyAll()
1. wait() method:
Causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.
public final void wait()throws InterruptedException: waits until object is notified.
public final void wait(long timeout)throws InterruptedException: waits for the
specified amount of time.

2. notify() method:

Wakes up a single thread that is waiting on this object's monitor. If any threads
are waiting on this object, one of them is chosen to be awakened. The choice is
arbitrary and occurs at the discretion of the implementation.
Syntax: public final void notify()

3. notifyAll() method:

Wakes up all threads that are waiting on this object's monitor.


Syntax: public final void notifyAll()

Understanding the process of inter-thread communication:

The point to point explanation of the above diagram is as follows:

1. Threads enter to acquire lock.


2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the
notified state (runnablestate).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and
exits the monitor state of theobject.
Example of inter thread communication in java:

class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}start();
new Thread(){
public void run(){c.deposit(10000);}
}start();
}}

Output: going to withdraw...


Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

PRODUCER CONSUMER PROBLEM:

The producer-consumer problem (also known as the bounded-buffer problem) is a classic


example of a multi-process synchronization problem. The problem describes two processes,
the producer and the consumer, which share a common, fixed-size buffer used as a queue.

 The producer’s job is to generate data, put it into the buffer, and start again.
 At the same time, the consumer is consuming the data (i.e. removing it from the
buffer), one piece at a time.
Problem
To make sure that the producer won’t try to add data into the buffer if it’s full and that the
consumer won’t try to remove data from an empty buffer.

Solution
The producer is to either go to sleep or discard data if the buffer is full. The next time the
consumer removes an item from the buffer, it notifies the producer, who starts to fill the
buffer again. In the same way, the consumer can go to sleep if it finds the buffer to be empty.
The next time the producer puts data into the buffer, it wakes up the sleeping consumer.

Implementation of Producer Consumer Class:

 A LinkedList list – to store list of jobs in queue.


 A Variable Capacity – to check for if the list is full or not
 A mechanism to control the insertion and extraction from this list so that we do not
insert into list if it is full or remove from it if it is empty.

// Java program to implement solution of producer


// consumer problem.

import java.util.LinkedList;

public class Threadexample


{
public static void main(String[] args) throws InterruptedException
{
// Object of a class that has both produce()
// and consume() methods final PC pc = new PC();
// Create producer thread
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try {
pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});

// Create consumer thread


Thread t2 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.consume();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});

// Start both threads


t1.start();
t2.start();

// t1 finishes before t2
t1.join();
t2.join();
}

// This class has a list, producer (adds items to list and consumer (removes items).
public static class PC {

// Create a list shared by producer and consumer AND Size of list is 2.


LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;

// Function called by producer thread


public void produce() throws InterruptedException
{
int value = 0;
while (true) {
synchronized (this)
{
// producer thread waits while list is full
while (list.size() == capacity)
wait();

System.out.println("Producer produced-" + value);

// to insert the jobs in the list


list.add(value++);

// notifies the consumer thread that now it can start consuming


notify();

// makes the working of program easier to understand


Thread.sleep(1000);
}
}
}

// Function called by consumer thread


public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
// consumer thread waits while list is empty
while (list.size() == 0)
wait();

// to retrieve the first job in the list


int val = list.removeFirst();

System.out.println("Consumer consumed-" + val);

// Wake up producer thread


notify();

// and sleep
Thread.sleep(1000);
}
}

}}

CONCEPTS OF APPLETS:

Java programs are classified into two ways:

1. Applications program:
 Application programs are those programs which are normally created, compiled
and executed as similar to the other languages.
 Each application program contains one main( ) method.
 Programs are created in a local computer.
 Programs are compiled with javac compiler and executed in java interpreter.
2. Applet program:
 An applet is a special program that we can embedded in a web page such that the
applet gains control over a certain part of the displayed page.
 It is differ from application program.
 Applets are created from classes.
 An applet do not have main as an entry. Instead have several methods to control
specific aspects of applet execution.

DIFFERENCES BETWEEN APPLETS AND APPLICATIONS:


LIFE CYCLE OF AN APPLET:

Life cycle of an applet:

When an applet begins, the following methods are called, in this sequence:

1. init( )
2. start( )
3. paint( )

When an applet is terminated, the following sequence of method calls takes place:

1. stop( )
2. destroy( )

1. init( ) : The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your applet.

2. start( ) : The start( ) method is called after init( ). It is also called to restart an applet after
it has been stopped. Note that init( ) is called once i.e. when the first time an applet is loaded
whereas start( ) is called each time an applet’s HTML document is displayed onscreen. So, if
a user leaves a web page and comes back, the applet resumes execution at start( ).

3. paint( ) : The paint( ) method is called each time an AWT-based applet’s output must be
redrawn. This situation can occur for several reasons. For example, the window in which the
applet is running may be overwritten by another window and then uncovered. Or the applet
window may be minimized and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause, whenever the
applet must redraw its output, paint( ) is called.
4. stop( ) : The stop( ) method is called when a web browser leaves the HTML document
containing the applet—when it goes to another page, for example. When stop( ) is called, the
applet is probably running. You should use stop( ) to suspend threads that don’t need to run
when the applet is not visible. You can restart them when start( ) is called if the user returns
to the page.

5. destroy( ) : The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory. At this point, you should free up any
resources the applet may be using. The stop( ) method is always called before destroy( ).

Step 1: Initialization

public void init()

There is no main method unlike our normal java programs. Every Applet will start it’s
execution from init() method. It is executed only once

Step 2: Start

public void start()

After init() method start() method is invoked. Executed when the browser is maximized

Step 3: Paint

public void paint (Graphics g)

Paint method is used to display the content on the applet. We can create the objects or
components to the applet or we can directly write a message on the applet. It will take
Graphics class as a parameter.

Step 4: Stop

public void stop()

stop() method is used to stop the applet. It is executed when the browser is minimized.

Step 5: Destroy

public void destroy()

destroy() method is used to completely close the applet. It is executed when the applet is
closed.
TYPES OF APPLETS:

A special type of Java program that runs in a Web browser is referred to as Applet. It
has less response time because it works on the client-side. It is much secured executed by the
browser under any of the platforms such as Windows, Linux and Mac OS etc. There are two
types of applets that a web page can contain.

1. Local Applet
2. Remote Applet

1. Local Applet:

Local Applet is written on our own, and then we will embed it into web pages. Local
Applet is developed locally and stored in the local system. A web page doesn't need the get
the information from the internet when it finds the local Applet in the system. It is specified
or defined by the file name or pathname.

There are two attributes used in defining an applet, i.e., the codebase that specifies the
path name and code that defined the name of the file that contains Applet's code.

Specifying Local applet:

1. <applet
2. codebase = "tictactoe"
3. code = "FaceApplet.class"
4. width = 120
5. height = 120>
6. </applet>

Let's take an example of Local applet to understand how we can create it and embedded it
into web page.

1. First, we will create a Local Applet for embedding in a web page.


2. After that, we will add that Local Applet to the web page.

FaceApplet.java

1. //Import packages and classes


2. import java.applet.*;
3. import java.awt.*;
4. import java.util.*;
5. import java.awt.event.*;
6. //Creating FaceApplet class that extends Applet
7. public class FaceApplet extends Applet
8. {
9. //paint() method starts
10. public void paint(Graphics g){
11. //Creating graphical object
12. g.setColor(Color.red);
13. g.drawString("Welcome", 50, 50);
14. g.drawLine(20, 30, 20, 300);
15. g.drawRect(70, 100, 30, 30);
16. g.fillRect(170, 100, 30, 30);
17. g.drawOval(70, 200, 30, 30);
18. g.setColor(Color.pink);
19. g.fillOval(170, 200, 30, 30);
20. g.drawArc(90, 150, 30, 30, 30, 270);
21. g.fillArc(270, 150, 30, 30, 0, 180);
22. } }

Execute the above code by using the following commands:

Javac FaceApplet.java

Appletviewer run.html

2. Remote Applet:
A remote applet is designed and developed by another developer. It is located or available
on a remote computer that is connected to the internet. In order to run the applet stored in the
remote computer, our system is connected to the internet then we can download run it. In
order to locate and load a remote applet, we must know the applet's address on the web that is
referred to as Uniform Recourse Locator(URL).

Specifying Remote applet:

1. <applet
2. codebase = "http://www.myconnect.com/applets/"
3. code = "FaceApplet.class"
4. width = 120
5. height =120>
6. </applet>
Difference Between Local Applet and Remote Applet:

Local Applet Remote Applet


There is no need to define the Applet’s URL We need to define the Applet’s URL in
in local Applet. Remote Applet
Local Applet is available on our computer. Remote Applet is not available on our
computer.
In order to use it or access it, we don’t need In order to use it or access it, we need an
internet connection. internet connection.

It is written on our own and then embedded It was written by another developer.
into the web pages.
We don’t need to download it. It is available on a remote computer, so we
need to download it to our system.

CREATING APPLETS:

An applet is a Java program that can be embedded into a web page. It runs inside the
web browser and works at client side. An applet is embedded in an HTML page using the
APPLET or OBJECT tag and hosted on a web server.
Applets are used to make the website more dynamic and entertaining.

Important points :

1. All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.


2. Applets are not stand-alone programs. Instead, they run within either a web browser
or an applet viewer. JDK provides a standard applet viewer tool called applet viewer.
3. In general, execution of an applet does not begin at main() method.
4. Output of an applet window is not performed by System.out.println(). Rather it is
handled with various AWT methods, such as drawString().

Creating Hello World applet :

// A Hello World Applet


// Save file as HelloWorld.java

import java.applet.Applet;
import java.awt.Graphics;

// HelloWorld class extends Applet


public class HelloWorld extends Applet
{
// Overriding paint() method
@Override
public void paint(Graphics g)
{
g.drawString("Hello World", 20, 20);
}

There are two standard ways in which you can run an applet :

1. Executing the applet within a Java-compatible web browser.


2. Using an applet viewer, such as the standard tool, applet-viewer. An applet viewer
executes your applet in a window. This is generally the fastest and easiest way to test
your applet.

1. Using java enabled web browser : To execute an applet in a web browser we have to
write a short HTML text file that contains a tag that loads the applet. We can use APPLET or
OBJECT tag for this purpose. Using APPLET, here is the HTML file that executes
HelloWorld :

<applet code="HelloWorld" width=200 height=60>


</applet>
2.Using appletviewer : This is the easiest way to run an applet. To execute HelloWorld with
an applet viewer, you may also execute the HTML file shown earlier.

For example, if the preceding HTML file is saved with


RunHelloWorld.html, then the following command line will run HelloWorld :

appletviewer RunHelloWorld.html

PASSING PARAMETERS TO APPLETS:

The <param> tag is a sub tag of the <applet> tag. The <param> tag contains two
attributes: name and value which are used to specify the name of the parameter and the value
of the parameter respectively. For example, the param tags for passing name and age
parameters looks as shown below:

<param name=”name” value=”Ramesh” />


<param name=”age” value=”25″ />
Now, these two parameters can be accessed in the applet program using the getParameter()
method of the Applet class.

getParameter() Method:
The getParameter() method of the Applet class can be used to retrieve the parameters
passed from the HTML page.

Syntax: String getParameter(String param-name)

Example:

import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
UNIT-V
Java Servlets and Java Swing and Abstract Windowing Toolkit
5.1 Java Servlets
5.1.1 Introduction:
 Using Java there exists a way to generate dynamic web pages and that way is Java Servlet.
 We can define a Java Servlet as the technology to design and deploy dynamic web pages
using the Java Programming Language. It implements a typical servlet in the client-server
architecture, and the Servlet lives on the server-side.
 Using Servlets, you can collect input from users through web page forms, present records
from a database or another source, and create web pages dynamically.

Definition of Servlet:
Servlets are the Java programs that run on the Java-enabled web server or application server.
They are used to handle the request obtained from the webserver, process the request, produce
the response, and then send a response back to the webserver.

Diagrammatical Representation how servlet works:

Web server:
 A web server is used to transfer data in the form of the HTTP protocol.
 The client just has to type the URL in a browser and the web server provides her/him the
required web page to read.
 The web server converts the client typed URL into the HTTP protocol in order to respond to
the request and with the help of Servlets, it serves the client’s request.

Web container:
 Web container is also known as servlet container or servlet engine.
 The servlet container is a component of the server that interacts with the servlets.
 It is responsible for mapping the URL of the particular servlet and managing the lifecycle of
the servlet.
 Web Container contains "Servlet", a java file which can take the request from client on the
internet, process it and respond with a response.
 Web Container, e.g. Tomcat, JBoss, Websphere, etc.
 Web Container also contains “Deployment Descriptor”, a simple XML document that is used
to map URL to the servlet.

Properties of Servlets:

 Servlets work on the server-side.


 Servlets are capable of handling complex requests obtained from the webserver.
 Servlets extends the capabilities of a server as they can respond to many types of requests, they
act like web containers for hosting web applications on web servers. They support nearly all the
client–server protocols, but is often used with HTTP and also known as HTTP servlet.

Features of Java Servlet:

The key features offered by the Java Servlets are as follows.


 Portable
 Efficient
 Scalable
 Robust

Portable: The servlets feature the same Portable nature as the Java Programming Language. The
Servlet program designed in one Operating System's Platform can be run in a different Operating
System Platform with ease.

Efficient: Once a servlet is deployed and loaded on the web server, it can instantly start fulfilling
the request of the clients.

Scalable: We consider Java Servlets to be highly scalable. Servlets use completely lightweight
threads for the processes and can simultaneously handle multiple client requests by generating
various threads.

Robust: The Java Servlets are best known for their robust operating procedures. The servlets
extend the features of Java(Java Security Manager, Java Garbage Collector, Exception Handling)
the servlet has no memory leakage. This creates the development of web applications in servlet
secure and less error prone.
Servlet Types

There are two main servlet types, generic and HTTP:

 Generic servlets
o Extend javax.servlet.GenericServlet.
o Are protocol independent. They contain no inherent HTTP support or any other
transport protocol.
 HTTP servlets
o Extend javax.servlet.HttpServlet.
o Have built-in HTTP protocol support and are more useful in a Sun Java System
Web Server environment.

All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle
methods.

For both servlet types, you implement the constructor method init() and the destructor
method destroy() to initialize or deallocate resources.

All servlets must implement a service() method, which is responsible for handling servlet requests.
For generic servlets, simply override the service method to provide routines for handling requests.
HTTP servlets provide a service method that automatically routes the request to another method
in the servlet based on which HTTP transfer method is used. So, for HTTP servlets,
override doPost() to process POST requests, doGet() to process GET requests, and so on.

5.1.2 Servlet Architecture:


Servlet Architecture is can be depicted from the image itself as provided below as follows:
Execution of Servlets basically involves the following steps:

1. The clients send the request to the webserver using any web browser.
2. The web server receives the request, the server verifies the request and transfers the request
to the servlet container or web container.
3. The servlet container creates a request object, response object, and thread to handle the client
request. The container stores the request and response objects in the thread object. For every
client request, the container creates a pair of request, response, and thread objects. For example,
if the servlet receives 2 client requests, the container will create 2 pairs of the request, response
objects, and 2 threads. The multiple threads created by the container share the same OS-level
process.
4. The thread will invoke the service() lifecycle method of the servlet by passing the request and
the response objects as the parameters. The business logic implemented in the service() method
would be executed.
5. The container will provide the response object from the servlet to the web server.
6. The web server constructs the response data in the form of a web page and serves the page to
the client browser.
7. The container will destroy the request, response, and thread.

5.1.3 Servlets Life Cycle:

The life cycle is the process from the construction till the destruction of any object. A servlet also
follows a certain life cycle. The life cycle of the servlet is managed by the servlet container.

The container performs the following steps:


1. Loads Servlet Class
2. Creates instance of Servlet
3. Calls init( ) method
4. Calls service ( ) method
5. Calls destroy ( ) method
1. Loads the Servlet Class
The class loader is responsible to load the Servlet class into the container. The servlet class is
loaded when the first request comes from the web container.

2. Creates instance of Servlet


After loading of Servlet class into the container, the web container creates its instance. The
instance of Servlet class is created only once in the servlet life cycle.

3. Calls the init( ) method


The init( ) method performs some specific action constructor of a class. It is automatically called
by Servlet container. It is called only once through the complete servlet life cycle.

Syntax:
public void init(ServletConfig config ) throws ServletException

4. Calls the service( ) method


The service( ) method performs actual task of servlet container. The web container is responsible
to call the service method each time the request for servlet is received. The service( ) invokes
the doGet( ), doPost( ), doPut ( ), doDelete( ) methods based on the HTTP request.

Syntax:
public void service(ServletRequest request, ServletResponse response) throws ServletException,
IOException

5. Calls the destroy( ) method


The destroy( ) method is executed when the servlet container remove the servlet from the
container. It is called only once at the end of the life cycle of servlet.

Syntax:
public void destroy( )
5.1.4 Servlets Generating Dynamic Content:
 Dynamic web pages are server-side web pages, each time it is viewed, we see different
content.
 It is controlled by Application server processing server-side scripts.
 The dynamic web pages can also change their contents on the request of the client.
 They have the capability to generate new content according to time and need. Which simply
means that dynamic web pages are never the same for all users.
 Dynamic web content is the content that changes with every user request. This type of web
application let the users personalize the content according to their preferences.
 To build such a powerful web app, you need Java technologies, like servlet and JSP. Web
Server is mostly designed to serve static HTML content. For this type of app, web server
needed a servlet plugin that can communicate with or build dynamic pages.
 Servlet plugin is also called as servlet container or web container.

 A Servlet is an ordinary Java class that implements a special Servlet interface. This class
is then deployed in a Servlet container.

 The servlet container is connected to a web server. When an HTTP request arrives at the
web server which should be handled by a servlet, the web server forwards the request to
the servlet container. The servlet container then forwards the request to the servlet that is
to handle the request.

 Today most servlet containers come with built-in web servers, so you do not often make
the distinction between a Java web server and a Java servlet container.

 Examples of Java web servers with servlet containers are Apache Tomcat, Glassfish, Jetty,
JBoss etc.
5.1.4.1 Steps to Create Servlets Application:

A web server is required to develop a servlet application. We are using Apache Tomcat server to
develop servlet application.

Following are the steps to develop a servlet application:


1. Create directory structure
2. Create a servlet
3. Compile the servlet
4. Create a deployment descriptor
5. Start the server and deploy the application

1. Create directory structure

There is a unique directory structure that must be followed to create Servlet application. This
structure tells where to put the different types of files.
2. Create a Servlet
//ServletDemo.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class ServletDemo extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("<html><body>");
pw.println("Hello World");
pw.println("</body></html>");
pw.close();
}
}

3. Compile the Servlet program

Assuming the class path and environment is setup properly, run the above Java program.
C:\javac ServletDemo.java
after compiling the Java file, paste the class file of servlet in WEB-INF/classes directory.

4. Create a deployment descriptor

The deployment descriptor is an xml file. It is used to map URL to servlet class, defining error
page.
//web.xml
<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>
5. Start the server and deploy the application

Now start the Tomcat server by using


<Tomcat installation-direcory>\bin\startup.bat
Open browser and type
http://localhost:8080/demo/HelloWorld

Advantages of Servlets:

Now let us see some advantages of servlets –


 Performance is outstanding.
 Servlets can execute within the address space of a server. As a result, we can say that it is
unnecessary to create a separate address space to handle the client request.
 They are platform-independent and mainly component-based.
 Servlets are secured as the security manager sets some restrictions to protect the resources
and data.
 While working, users don’t need to worry about freeing memory as a garbage allocation
technique.
 Servlets provide full functionality as all the libraries are available. It can easily
communicate with applets and other mechanisms.
5.2 Java Swing and Abstract Window Toolkit (AWT):

5.2.1 Introduction:

 Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract
Window Toolkit [AWT].
 Unlike AWT, Java Swing provides platform-independent and lightweight components.
 The components are lightweight as compared to AWT components. It provides an excellent
interface to the user for all the platforms. It is not specifically for one platform.
 The components are written in Java and platform-independent as well. The Java foundation
classes first appeared in 1997, then later called Swing. To use the swing in java, javax. A
swing package needs to be used or imported. It is also known as Java Swing.
 Swing offers much-improved functionality over AWT, new components, expanded
components features, and excellent event handling with drag-and-drop support.
 The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Definition of Swing:
Swing is the graphical user interface toolkit that is used for developing windows based java
applications or programs. It is the successor of AWT, known as the Abstract window toolkit API
for Java, and AWT components are mainly heavyweight.

Features of Swing:
The features of the Swing are as follows:

1. Platform Independent: It is platform-independent; the swing components used to build


the program are not platform-specific. It can be used on any platform and anywhere.
2. Lightweight: Swing components are lightweight, which helps in creating the UI lighter.
The swings component allows it to plug into the operating system user interface
framework, including the mappings for screens or devices and other user interactions like
keypress and mouse movements.
3. Plugging: It has a powerful component that can be extended to provide support for the user
interface that helps in a good look and feel to the application. It refers to the highly
modular-based architecture that allows it to plug into other customized implementations
and frameworks for user interfaces. Its components are imported through a package called
java.swing.
4. Manageable: It is easy to manage and configure. Its mechanism and composition pattern
also allows changing the settings at run time. The uniform changes can be provided to the
user interface without any changes to the application code.
5. MVC: They mainly follow the concept of MVC, which is the Model View Controller.
With the help of this, we can make changes in one component without impacting or
touching other components. It is known as loosely coupled architecture as well.
6. Customizable: Swing controls can be easily customized. It can be changed, and the visual
appearance of the component application is independent of its internal representation.

5.2.2 Limitations of AWT:

Abstract Window Toolkit (AWT) is a set of Java classes for creating graphical user interface (GUI)
components such as buttons, labels, and windows. While AWT was the first GUI toolkit available
for Java. Some of the limitations of AWT include:

1. Platform-dependent: AWT is built on top of the native GUI toolkits of the underlying
operating system, which means that the look and feel of AWT components can be
different on different platforms.
2. Limited customization: The components in AWT have a limited set of properties that
can be modified, making it difficult to customize the look and feel of the components.
3. Limited layout management: AWT's layout management is basic and it can be difficult
to create complex layouts with it.
4. Limited functionality: AWT components have a limited set of functionality, and many
of the more advanced features found in other toolkits are not available in AWT.
5. Poor performance: AWT components are heavy-weight and can consume a lot of
resources, making them less performant than other toolkits, especially when handling
large numbers of components.

Due to these limitations, AWT is generally not recommended for developing new GUI applications
in Java. Instead, developers typically use more advanced toolkits such as Swing or JavaFX for
creating modern, feature-rich, and platform-independent GUI applications.

5.2.3 MVC architecture:

MVC stands for Model-View-Controller. The Model-View-Controller (MVC) is a well-


known design pattern in the web development field.

It is way to organize our code. It specifies that a program or application shall consist of data model,
presentation information and control information.

The MVC pattern needs all these components to be separated as different objects.
o Model: It represents the business layer or data for the application. It is an object to carry
the data that can also contain the logic to update controller if data is changed.
o View: It represents the presentation layer of application. It is used to visualize the data that
the model contains.
o Controller: It works on both the model and view. It is used to manage the flow of
application, i.e. data flow in the model object and to update the view whenever data is
changed.

Swing uses the model-view-controller architecture (MVC) as the fundamental design behind each
of its components. Essentially, MVC breaks GUI components into three elements. Each of these
elements plays a crucial role in how the component behaves. The MVC pattern is a model of how
a user interface can be structured.

Model
A model is an abstraction of something that is presented to the user. The models provided by Swing
fall into two general categories: GUI-state models and application-data models. GUI state
models are interfaces that define the visual status of a GUI control, such as whether a button is
pressed or armed like ButtonModel. An application-data model is an interface that represents some
quantifiable data that the UI presents to the user, such as the value of a cell in a table
like TableModel.

View
The view is a UI component that is responsible for presenting data to the user. Thus it is responsible
for all UI dependent issues like layout, drawing, etc. JTable is a good example for the view.

Controller
A controller encapsulates the application code that is executed in order to a user interaction (mouse
motion, mouse click, key press, etc.). Controllers might need input for their execution and they
produce output. They read their input from models and update models as result of the execution.
In swing a controller is normally implemented by an ActionListener or Action.
5.2.4 Swing components and containers:

A component is an independent visual control and Java Swing Framework contains a large set of
these components which provide rich functionalities and allow high level of customization. They
all are derived from JComponent class. All these components are lightweight components. This
class provides some common functionality like pluggable look and feel, support for accessibility,
drag and drop, layout, etc.

A container holds a group of components. It provides a space where a component can be managed
and displayed. Containers are of two types:

1. Top level Containers


o It inherits Component and Container of AWT.
o It cannot be contained within other containers.
o Heavyweight.
o Example: JFrame, JDialog, JApplet
2. Lightweight Containers
o It inherits JComponent class.
o It is a general purpose container.
o It can be used to organize related components together.
o Example: JPanel

5.2.5 Exploring swing:

The hierarchy of java swing API is given below.


JApplet:
 JApplet is a java swing public class designed for developers usually written in Java.
 JApplet is generally in the form of Java bytecode that runs with the help of a Java virtual
machine (JVM) or Applet viewer from Sun Microsystems.
 As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of
swing. The JApplet class extends the Applet class.

JFrame:
 It is an extended version of Java.awt.Frame that adds support for the JFC/Swing
architecture.
 JFrame is the core class of javax.swing package and is used to develop GUI (Graphical
User Interface) in which various visual objects like Text Field, Radio Button, Scroll Bar,
Check Box etc are embedded. This GUI is called Window pane.
 JFrame is a window with a title Bar, Border, a resizable Border, menu Bar, Buttons that
close or iconify the window and a content pane that acts as a container.

JComponent:
 With the exception of top-level containers, all Swing components whose names begin with
"J" descend from the JComponent class. For example, JPanel, JScrollPane, JButton,
and JTable all inherit from JComponent.
 The JComponent class extends the Container class, which itself extends Component.
 The Component class includes everything from providing layout hints to supporting
painting and events. The Container class has support for adding components to the
container and laying them out.
Icons and Labels:
 Swing allows you to create labels that can contain text, images, or both.
 JLabel is a class of java Swing. JLabel is used to display a short string or an image icon.
 JLabel is inactive to input events such a mouse focus or keyboard focus. By default labels
are vertically centred but the user can change the alignment of label.
Example:
ImageIcon icon = new ImageIcon("java-swing-tutorial.JPG","My Website");
JLabel j1 = new JLabel("Image with Text", icon, JLabel.CENTER);
JLabel j2 = new JLabel("Text Only Label");
JLabel j3 = new JLabel(icon);

JTextfields:
 JTextField is a part of javax.swing package. The class JTextField is a component that
allows editing of a single line of text. JTextField inherits the JTextComponent class and
uses the interface SwingConstants.
 A user can input non-formatted text in the box. To initialize the text field, call its
constructor and pass an optional integer parameter to it. This parameter sets the width of
the box measured by the number of columns. It does not limit the number of characters that
can be input in the box.
Example:
JTextField txtBox = new JTextField(16);
It renders a text box of 16 column width.
JButton:

 JButton class in Java is used to create push buttons that can be used to perform any
ActionEvent whenever it is clicked.
 In Order to achieve event action, the ActionListener interface needs to be implemented.
 The Buttons component in Swing is similar to that of the AWT button component except
that it can contain text, image or both.
 The JButton class extends the JComponent class and can be used in a container.

Examples:
JButton okBtn = new JButton(“Click Here");
This constructor returns a button with text Click Here on it

Check boxes:
 Check boxes are labelled options that allow the user to select multiple options at once.
Thus, any, all, or none of a set of check boxes may be selected.
 JCheckBox renders a check-box with a label. The check-box has two states – on/off. When
selected, the state is on and a small tick is displayed in the box.
Example:
CheckBox chkBox = new JCheckBox("Show Title", true);
It returns a checkbox with the label Show Help. Notice the second parameter in the constructor. It
is a boolean value that indicates the default state of the check-box. True means the check-box is
defaulted to on state.
Radio buttons:
 Radio buttons provide a user with a way to select one of a number of labelled options
displayed simultaneously in a window.
 Radio buttons are organized in a radio button group. Only one button in a group can be
selected at any given time.
 When the user selects a new button, the previously selected button is automatically
deselected. One button is usually selected at program starup by default.

Example:
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton rb1 = new JRadioButton("Easy", true);
JRadioButton rb2 = new JRadioButton("Medium");
JRadioButton rb3 = new JRadioButton("Hard");
radioGroup.add(rb1);
radioGroup.add(rb2);
radioGroup.add(rb3);
The above code creates a button group and three radio button elements. All three elements are
then added to the group. This ensures that only one option out of the available options in the
group can be selected at a time. The default selected option is set to Easy.

Combo boxes:
 Combo boxes are drop-down menus that can appear along with other widgets in the main
area of a window. The user may select one option at a time, and it then remains selected.
 JCombobox class is used to render a dropdown of the list of options.

Example:
String[] proglang = { “Java", "Python", "c++", "PHP", "Perl" };
JComboBox lang = new JComboBox(proglang);
lang.setSelectedIndex(3);
The default selected option can be specified through the setSelectedIndex method. The above code
sets C++ as the default selected option.

Tabbed Panes:
 With the JTabbedPane class, you can have several components, such as panels, share the
same space. The user chooses which component to view by selecting the tab corresponding
to the desired component.
 TtabbedPane is very useful component that lets the user switch between tabs in an
application. This is a highly useful utility as it lets the user browse more content without
navigating to different pages.
 To create a tabbed pane, instantiate JTabbedPane, create the components you wish it to
display, and then add the components to the tabbed pane using the addTab method.
Example:
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab 1", new JPanel());
tabbedPane.addTab("Tab 2", new JPanel());
tabbedPane.addTab("Tab 3", new JPanel());
tabbedPane.addTab("Tab 4", new JPanel());

The above code creates a two tabbed panel with headings Tab1 Tab2 Tab3 and Tab4
Scroll Panes:
 A JscrollPane is used to make scrollable view of a component. When screen size is limited,
we use a scroll pane to display a large component or a component whose size can change
dynamically.
 It can have both vertical and horizontal scrollbars when needed.
Example:
JTextArea tArea = new JTextArea(10,10);
JScrollPane scrollPane = new JScrollPane(tArea);
panel.add(scrollPane);
The above code creates a scroll pane with JTextarea component. When the component
content is larger than the view, then horizontal and vertical scrollbar appears.

Trees:
 JTree is a Swing component with which we can display hierarchical data. JTree is quite a
complex component.
 A JTree has a 'root node' which is the top-most parent for all nodes in the tree. A node is
an item in a tree.
 A node can have many children nodes. These children nodes themselves can have further
children nodes. If a node doesn't have any children node, it is called a leaf node.
Example:
DefaultMutableTreeNode state=new DefaultMutableTreeNode("States");
DefaultMutableTreeNode wb=new DefaultMutableTreeNode("West Bengal");
DefaultMutableTreeNode del=new DefaultMutableTreeNode("Delhi");
DefaultMutableTreeNode ap=new DefaultMutableTreeNode("Andhra Pradesh");
DefaultMutableTreeNode tn=new DefaultMutableTreeNode("Tamil Nadu");
state.add(wb);
state.add(del);
state.add(ap);
state.add(tn);
JTree jt=new JTree(state);
f.add(jt);
Tables:
 The JTable class is a part of Java Swing Package and is generally used to display or edit
two-dimensional data that is having both rows and columns.
 It is similar to a spreadsheet. This arranges data in a tabular form.
Example:
String[] columnNames = {"Name", "Salary"};
Object[][] data = { {"Ramesh Raman", 5000} {"Shabbir Hussein", 7000} };
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setSize(300, 300);
table.setFillsViewportHeight(true);

5.2.6 Networking with java:

Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.
Java socket programming provides facility to share data between different computing devices.

Advantage of Java Networking


1. Sharing resources
2. Centralize software management.
The java.net package supports two protocols,

1. TCP: Transmission Control Protocol provides reliable communication between the sender
and receiver. TCP is used along with the Internet Protocol referred as TCP/IP.
2. UDP: User Datagram Protocol provides a connection-less protocol service by allowing
packet of data to be transferred along two or more nodes

The widely used Java networking terminologies are given below:


1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

1) IP Address

IP address is a unique number assigned to a node of a network e.g. 192.168.0.1. It is composed of


octets that range from 0 to 255.It is a logical address that can be changed.

2) Protocol

A protocol is a set of rules basically that is followed for communication. For example:

o TCP
o FTP
o Telnet
o SMTP
o POP etc.

3) Port Number

The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.

The port number is associated with the IP address for communication between two applications.

4) MAC Address

MAC (Media Access Control) address is a unique identifier of NIC (Network Interface Controller).
A network node can have multiple NIC but each with unique MAC address.

For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.


5) Connection-oriented and connection-less protocol

In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but


slow. The example of connection-oriented protocol is TCP.

But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable
but fast. The example of connection-less protocol is UDP.

6) Socket

A socket is an endpoint between two way communications.

5.2.7Java Object Database Connectivity (ODBC):


 JDBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC
(Open Database Connectivity).
 JDBC is a standard API specification developed in order to move data from frontend to
the backend. This API consists of classes and interfaces written in Java.
 It basically acts as an interface (not the one we use in Java) or channel between your Java
program and databases i.e it establishes a link between the two so that a programmer
could send data from Java code and store it in the database for future use.
 JDBC was initially conceived as a client-side API, enabling a Java client to interact with a
data source. That changed with JDBC 2.0, which included an optional package supporting
server-side JDBC connections.
 Every new JDBC release since then has featured updates to both the client-side package
(java.sql) and the server-side package (javax.sql).

How JDBC works:

As a developer, you can use JDBC to interact with a database from within a Java program.
JDBC acts as a bridge from your code to the database, as shown in Figure.
JDBC’s architecture:

The JDBC interface consists of two layers:


 The JDBC API supports communication between the Java application and the JDBC
manager.
 The JDBC driver supports communication between the JDBC manager and the database
driver.
The JDBC API and JDBC driver have been refined extensively over the years, resulting in a
feature-rich, performant, and reliable library.

JDBC is the common API that your application code interacts with. Beneath that is the JDBC-
compliant driver for the database you are using. The following Figure illustrates the JDBC
architecture.

JDBC drivers

As an application programmer, you don’t need to immediately be concerned with the


implementation of the driver you use, so long as it is secure and official. However, it is useful to
be aware that there are four JDBC driver types:

 JDBC-ODBC bridge driver: A thin Java layer that uses an ODBC driver under the hood.
 Native API driver: Provides an interface from Java to the native database client.
 Middleware driver: A universal interface (“middleware”) between Java and the RDBMS’s
vendor-specific protocol.
 Pure Java driver: A driver that implements the vendor-specific protocol directly in Java.

Steps for Connectivity between Java Program and Database


1. Import the Packages
2. Load the drivers using the forName() method
3. Register the drivers using DriverManager
4. Establish a connection using the Connection class object
5. Create a statement
6. Execute the query
7. Close the connections
Let us discuss these steps one by one:

Step 1: Import the Packages


import java.sql.*; // Importing database
import java.util.*; // Importing required classes

Step 2: Loading the drivers


 In order to begin with, you first need to load the driver before using it in the program.
This is done by using Class.forName().

 The following example uses Class.forName() to load the Oracle driver as shown below
as follows:
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Step 3: Register the drivers
 Registration is to be done once in your program.
 You can register a driver using DriverManager.registerDriver()
 DriverManager is a Java inbuilt class with a static member register. Here we call the
constructor of the driver class at compile time.
 The following example uses DriverManager.registerDriver()to register the Oracle driver
as shown below:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
Step 4: Establish a connection using the Connection class object
 After loading the driver, establish connections as shown below as follows:
Connection con = DriverManager.getConnection(url,user,password)
user: Username from which your SQL command prompt can be accessed.
password: password from which the SQL command prompt can be accessed.
con: It is a reference to the Connection interface.
Url: Uniform Resource Locator which is created as shown below:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”
Step 5: Create a statement
 Once a connection is established you can interact with the database. The JDBCStatement,
CallableStatement, and PreparedStatement interfaces define the methods that enable you
to send SQL commands and receive data from your database.
Use of JDBC Statement is as follows:
Statement st = con.createStatement();
Note: Here, con is a reference to Connection interface used in previous step.
Step 6: Execute the query
 Now comes the most important part i.e executing the query. The query here is an SQL
Query. Now we know we can have multiple types of queries. Some of them are as
follows:
1. The query for updating/inserting a table in a database.
2. The query for retrieving data.
 The executeQuery() method of the Statement interface is used to execute queries of
retrieving values from the database. This method returns the object of ResultSet that can
be used to get all the records of a table.
 The executeUpdate(sql query) method of the Statement interface is used to execute
queries of updating/inserting.

Step 7: Closing the connections
 So finally we have sent the data to the specified location and now we are on the verge of
completing our task.
 By closing the connection, objects of Statement and ResultSet will be closed
automatically.
 The close() method of the Connection interface is used to close the connection. It is
shown below as follows:
con.close();

Example java program for Connectivity between Java Program and Database

import java.io.*;
import java.sql.*;

class jdbcconnection {
public static void main(String[] args) throws Exception
{
String url= "jdbc:mysql://localhost:3306/table_name"; // table details
String username = "rootgfg"; // MySQL credentials
String password = "gfg123";
String query = "select *from students"; // query to be run
Class.forName("com.mysql.cj.jdbc.Driver"); // Driver name
Connection con = DriverManager.getConnection(url, username, password);
System.out.println("Connection Established successfully");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query); // Execute query
rs.next();
String name = rs.getString("name"); // Retrieve name from db
System.out.println(name); // Print result on console
st.close(); // close statement
con.close(); // close connection
System.out.println("Connection Closed....");
}
}
Output

You might also like