Java Notes
Java Notes
JAVA PROGRAMMING
DIGITAL NOTES
B. TECH II YEAR – II SEM (2022-23)
MALLAREDDY UNIVERSITY
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.
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]
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:
OOP Concepts
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.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
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
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.
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.
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.
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
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
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:
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Output:20
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
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
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
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
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:
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.
Java Enum
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.
The control flow statements in Java allow you to run or skip blocks of code when special
conditions are met.
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:
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
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:
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:
Example:
Creating Arrays:
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:
Example:
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:
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);
}
}
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);
}}}
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console class is
introduced since 1.5.
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);
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
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.
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
Output:
111 Karan
222 Aryan
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
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);}
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,
a, b − formal parameters
Method definition consists of a method header and a method body. The same is shown in the
following syntax −
Syntax
modifier − It defines the access type of the method and it is optional to use.
nameOfMethod − This is the method name. The method signature consists of the method
name and the parameter list.
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.
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);
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.
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.
If you apply static keyword with any method, it is known as static method.
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
Access Control
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.
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
The protected access modifier is accessible within package and outside the package but through
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.
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();
}}
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
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
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.
The java compiler provides a default constructor if you Method is not provided by compiler in
don't have any constructor. any case.
There are many differences between constructors and methods. They are given belo
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.
Polymorphism : Method overloading and method overriding, abstract classes and methods.
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.
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 extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called 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);
}
}
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
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
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.
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:
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.
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:
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.
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.
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.
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().
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.
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
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.
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{}
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.
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");
}
Output:
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:
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...
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...
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.
JAVA PROGRAMMING
{
Bike obj=new Honda3();
System.out.println(obj.speedlimit);//90
}
Output:
90
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
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.
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.
In Java, Method Overloading is not possible by changing the return type of the method only.
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
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
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.
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:
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.
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);
}
}
}
JAVA PROGRAMMING
Output:40
60
class OverloadingCalculation2
{
void sum(int a,int b)
{
System.out.println("int arg method invoked");
}
void sum(long a,long b)
{
System.out.println("long arg method invoked");
}
If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.
class OverloadingCalculation3
{
void sum(int a,long b)
{
System.out.println("a method invoked");
}
void sum(long a,int b)
{
System.out.println("b method invoked");
}
JAVA PROGRAMMING
public static void main(String args[])
{
OverloadingCalculation3 obj=new OverloadingCalculation3();
obj.sum(20,20);//now ambiguity
}
}
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.
Let's understand the problem that we may face in the program if we don't use method overriding.
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.
JAVA PROGRAMMING
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
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
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
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:
A list of differences between overloading and overriding in Java is given below for quick
revision in tabular form.
Private/Static/Final
5 Can be overloaded. Cannot be overridden.
method
JAVA PROGRAMMING
polymorphism, static
polymorphism, or early
binding.
JAVA PROGRAMMING
Connecting a method call to the method body is known as binding.
Understanding Type
int data=30;
JAVA PROGRAMMING
class 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.
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.
class Animal
{
void eat()
{
JAVA PROGRAMMING
System.out.println("animal is eating...");
}
}
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.
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.
JAVA PROGRAMMING
There are two ways to achieve abstraction 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.
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.
running safely
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
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
File: TestBank.java
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:
An abstract class can have a data member, abstract method, method body (non-abstract method),
constructor, and even main() method.
File: TestAbstraction2.java
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 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.
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();
}
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.
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.
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.
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
In this example, 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
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
JAVA PROGRAMMING
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}
}
Output:
drawing circle
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
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");
}
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();
}
Output:
Hello
Interface inheritance:
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");
}
Output:
Hello
Welcome
There properties can be reused commonly in a There properties commonly usable in any
2
specific application. application of java environment.
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
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.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
1|P a ge
JAVA PROGRAMMING
Malla Reddy University
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
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.
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
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
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.
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.
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
Output:Hello subpackage
There is a scenario, I want to put the class file of A.java source file in classes folder of c: drive.
For example:
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
To Compile:
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
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:
Output:Welcome to package
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{}
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{}
Package class:
The package class provides methods to get information about the specification and
implementation of a package. It provides methods such as getName(), getImplementationTitle(),
getImplementationVendor(), getImplementationVersion() etc.
In this example, we are printing the details of java.lang package by invoking the methods of
package class.
1. class PackageInfo{
2. public static void main(String args[]){
3.
4. Package p=Package.getPackage("java.lang");
5.
6. System.out.println("package name: "+p.getName());
7.
8. System.out.println("Specification Title: "+p.getSpecificationTitle());
9. System.out.println("Specification Vendor: "+p.getSpecificationVendor());
10. System.out.println("Specification Version: "+p.getSpecificationVersion());
11.
12. System.out.println("Implementaion Title: "+p.getImplementationTitle());
13. System.out.println("Implementation Vendor: "+p.getImplementationVendor());
14. System.out.println("Implementation Version: "+p.getImplementationVersion());
8|P a ge
JAVA PROGRAMMING
Malla Reddy University
In this tutorial, we will learn about Java exceptions, it's types, and the difference between
checked and unchecked exceptions.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the application.
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?
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
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
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
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.
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.
Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.
JavaExceptionExample.java
Output:
13 | P a g e
JAVA PROGRAMMING
Malla Reddy University
There are given some scenarios where unchecked exceptions may occur. They are as follows:
int a=50/0;//ArithmeticException
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
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be
other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
14 | P a g e
JAVA PROGRAMMING
Malla Reddy University
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 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.
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:
But if the application programmer handles the exception, the normal flow of the application is
maintained, i.e., rest of the code is executed.
Example 1
TryCatchExample1.java
16 | P a g e
JAVA PROGRAMMING
Malla Reddy University
Output:
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.
Let's see the solution of the above problem by a java try-catch block.
Example 2
TryCatchExample2.java
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.
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.
Example 1
MultipleCatchBlock1.java
18 | P a g e
JAVA PROGRAMMING
Malla Reddy University
Output:
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.
19 | P a g e
JAVA PROGRAMMING
Malla Reddy University
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
Example 1
Let's see an example where we place a try block within another try block for two different
exceptions.
NestedTryBlock.java
21 | P a g e
JAVA PROGRAMMING
Malla Reddy University
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 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.
22 | P a g e
JAVA PROGRAMMING
Malla Reddy University
Note: If you don't handle the exception, before terminating the program, JVM executes finally
block (if any).
Let's see the different cases where Java finally block can be used.
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
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:
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
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).
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.
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.
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.
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
Output:
The above code throw an unchecked exception. Similarly, we can also throw unchecked and user
defined exceptions.
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.
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).
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:
30 | P a g e
JAVA PROGRAMMING
Malla Reddy University
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.
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.
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.
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...
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:
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:
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:
34 | P a g e
JAVA PROGRAMMING
Malla Reddy University
TestThrow.java
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:
TestThrows.java
Output:
36 | P a g e
JAVA PROGRAMMING
Malla Reddy University
TestThrowAndThrows.java
Output:
37 | P a g e
JAVA PROGRAMMING
Malla Reddy University
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:
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.
38 | P a g e
JAVA PROGRAMMING
Malla Reddy University
Let's consider the following example where we declare final variable age. Once declared it
cannot be modified.
FinalExampleTest.java
Output:
In the above example, we have declared a variable final. Similarly, we can declare the methods
and classes final using the final keyword.
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
Output:
FinalizeExample.java
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.
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:
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:
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:
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.
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.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
10. public Thread currentThread(): returns the reference of currently executing thread.
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
19. public void setDaemon(boolean b): marks the thread as daemon or user 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().
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
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.
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.
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.
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.
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.
// 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:
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.
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:
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();
}}
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.
import java.util.LinkedList;
// 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 {
// and sleep
Thread.sleep(1000);
}
}
}}
CONCEPTS OF APPLETS:
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.
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
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
After init() method start() method is invoked. Executed when the browser is maximized
Step 3: Paint
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
stop() method is used to stop the applet. It is executed when the browser is minimized.
Step 5: 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.
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.
FaceApplet.java
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).
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:
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 :
import java.applet.Applet;
import java.awt.Graphics;
There are two standard ways in which you can run an 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 :
appletviewer RunHelloWorld.html
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:
getParameter() Method:
The getParameter() method of the Applet class can be used to retrieve the parameters
passed from the HTML page.
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.
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:
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
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.
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.
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.
Syntax:
public void init(ServletConfig config ) throws ServletException
Syntax:
public void service(ServletRequest request, ServletResponse response) throws ServletException,
IOException
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.
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();
}
}
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.
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
Advantages of Servlets:
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:
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.
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:
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);
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.
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
1) IP Address
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.
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
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:
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
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.
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