You are on page 1of 136

Section-I

Unit- I
Features of Java
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Portable
7. Dynamic
8. Compiled and Interpreted
9. Multithreaded
10. Distributed
Simple
According to Sun, Java language is simple because:

 syntax is based on C++ (so easier for programmers to learn it after C++).

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

 No need to remove unreferenced objects because there is Automatic Garbage Collection


in java.
Object-oriented
Object-oriented means we organize our software as a combination of different types of objects
that incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software development and
maintenance by providing some rules.
In java everything including main is also in class. So the java is purely object oriented language.
Platform Independent
A platform is the hardware or software environment in which a program runs. There are two
types of platforms software-based and hardware-based. Java provides software-based platform.
The Java platform differs from most other platforms in the sense that it's a software-based
platform that runs on top of other hardware-based platforms.It has two components:
1. Runtime Environment
2. API(Application Programming Interface)

Secured
Java is secured because:
 No explicit pointer
 Programs run inside virtual machine sandbox.
 Classloader- adds security by separating the package for the classes of the local file
system from those that are imported from network sources.
 Bytecode Verifier- checks the code fragments for illegal code that can violate access
right to objects.
 Security Manager- determines what resources a class can access such as reading and
writing to the local disk.
These security are provided by java language.
Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers
that avoids security problem. There is automatic garbage collection in java. There is exception
handling and type checking mechanism in java. All these points makes java robust
Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed
applications. We may access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it shares the same memory. Threads are important for multi-media, Web
applications etc.

Difference between JDK, JRE and JVM

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform
dependent because configuration of each OS differs. But, Java is platform independent.
The JVM performs following main tasks:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment

JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is
the implementation of JVM.It physically exists.It contains set of libraries + other files that JVM
uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun Micro
Systems.
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development
tools.

JVM (Java Virtual Machine)


JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e.JVM is plateform dependent).
What is JVM?
It is:
1. A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by
Sun and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run
the java class, and instance of JVM is created.
What it does?
The JVM performs following operation:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment
JVM provides definitions for the:
 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.

Internal Architecture of JVM


Let's understand the internal architecture of JVM. It contains class loader, memory area,
execution engine etc.

1) Class loader:
Class loader is a subsystem of JVM that is used to load class files.
2) Class(Method) Area:
Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.
3) Heap:
It is the runtime data area in which objects are allocated.
4) Stack:
Java Stack stores frames.It holds local variables and partial results, and plays a part in method
invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.
5) Program Counter Register:
PC (program counter) register. It contains the address of the Java virtual machine instruction
currently being executed.
6) Native Method Stack:
It contains all the native methods used in the application.
7) Execution Engine:
It contains:

1) A virtual processor
2) Interpreter:Read bytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles parts of the
byte code that have similar functionality at the same time, and hence reduces the amount of time
needed for compilation.Here the term ?compiler? refers to a translator from the instruction set of
a Java virtual machine (JVM) to the instruction set of a specific CPU.

Variable and Datatype in Java


There are three types of variables: local, instance and static. There are two types of datatypes in
java, primitive and non-primitive.
Variable
Variable is name of reserved area allocated in memory.
1. int data=50;//Here data is variable
Types of Variable
There are three types of variables in java
 local variable
 instance variable
 static variable

Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable . It
is not declared as static.
Static variable
A variable that is declared as static is called static variable. It cannot be local.
We will have detailed learning of these variables in next chapters.
Example to understand the types of variables
1. class A{
2. int data=50;//instance variable
3. static int m=100;//static variable
4. void method(){
5. int n=90;//local variable
6. }
7. }//end of class

Data Types in Java


In java, there are two types of data types
 primitive data types
 non-primitive data types

Data Default Default


Type Value size

boolean false 1 bit

char '\u0000' 2 byte


byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Operators in java
Operator in java is a symbol that is used to perform operations. There are many types of
operators in java such as unary operator, arithmetic operator, relational operator, shift operator,
bitwise operator, ternary operator and assignment operator.

Operators Precedence

postfix expr++ expr--

unary ++expr --expr +expr -expr ~ !

multiplicative */%

additive +-

shift << >> >>>

relational < > <= >= instanceof

equality == !=

bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&

logical OR ||

ternary ?:

assignment = += -= *= /= %=
Simple Java Program
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Understanding first java program
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
 class keyword is used to declare a class in java.
 public keyword is an access modifier which represents visibility, it means it is visible to
all.
 static is a keyword, if we declare any method as static, it is known as static method. The
core advantage of static method is that there is no need to create object to invoke the
static method. The main method is executed by the JVM, so it doesn't require to create
object to invoke the main method. So it saves memory.
 void is the return type of the method, it means it doesn't return any value.
 main represents startup of the program.
 String[] args is used for command line argument.
 System.out.println() is used print statement.
Internal Details of Hello Java Program
What happens at compile time?
At compile time, java file is compiled by Java Compiler (It does not interact with OS) and
converts the java code into bytecode.
What happens at runtime?
At runtime, following steps are performed:

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


Bytecode Verifier: checks the code fragments for illegal code that can violate access right to
objects.
Interpreter: read bytecode stream then execute the instructions.
Enhanced for loop in Java:
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
 Declaration: The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for
block and its value would be the same as the current array element.
 Expression: This evaluates to the array you need to loop through. The expression can be
an array variable or method call that returns an array.
Example:
public class Test {

public static void main(String args[]){


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
This would produce the following result:
10,20,30,40,50,
James,Larry,Tom,Lacy,
UNIT-II
Object and Class in Java
Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen,
table, car etc. It can be physical or logical (tengible and intengible). The example of
integible object is banking system.
An object has three characteristics:
 state: represents data (value) of an object.
 behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
 identity: Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But,it is used internally by the JVM to identify each
object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is
used to write, so writing is its behavior.

Object is an instance of a class. Class is a template or blueprint from which objects are created.
So object is the instance(result) of a class.

Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which
objects are created.
A class in java can contain:
 data member
 method
 constructor
 block
 class and interface
Syntax to declare a class:
class <class_name>{
data member;
method;
}
Simple Example of Object and Class
In this example, we have created a Student class that have two data members id and name. We
are creating the object of the Student class by new keyword and printing the objects value.
class Student1{
int id;//data member (also instance variable)
String name;//data member(also instance variable)

public static void main(String args[]){


Student1 s1=new Student1();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:0 null

Method Overloading in Java


If a class have multiple methods by same name but different parameters, it is known as Method
Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand the
behaviour of the method because its name differs. So, we perform method overloading to figure
out the program quickly.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type

1)Example of Method Overloading by changing the no. of arguments


In this example, we have created two overloaded methods, first sum method performs addition of
two numbers and second sum method performs addition of three numbers.
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){


Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);

}
}

Output:30
40

2)Example of Method Overloading by changing data type of argument


In this example, we have created two overloaded methods that differs in data type. The first sum
method receives two integer arguments and second sum method receives two double arguments.
class Calculation2{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}

public static void main(String args[]){


Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);

}
}

Output:21.0
40

Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides
data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
<class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}

Output:
Bike is created
If there is no constructor in a class, compiler automatically creates a default constructor.

Q) What is the purpose of default constructor?


Default constructor provides the default values to the object like 0, null etc. depending on the
type.
Example of default constructor that displays the default values
class Student3{
int id;
String name;

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

public static void main(String args[]){


Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a
default constructor.Here 0 and null values are provided by default constructor.

Java parameterized constructor


A constructor that have parameters is known as parameterized constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.
class Student4{
int id;
String name;

Student4(int i,String n){


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

public static void main(String args[]){


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

Output:
111 Karan
222 Aryan

Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by taking
into account the numbe of parameters in the list and their type.
Example of Constructor Overloading
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Output:
111 Karan 0
222 Aryan 25

Difference between constructor and method in java


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

Method is used to expose behaviour


Constructor is used to initialize the state of an object.
of an object.

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

Constructor is invoked implicitly. Method is invoked explicitly.

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

Method name may or may not be


Constructor name must be same as the class name.
same as class name.
Java static keyword
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods.. The static keyword belongs to the class than instance of the
class.
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
1) Java static variable
If you declare any variable as static, it is known static variable.
 The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of students etc.
 The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Understanding problem without static variable
class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get memory
each time when object is created.All student have its unique rollno and name so instance data
member is good.Here, college refers to the common property of all objects.If we make it
static,this field will get memory only once.
Java static property is shared to all objects.

Example of static variable


//Program of static variable

class Student8{
int rollno;
String name;
static String college ="ITS";

Student8(int r,String n){


rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");

s1.display();
s2.display();
}
}
Output:111 Karan ITS
222 Aryan ITS

Program of counter without static variable


In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object
will have the copy of the instance variable, if it is incremented, it won't reflect to other objects.
So each objects will have the value 1 in the count variable.
class Counter{
int count=0;//will get memory when instance is created
Counter(){
count++;
System.out.println(count);
}

public static void main(String args[]){

Counter c1=new Counter();


Counter c2=new Counter();
Counter c3=new Counter();

}
}

Output:1
1
1

Program of counter by static variable


As we have mentioned above, static variable will get the memory only once, if any object
changes the value of the static variable, it will retain its value.
class Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;
System.out.println(count);
}

public static void main(String args[]){


Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();

}
}

Output:1
2
3

2) Java static method


If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 static method can access static data member and can change the value of it.
Example of static method
//Program of changing the common property of all objects(static field).

class Student9{
int rollno;
String name;
static String college = "ITS";

static void change(){


college = "BBDIT";
}

Student9(int r, String n){


rollno = r;
name = n;
}

void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student9.change();

Student9 s1 = new Student9 (111,"Karan");


Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");

s1.display();
s2.display();
s3.display();
}
}

Output:111 Karan BBDIT


222 Aryan BBDIT
333 Sonoo BBDIT

Restrictions for static method


There are two main restrictions for the static method. They are:

1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block only.
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can't
be changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Output: Compile Time Error

2) Java final method


If you make any method as final, you cannot override it.
Example of final method
class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output: Compile Time Error

3) Java final class


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

class Honda1 extends Bike{


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

public static void main(String args[]){


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

Output: Compile Time Error

Q) Is final method inherited?


Ans) Yes, final method is inherited but you cannot override it. For Example:
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}

Output: running...
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of parent
class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing
class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called
a subclass.
Understanding the simple example of inheritance

As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer is
a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
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);
}
}
OUTPUT:
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.

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


When a class extends multiple classes i.e. known as multiple inheritance. For Example:

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If
A and B classes have same method and you call it from child class object, there will be
ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time error
now.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

Public Static void main(String args[]){


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

Abstract class in Java


A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
Before learning java abstract class, let's understand the abstraction in java first.

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)

Abstract class in Java


A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
Example abstract class
abstract class A{}

abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.
Example abstract method
abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method


In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
abstract class Bike{
abstract void run();
}

class Honda4 extends Bike{


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

public static void main(String args[]){


Bike obj = new Honda4();
obj.run();
}
}
Output;
running safely..

Understanding the real scenario of abstract class


In this example, Shape is the abstract class, its implementation is provided by the Rectangle and
Circle classes.
. In this example, if you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.
File: TestAbstraction1.java
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}

class Circle1 extends Shape{


void draw(){System.out.println("drawing circle");}
}

//In real scenario, method is called by programmer or user


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

Shape s=new Circle1();


s.draw();
}
}
Output:
drawing circle

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java.
In other words, If subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
 Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
 Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

Understanding the problem without method overriding


Let's understand the problem that we may face in the program if we don't use method overriding.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{

public static void main(String args[]){


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

public static void main(String args[]){


Bike2 obj = new Bike2();
obj.run();
}

Output:Bike is running safely

Real example of Java Method Overriding


Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of
interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%,
7% and 9% rate of interest.
class Bank{
int getRateOfInterest(){return 0;}
}

class SBI extends Bank{


int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}

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

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Difference between method overloading and method overriding in java
No. Method Overloading Method Overriding

Method overriding is used to provide


Method overloading is used to increase the the specific implementation of the
1)
readability of the program. method that is already provided by its
super class.

Method overriding occurs in two


2) Method overloading is performed within class. classes that have IS-A (inheritance)
relationship.

In case of method overloading, parameter must be In case of method overriding,


3)
different. parameter must be same.

Method overloading is the example of compile time Method overriding is the example of
4)
polymorphism. run time polymorphism.

In java, method overloading can't be performed by


changing return type of the method only. Return type Return type must be same or
5)
can be same or different in method overloading. But covariant in method overriding.
you must have to change the parameter.

Java Method Overloading example


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

The java instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with any
variable that has null value, it returns false.
Simple example of java instanceof
Let's see the simple example of instance operator where it tests the current class.
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple);//true
}
}
Output: true

An object of subclass type is also a type of parent class. For example, if Dog extends Animal
then object of Dog can be referred by either Dog or Animal class.
Another example of java instanceof operator
class Animal{}
class Dog1 extends Animal{//Dog inherits Animal

public static void main(String args[]){


Dog1 d=new Dog1();
System.out.println(d instanceof Animal);//true
}
}
Output: true
instanceof in java with a variable that have null value
If we apply instanceof operator with a variable that have null value, it returns false. Let's see the
example given below where we apply instanceof operator with the variable that have null value.
class Dog2{
public static void main(String args[]){
Dog2 d=null;
System.out.println(d instanceof Dog2);//false
}
}
Output: false
this keyword in java
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers
to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
1. this keyword can be used to refer current class instance variable.
2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance.

1) The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves the
problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:
class Student10{
int id;
String name;

Student10(int id,String name){


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

public static void main(String args[]){


Student10 s1 = new Student10(111,"Karan");
Student10 s2 = new Student10(321,"Aryan");
s1.display();
s2.display();
}
}

Output:0 null
0 null
In the above example, parameter (formal arguments) and instance variables are same that is why
we are using this keyword to distinguish between local variable and instance variable.
Solution of the above problem by this keyword
//example of this keyword
class Student11{
int id;
String name;
Student11(int id,String name){
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();
}
}

Output111 Karan
222 Aryan

If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword like in the following program:
Program where this keyword is not required
class Student12{
int id;
String name;
Student12(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student12 e1 = new Student12(111,"karan");
Student12 e2 = new Student12(222,"Aryan");
e1.display();
e2.display();
}
}

Output:111 Karan
222 Aryan

2) this() can be used to invoked current class constructor.


The this() constructor call can be used to invoke the current class constructor (constructor
chaining). This approach is better if you have many constructors in the class and want to reuse
that constructor.
//Program of this() constructor call (constructor chaining)

class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}

Student13(int id,String name){


this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student13 e1 = new Student13(111,"karan");
Student13 e2 = new Student13(222,"Aryan");
e1.display();
e2.display();
}
}

Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
Where to use this() constructor call?
The this() constructor call should be used to reuse the constructor in the constructor. It maintains
the chain between the constructors i.e. it is used for constructor chaining. Let's see the example
given below that displays the actual use of this keyword.
class Student14{
int id;
String name;
String city;

Student14(int id,String name){


this.id = id;
this.name = name;
}
Student14(int id,String name,String city){
this(id,name);//now no need to initialize id and name
this.city=city;
}
void display(){System.out.println(id+" "+name+" "+city);}

public static void main(String args[]){


Student14 e1 = new Student14(111,"karan");
Student14 e2 = new Student14(222,"Aryan","delhi");
e1.display();
e2.display();
}
}

Output:111 Karan null


222 Aryan delhi
Rule: Call to this() must be the first statement in constructor.
class Student15{
int id;
String name;
Student15(){System.out.println("default constructor is invoked");}

Student15(int id,String name){


id = id;
name = name;
this ();//must be the first statement
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student15 e1 = new Student15(111,"karan");
Student15 e2 = new Student15(222,"Aryan");
e1.display();
e2.display();
}
}

Output: Compile Time Error

3)The this keyword can be used to invoke current class method (implicitly).
You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see the
example

class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}

Output: method is invoked

4) this keyword can be passed as an argument in the method.


The this keyword can also be passed as an argument in the method. It is mainly used in the event
handling. Let's see the example:
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}

public static void main(String args[]){


S2 s1 = new S2();
s1.p();
}
}

Output:method is invoked
Application of this that can be passed as an argument:
In event handling (or) in a situation where we have to provide reference of a class to another one.

5) The this keyword can be passed as argument in the constructor call.


We can pass the this keyword in the constructor also. It is useful if we have to use one object in
multiple classes. Let's see the example:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}

class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10

6) The this keyword can be used to return current class instance.


We can return the this keyword as an statement from the method. In such case, return type of the
method must be the class type (non-primitive). Let's see the example:
Syntax of this that can be returned as a statement
return_type method_name(){
return this;
}
Example of this keyword that you return as a statement from the method
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}

class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}

Output:Hello java

Proving this keyword


Let's prove that this keyword refers to the current class instance variable. In this program, we are
printing the reference variable and this, output of both variables are same.
class A5{
void m(){
System.out.println(this);//prints same reference ID
}

public static void main(String args[]){


A5 obj=new A5();
System.out.println(obj);//prints the reference ID

obj.m();
}
}

Output:A5@22b3ea59
A5@22b3ea59
Variable Argument (Varargs):
The varrags allows the method to accept zero or muliple arguments. Before varargs either we use
overloaded method or take an array as the method parameter but it was not considered good
because it leads to the maintenance problem. If we don't know how many argument we will have
to pass in the method, varargs is the better approach.
Advantage of Varargs:
We don't have to provide overloaded methods so less code.

Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:
return_type method_name(data_type... variableName){}

Simple Example of Varargs in java:

class VarargsExample1{

static void display(String... values){


System.out.println("display method invoked ");
}

public static void main(String args[]){

display();//zero argument
display("my","name","is","varargs");//four arguments
}
}

Output:display method invoked


display method invoked
Another Program of Varargs in java:

class VarargsExample2{

static void display(String... values){


System.out.println("display method invoked ");
for(String s:values){
System.out.println(s);
}
}

public static void main(String args[]){

display();//zero argument
display("hello");//one argument
display("my","name","is","varargs");//four arguments
}
}

Output:display method invoked


display method invoked
hello
display method invoked
my
name
is
varargs
Rules for varargs:
While using the varargs, you must follow some rules otherwise program code won't compile.
The rules are as follows:
 There can be only one variable argument in the method.
 Variable argument (varargs) must be the last argument.
Examples of varargs that fails to compile:

void method(String... a, int... b){}//Compile time error

void method(int... a, String b){}//Compile time error

Example of Varargs that is the last argument in the method:

class VarargsExample3{

static void display(int num, String... values){


System.out.println("number is "+num);
for(String s:values){
System.out.println(s);
}
}

public static void main(String args[]){

display(500,"hello");//one argument
display(1000,"my","name","is","varargs");//four arguments
}
}

Output:number is 500
hello
number is 1000
my
name
is
varargs
UNIT-III

Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and
multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
 It is used to achieve fully abstraction.
 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.
The java compiler adds public and abstract keywords before the interface method and public,
static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods are public and
abstract.
Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.

Simple example of Java interface


In this example, Printable interface have only one method, its implementation is provided in the
A class.
interface printable{
void print();
}

class A6 implements printable{


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

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

Output:Hello

Multiple inheritance in Java by interface


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

interface Printable{
void print();
}

interface Showable{
void show();
}

class A7 implements Printable,Showable{

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


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

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}

Output:Hello
Welcome

Q) Multiple inheritance is not supported through class in java but it is possible by


interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of
class. But it is supported in case of interface because there is no ambiguity as implementation is
provided by the implementation class. For example:
interface Printable{
void print();
}
interface Showable{
void print();
}

class TestTnterface1 implements Printable,Showable{


public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestTnterface1 obj = new TestTnterface1();
obj.print();
}
}
Output:
Hello
As you can see in the above example, Printable and Showable interface have same methods but
its implementation is provided by class TestTnterface1, so there is no ambiguity.

Interface inheritance
A class implements interface but one interface extends another interface .
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class Testinterface2 implements Showable{

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


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

public static void main(String args[]){


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

Q) What is marker or tagged interface?


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

Nested Interface in Java


Note: An interface can have another interface i.e. known as nested interface. We will learn it in
detail in the nested classes chapter. For example:
interface printable{
void print();
interface MessagePrintable{
void msg();
}
}
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and non-


Interface can have only abstract methods.
abstract methods.

2) Abstract class doesn't support multiple


Interface supports multiple inheritance.
inheritance.

3) Abstract class can have final, non-final, static


Interface has only static and final variables.
and non-static variables.
4) Abstract class can have static methods, main Interface can't have static methods, main
method and constructor. method or constructor.

5) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.

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

7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
Example of abstract class and interface in Java
Let's see a simple example where we are using interface and abstract class both.
//Creating interface that has 4 methods
interface A{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}

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

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

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


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

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

Access Modifiers in java


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

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
2) protected access modifier
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
3) public access modifier
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Example of public access modifier
//save by A.java

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

package mypack;
import pack.*;

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

Understanding all java access modifiers


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

Access within within outside package by subclass outside


Modifier class package only package

Private Y N N N

Protected Y Y Y N

Public Y Y Y Y

Java String
Java String provides a lot of concepts that can be performed on a string such as compare,
concat, equals, split, length, replace, compareTo, intern, substring etc.
In java, string is basically an object that represents sequence of char values.
An array of characters works same as java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
What is String in java
Generally, string is a sequence of characters. But in java, string is an object that represents a
sequence of characters. String class is used to create string object.
How to create String object?
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
2) By new keyword
1. String s=new String("Welcome");
ava String Example
1. public class StringExample{
2. public static void main(String args[]){
3. String s1="java";//creating string by java string literal
4.
5. char ch[]={'s','t','r','i','n','g','s'};
6. String s2=new String(ch);//converting char array to string
7.
8. String s3=new String("example");//creating java string by new keyword
9.
10. System.out.println(s1);
11. System.out.println(s2);
12. System.out.println(s3);
13. }}
Test it Now
java
strings
example
Java String class methods
The java.lang.String class provides many useful methods to perform operations on sequence of
char values.

No. Method Description

1 char charAt(int index) returns char value for the particular index

2 int length() returns string length

3 String substring(int beginIndex) returns substring for given begin index

String substring(int beginIndex, int returns substring for given begin index and end
4
endIndex) index

5 boolean equals(Object another) checks the equality of string with object

6 String concat(String str) concatinates specified string

7 String replace(char old, char new) replaces all occurrences of specified char value

returns trimmed string omitting leading and


8 String trim()
trailing spaces

9 int indexOf(int ch) returns specified char value index

returns specified char value index starting with


10 int indexOf(int ch, int fromIndex)
given index

11 String toLowerCase() returns string in lowercase.

12 String toUpperCase() returns string in uppercase.

Java String compare

We can compare string in java on the basis of content and reference.


It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.
There are three ways to compare string in java:
1. By equals() method
2. By = = operator
3. By compareTo() method
1) String compare by equals() method
The String equals() method compares the original content of the string. It compares values of
string for equality. String class provides two methods:
 public boolean equals(Object another) compares this string to the specified object.
 public boolean equalsIgnoreCase(String another) compares this String to another
string, ignoring case.
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}

Output:true
true
false
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";

System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s3));//true
}
}
Test it Now
Output:false
true

2) String compare by == operator


The = = operator compares references not values.
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
}
}

Output:true
false

3) String compare by compareTo() method


The String compareTo() method compares values lexicographically and returns an integer value
that describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
 s1 == s2 :0
 s1 > s2 :positive value
 s1 < s2 :negative value
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )

Output:0
1
-1
Java StringBuffer class
Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in
java is same as String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
Important Constructors of StringBuffer class
1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
Important methods of StringBuffer class
1. public synchronized StringBuffer append(String s): is used to append the specified
string with this string. The append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double) etc.
2. public synchronized StringBuffer insert(int offset, String s): is used to insert the
specified string with this string at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float),
insert(int, double) etc.
3. public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is
used to replace the string from specified startIndex and endIndex.
4. public char charAt(int index): is used to return the character at the specified position.
5. public int length(): is used to return the length of the string i.e. total number of
characters.
What is mutable string
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
1) StringBuffer append() method
The append() method concatenates the given argument with this string.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
2) StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Vectors: Vector implements a dynamic array. It is similar to ArrayList, but with two differences:
 Vector is synchronized.
 Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance or you just
need one that can change sizes over the lifetime of a program.
Below given are the list of constructors provided by the vector class.

SR.NO Constructor and Description

Vector( )
1
This constructor creates a default vector, which has an initial size of 10

Vector(int size)
2 This constructor accepts an argument that equals to the required size, and creates a
vector whose initial capacity is specified by size:
Vector defines the following methods:

SN Methods with Description

void add(int index, Object element)


1
Inserts the specified element at the specified position in this Vector.

void addElement(Object obj)


2
Adds the specified component to the end of this vector, increasing its size by one.

void copyInto(Object[] anArray)


3
Copies the components of this vector into the specified array.

Object elementAt(int index)


4
Returns the component at the specified index.

int indexOf(Object elem)


5 Searches for the first occurence of the given argument, testing for equality using the
equals method.

void insertElementAt(Object obj, int index)


6
Inserts the specified object as a component in this vector at the specified index.

7 Object remove(int index)


Removes the element at the specified position in this Vector.

void removeAllElements()
8
Removes all components from this vector and sets its size to zero.

void removeElementAt(int index)


9
removeElementAt(int index)

int size()
10
Returns the number of components in this vector.
/*Write a program that accepts a shopping list of items from the command line and stores them
in
a vector. Also provide facility to perform following operations
a) To delete an item in the list.
b) To add an item at a specified location in the list.
c) To add an item at the end of the list.
d) To print the contents of the vector.
*/

import java.util.*;
import java.io.*;

class MenuDriven
{
public static void main(String args[])
{
Vector itemList = new Vector();
String str,item;
int i,j,len,choice,pos;

len=args.length;
for(i=0;i<len;i++)
itemList.addElement(args[i]);
while(true)
{
System.out.println("\n\nChoose your choice ...");
System.out.println("1) Delete Item");
System.out.println("2) Add Item at Specified Location ");
System.out.println("3) Add Item at the End of the list");
System.out.println("4) Print Vector List ");
System.out.print("Enter your choice : ");

Scanner sc = new Scanner(System.in);


choice=sc.nextInt();
switch(choice)
{
case 1 : System.out.print("Enter Item you want to delete : ");
str=sc.nextLine();

itemList.removeElement(str); //string is not needed to convert object type as it

//is already object of class String


break;
case 2 : System.out.print("Enter Item to be Insert : ");

item=sc.nextLine();
System.out.print("Enter
Position to insert item : ");
pos=sc.nextInt();

itemList.insertElementAt(item,pos-1);
break;
case 3 : System.out.print("Enter Item to be Insert : ");

item=sc.nextLine();

itemList.addElement(item);
break;
case 4 : len=itemList.size();
System.out.println("\nItem Display ");
for(i=0;i<len;i++)
{

System.out.println((i+1)+") "+itemList.elementAt(i));
}
break;

default : System.out.println("\nEntered Choice is


Invalid\nTry Again\n");
}

}
}
}
Output:
Choose your choice ...
1) Delete Item
2) Add Item at Specified Location
3) Add Item at the End of the list
4) Print Vector List
5) Exit
Enter your choice : 2
Enter Item to be Insert : soap
Enter Position to insert item : 1

Choose your choice ...


1) Delete Item
2) Add Item at Specified Location
3) Add Item at the End of the list
4) Print Vector List
5) Exit
Enter your choice : 4

Item Display
1) soap
2) sugar
3) oil
4) jaggery
5) tea
6) coffee

Choose your choice ...


1) Delete Item
2) Add Item at Specified Location
3) Add Item at the End of the list
4) Print Vector List
5) Exit
Enter your choice : 5

Java - Packages
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations ) providing access protection and name space management.
Some of the existing packages in Java are::
 java.lang - bundles the fundamental classes
 java.io - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes.
Creating a package:
While creating a package, you should choose a name for the package and include a package
statement along with that name at the top of every source file that contains the classes, interfaces,
enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be placed in the current default package.
Package are categorized into two forms
 Built-in Package:-Existing Java package for example java.lang, java.util etc.
 User-defined-package:- Java package created by user to categorized classes and interface
Creating a package
Creating a package in java is quite easy. Simply include a package command followed by name
of the package as the first statement in java source file.
package mypack;
public class employee
{
...statement;
}

The above statement create a package called mypack.


Java uses file system directory to store package. For example the .class for any classes you to
define to be part of mypack package must be stored in a directory called mypack

Example of package creation


package mypack
class Book
{
String bookname;
String author;
Book(String b, String c)
{
this.bookname = b;
this.author = c;
}
public void show()
{
System.out.println(bookname+" "+ author);
}
}

class test
{
public static void main(String[] args)
{
Book bk = new Book("java","Herbert");
bk.show();
}
}
To run this program :
 create a directory under your current working development directory(i.e. JDK directory),
name it as mypack.
 compile the source file
 Put the class file into the directory you have created.
 Execute the program from development directory.
mport keyword
import keyword is used to import built-in and user-defined packages into your java source file.
So that your class can refer to a class that is in another package by directly using its name.
There are 3 different ways to refer to class that is present in different package
1. Using fully qualified name (But this is not a good practice.)
Example :
class MyDate extends java.util.Date
{
//statement;
}
2. import the only class you want to use.
Example :
import java.util.Date;
class MyDate extends Date
{
//statement.
}
3. import all the classes from the particular package
Example :
import java.util.*;
class MyDate extends Date
{
//statement;
}

import statement is kept after the package statement.


Example :
package mypack;
import java.util.*;
But if you are not creating any package then import statement will be the first statement of your
java source file.
Static import
static import is a feature that expands the capabilities of import keyword. It is used to import
static member of a class. We all know that static member are referred in association with its
class name outside the class. Using static import, it is possible to refer to the static member
directly without its class name. There are two general form of static import statement.
 The first form of static import statement, import only a single static member of a class
Syntax
import static package.class-name.static-member-name;
Example
import static java.lang.Math.sqrt; //importing static method sqrt of Math class
 The second form of static import statement,imports all the static member of a class
Syntax
import static package.class-type-name.*;
Example
import static java.lang.Math.*; //importing all static member of Math class

Example without using static import


public class Test
{
public static void main(String[] args)
{
System.out.println(Math.sqrt(144));
}
}
Output
12

Example using static import


import static java.lang.Math.*;
public class Test
{
public static void main(String[] args)
{
System.out.println(sqrt(144));
}
}
Output
12
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.

The import keyword is used to make the classes and interface of another package accessible to
the current package.
Example of package that import the packagename.*
//save by A.java

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

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
//save by A.java

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

package mypack;
import pack.A;

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

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.
Example of package by import fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

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

Multithreading in java is a process of executing multiple threads simultaneously.


Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
Advantage of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single thread
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved by two ways:
 Process-based Multitasking(Multiprocessing)
 Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
 Each process have its own address in memory i.e. each process allocates separate
memory area.
 Process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
2) Thread-based Multitasking (Multithreading)
 Threads share the same address space.
 Thread is lightweight.
 Cost of communication between the thread is low.
What is Thread in java
A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It
shares a common memory area.

As shown in the above figure, thread is executed inside the process. There is context-switching
between the threads. There can be multiple processes inside the OS and one process can have
multiple threads.

Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

1) New

The thread is in new state if you create an instance of Thread class but before the invocation of
start() method.

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated

A thread is in terminated or dead state when its run() method exits.

How to create thread

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface

Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:


 Thread()
 Thread(Runnable r)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep for
the specified number of milliseconds.
4. public int getPriority(): returns the priority of the thread.
5. public void setPriority(int priority): changes the priority of the thread.
6. public String getName(): returns the name of the thread.
7. public void setName(String name): changes the name of the thread.
8. public Thread currentThread(): returns the reference of currently executing thread.
9. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
10. public void suspend(): is used to suspend the thread(depricated).
11. public void resume(): is used to resume the suspended thread(depricated).
12. public void stop(): is used to stop the thread(depricated).

Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.

Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:

 A new thread starts(with new callstack).


 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method will run.

1)By extending Thread class:

class Multi extends Thread{

public void run(){

System.out.println("thread is running...");

public static void main(String args[]){

Multi t1=new Multi();

t1.start();

Output:thread is running...

2)By implementing the Runnable interface:

class Multi3 implements Runnable{

public void run(){

System.out.println("thread is running...");

}
public static void main(String args[]){

Multi3 m1=new Multi3();

Thread t1 =new Thread(m1);

t1.start();

Output:thread is running...

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

Sleep method in java

The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Syntax of sleep() method in java

The Thread class provides two methods for sleeping a thread:

 public static void sleep(long miliseconds)throws InterruptedException


 public static void sleep(long miliseconds, int nanos)throws InterruptedException

Example of sleep method in java

class TestSleepMethod1 extends Thread{

public void run(){

for(int i=1;i<5;i++){

try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}

System.out.println(i);
}

public static void main(String args[]){

TestSleepMethod1 t1=new TestSleepMethod1();

TestSleepMethod1 t2=new TestSleepMethod1();

t1.start();

t2.start();

Output:

1
1
2
2
3
3
4
4

As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time,the thread shedular picks up another thread and so on.

Priority of a Thread (Thread Priority):

Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.

3 constants defiend in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and


the value of MAX_PRIORITY is 10.

Example of priority of a Thread:

class TestMultiPriority1 extends Thread{

public void run(){

System.out.println("running thread name is:"+Thread.currentThread().getName());

System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

public static void main(String args[]){

TestMultiPriority1 m1=new TestMultiPriority1();

TestMultiPriority1 m2=new TestMultiPriority1();

m1.setPriority(Thread.MIN_PRIORITY);

m2.setPriority(Thread.MAX_PRIORITY);

m1.start();

m2.start();

Output:running thread name is:Thread-0


running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Synchronization in Java

Synchronization in java is the capability to control the access of multiple threads to any shared
resource.

Java Synchronization is better option where we want to allow only one thread to access the
shared resource.

Why use Synchronization

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. This
can be done by three ways in java:

1. by synchronized method
2. by synchronized block
3. by static synchronization

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor. Every object has
an lock associated with it. By convention, a thread that needs consistent access to an object's
fields has to acquire the object's lock before accessing them, and then release the lock when it's
done with them.

From Java 5 the package java.util.concurrent.locks contains several lock implementations.

Understanding the problem without Synchronization

In this example, there is no synchronization, so output is inconsistent. Let's see the example:

Class Table{

void printTable(int n){//method not synchronized

for(int i=1;i<=5;i++){

System.out.println(n*i);

try{

Thread.sleep(400);

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

}
}

class MyThread1 extends Thread{

Table t;

MyThread1(Table t){

this.t=t;

public void run(){

t.printTable(5);

class MyThread2 extends Thread{

Table t;

MyThread2(Table t){

this.t=t;

public void run(){

t.printTable(100);

}
class TestSynchronization1{

public static void main(String args[]){

Table obj = new Table();//only one object

MyThread1 t1=new MyThread1(obj);

MyThread2 t2=new MyThread2(obj);

t1.start();

t2.start();

Output: 5
100
10
200
15
300
20
400
25
500

Java synchronized method

If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.

//example of java synchronized method

class Table{

synchronized void printTable(int n){//synchronized method


for(int i=1;i<=5;i++){

System.out.println(n*i);

try{

Thread.sleep(400);

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

class MyThread1 extends Thread{

Table t;

MyThread1(Table t){

this.t=t;

public void run(){

t.printTable(5);

class MyThread2 extends Thread{

Table t;

MyThread2(Table t){
this.t=t;

public void run(){

t.printTable(100);

public class TestSynchronization2{

public static void main(String args[]){

Table obj = new Table();//only one object

MyThread1 t1=new MyThread1(obj);

MyThread2 t2=new MyThread2(obj);

t1.start();

t2.start();

Output: 5
10
15
20
25
100
200
300
400
500
Exception Handling in Java
The exception handling in java is one of the powerful mechanism to handle the runtime errors
so that normal flow of the application can be maintained.
What is an exception?
An Exception can be anything which interrupts the normal flow of the program. When an
exception occurs program processing gets terminated and doesn’t continue further. In such cases
we get a system generated error message. The good thing about exceptions is that they can be
handled.
Difference between error and exception
Errors indicate serious problems and abnormal conditions that most applications should not try
to handle. Error defines problems that are not expected to be caught under normal circumstances
by our program. For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such conditions and take
necessary corrective actions. Few examples –
 DivideByZero exception
 NullPointerException
 ArithmeticException
 ArrayIndexOutOfBoundsException
Advantages of Exception Handling
 Exception handling allows us to control the normal flow of the program by using
exception handling in program.
 It throws an exception whenever a calling method encounters an error providing that the
calling method takes care of that error.
 It also gives us the scope of organizing and differentiating between different error types
using a separate block of codes. This is done with the help of try-catch blocks.
Why to handle exception?
If an exception is raised, which has not been handled by programmer then program execution can get
terminated and system prints a non user friendly error message.
Ex:-Take a look at the below system generated exception
An exception generated by the system is given below
Exception in thread "main" java.lang.ArithmeticException: / by zero at
ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo : The class name
main : The method name
ExceptionDemo.java : The filename
java:5 : Line number
Hierarchy of Java Exception classes

Common scenarios where exceptions may occur


There are given some scenarios where unchecked exceptions can occur. They are as follows:
1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException

2) Scenario where NullPointerException occurs


If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) Scenario where NumberFormatException occurs
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a
string variable that have characters, converting this variable into digit will occur
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

4) Scenario where ArrayIndexOutOfBoundsException occurs


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

a[10]=50; //ArrayIndexOutOfBoundsException

Java Exception Handling Keywords


There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw

Try Catch in Java – Exception handling

What is Try Block?


The try block contains a block of program statements within which an exception might occur. A
try block is always followed by a catch block, which handles the exception that occurs in
associated try block. A try block must followed by a Catch block or Finally block or both.
Syntax of try block
try{
//statements that may cause an exception
}
What is Catch Block?
A catch block must be associated with a try block. The corresponding catch block executes if an
exception of a particular type occurs within the try block. For example if an arithmetic exception
occurs in try block then the statements enclosed in catch block for arithmetic exception executes.
Syntax of try catch in java
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
Flow of try catch block
1. If an exception occurs in try block then the control of execution is passed to the catch
block from try block. The exception is caught up by the corresponding catch block. A
single try block can have multiple catch statements associated with it, but each catch
block can be defined for only one exception class. The program can also contain nested
try-catch-finally blocks.
2. After the execution of all the try blocks, the code inside the finally block executes. It is
not mandatory to include a finally block at all, but if you do, it will run regardless of
whether an exception was thrown and handled by the try and catch blocks.
An example of Try catch in Java
class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
// Try block to handle code that may cause exception
num1 = 0;
num2 = 62 / num1;
System.out.println("Try block message");
} catch (ArithmeticException e) {
// This block is to catch divide-by-zero error
System.out.println("Error: Don't divide a number by zero");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
Output:
Error: Don't divide a number by zero
I'm out of try-catch block in Java.
Multiple catch blocks in Java
1. A try block can have any number of catch blocks.
2. A catch block that is written for catching the class Exception can catch all other exceptions
Syntax:
catch(Exception e){
//This catch block catches all the exceptions
}
3. If multiple catch blocks are present in a program then the above mentioned catch block should
be placed at the last as per the exception handling best practices.
4. If the try block is not throwing any exception, the catch block will be completely ignored and
the program continues.
5. If the try block throws an exception, the appropriate catch block (if one exists) will catch it
–catch(ArithmeticException e) is a catch block that can catch ArithmeticException
–catch(NullPointerException e) is a catch block that can catch NullPointerException
6. All the statements in the catch block will be executed and then the program continues.
Example of Multiple catch blocks
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Output:
Warning: ArithmeticException
Out of try-catch block...
In the above example there are multiple catch blocks and these catch blocks executes
sequentially when an exception occurs in try block. Which means if you put the last catch block
( catch(Exception e)) at the first place, just after try block then in case of any exception this
block will execute as it has the ability to handle all exceptions. This catch block should be placed
at the last to avoid such situations.
ava finally block
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block must be followed by try or catch block.
Why use java finally
 Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.

Usage of Java finally


Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}

Output:finally block is always executed


Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}

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


finally block is always executed
rest of the code...

User defined exception in java


Exception Handling
User defined exceptions in java are also known as Custom exceptions. Most of the times when
we are developing an application in java, we often feel a need to create and throw our own
exceptions. These exceptions are known as User defined or Custom exceptions
Define an Exception called “NoMatchException” that is thrown when a string is not equal
to “India”. Write a program that uses this exception.
class NoMatchException extends Exception
{

NoMatchException(String message)
{
Super(message);
}

}
class NoMatch
{
public static void main(String args[])
{
try
{
if(args[0].compareTo("India") == 0)
{
System.out.println("\nString is equal to 'India'.");
}
else
{
throw new NoMatchException("Arguments is not equal to 'India'.");
}
}
catch(NoMatchException e)
{
System.out.println("\nException Caught: ");
System.out.println(e.getMessage());
}
}
}

Unit – V
Applet and Graphics Programming
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
 Plugin is required at client browser to execute applet.
Lifecycle of Java Applet
These are the different stages involved in the life cycle of an applet:
 Initialization State
 Running state
 Idle or stopped state
 Dead state

Initialization State : This state is the first state of the applet life cycle. An applet is created by
the method init(). This method initializes the created applet. It is Called exactly once in an
applet's life when applet is first loaded, which is after object creation, e.g. when the browser
visits the web page for the first time.Used to read applet parameters, start downloading any other
images or media files, etc.
Running State : This state is the second stage of the applet life cycle. This state comes when
start() method is called. Called at least once.Called when an applet is started or restarted, i.e.,
whenever the browser visits the web page.
Idle or Stopped State : This state is the third stage of the applet life cycle. This state comes
when stop() method is called implicitly or explicitly.stop() method is called implicitly. It is called
at least once when the browser leaves the web page when we move from one page to another.
This method is called only in the running state and can be called any number of times.
Dead State : This state is the fourth stage of the applet life cycle. This state comes when
destroy() method is called. In this state the applet is completely removed from the memory. It
called exactly once when the browser unloads the applet.Used to perform any final clean-up. It
occurs only once in the life cycle.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome",150,150);
}

}
Note: class must be public because its object is created by Java Plugin software that resides on
the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it
is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code="First.class" width="300" height="300">
</applet>
*/

public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome to applet",150,150);
}
}
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java

Displaying Graphics in Applet


java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
7. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
8. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
9. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.

1. Draw a simple string


In this program, we show how to design a string in graphics programming.
import java.awt.*;
import java.applet.Applet;

/*
<applet code="GrpStringEx.class" width="400" height="400">
</applet
*/
public class GrpStringEx extends Applet
{
public void paint(Graphics grp)
{
grp.setColor(Color.blue);
grp.drawString("welcome-to-appletworld-in-java", 150, 150);
}
}

Output
To execute our code by the appletviewer tool, write in the command prompt:
javac GrpStringEx.java
appletviewer GrpStringEx.java

2. Draw a rectangle
In this example, we draw a simple rectangle.
import java.awt.*;
import java.applet.Applet;
/*
<applet code="GrpRectEx.class" width="400" height="400">
</applet
*/
public class GrpRectEx extends Applet
{
public void paint(Graphics grp)
{
grp.setColor(Color.blue);
grp.drawRect(100,50,150,150);
}
}

Output

3. Fill color in rectangle


In this example, we fill in the color of our rectangle usnig the grp.fillRect method.
import java.awt.*;
import java.applet.Applet;
/*
<applet code="GrpRectEx.class" width="400" height="400">
</applet
*/

public class GrpRectEx extends Applet


{
public void paint(Graphics grp)
{
grp.setColor(Color.blue);
grp.drawRect(100,50,150,150);
grp.fillRect(100,50,150,150);
}
}
Output

4. Draw an oval and an arc


In this example, we create an oval and an arc with specified co-ordinates.
import java.awt.*;
import java.applet.Applet;
/*
<applet code="GrpOvalEx.class" width="400" height="400">
</applet
*/

public class GrpOvalEx extends Applet


{
public void paint(Graphics grp)
{
grp.setColor(Color.blue);
grp.drawOval(100,50,150,150);
grp.drawArc(100,150,150,150,0,180);
}
}
Output

5. fill color in oval and arc


In this example, we fill an oval and an arc with a color using the fillOval and fillArc methods.
import java.awt.*;
import java.applet.Applet;
/*
<applet code="GrpOvalEx.class" width="400" height="400">
</applet
*/

public class GrpOvalEx extends Applet


{
public void paint(Graphics grp)
{
grp.setColor(Color.blue);
grp.fillOval(100,50,150,150);
grp.setColor(Color.red);
grp.fillArc(100,150,150,150,0,180);
}
}
Output

6. Draw a line
In this example, we draw a simple line with specified co-ordinates.
import java.awt.*;
import java.applet.Applet;
/*
<applet code="GrpLineEx.class" width="400" height="400">
</applet
*/

public class GrpLineEx extends Applet


{
public void paint(Graphics grp)
{
grp.setColor(Color.blue);
grp.drawLine(50,30,400,30);
}
}
Output

Passing parameters to applets


We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter(). Syntax:
public String getParameter(String parameterName)
Following program shows how to pass and read parameters using applet:
import java.awt.*;
import java.applet.*;
public class ParameterExample extends Applet
{
// We'll save the first HTM parameter as a String
String parameter1;
// the second one we will use as an integer
int parameter2;
// third one too
int parameter3;
// we'll add param2 to param2
int result;
public void init()
{
// This method will get the specified parameter's value
// out of the HTML code that is calling the applet.
parameter1 = getParameter("param1");
// Since those are read as text we need to transform them
// to integers to be able to count with them.
parameter2 = Integer.parseInt(getParameter("param2"));
parameter3 = Integer.parseInt(getParameter("param3"));
result = parameter2 + parameter3;
}
public void paint(Graphics g)
{
// Shows what was in the HTML param code.
g.drawString("Parameter 1 is: " + parameter1,20,20);
g.drawString("Parameter 2 is: " + parameter2,20,40);
g.drawString("Parameter 3 is: " + parameter3,20,60);
g.drawString("Parameter 2 + parameter 3 is: " + result,20,80);
}
}
/*
<APPLET CODE="ParameterExample" WIDTH=200 HEIGHT=100>
<param name="param1" value="Hello">
<param name="param2" value="14">
<param name="param3" value="2">
</APPLET>

*/
Output
Display Numerical Values in Applet
In applets, we can display numerical values by first converting them into strings and then using
the drawstring() method of Graphics class we can do this easily by calling the valueOf() Method
of String class. Let us consider an example:
import java.awt.*;
import java.applet.*;
/*<APPLET Code="DisplayNumericalValues.class" Width=400 Height=300>
</APPLET>
*/
public class DisplayNumericalValues extends Applet
{
public void paint(Graphics g)
{
int val1 = 10;
int val2 = 20;
int sum = val1 + val2;
String str_sum = "Sum="+String.valueOf(sum);
g.drawString(str_sum,100,200);
}
}
Output
Getting Input from the User in Java Applet
Applets work in graphical environment. Therefore applets treat input as text strings. We must
first create an area of the screen in which user can type and edit input items. We can do this by
using the TextField class of the applet package. The values of the fields can be given even editer
after the creation of input fields. Next step is to retrieve the items from the fields for display of
calculations.

For any kinds of computation on the input field, we must convert it to the right form and the
resuls again converted back to strings for display.
Let us consider an example
import java.awt.*;
import java.applet.*;
/*<APPLET Code="GettingInputfromtheUser.class" Width=400 Height=300>
</APPLET>*/
public class GettingInputfromtheUser extends Applet
{
TextField t1, t2;
public void init()
{
t1 = new TextField(10);
t2 = new TextField(10);

add(t1);
add(t2);

t1.setText("0");
t2.setText("0");
}
public void paint(Graphics g)
{
int a=0,b=0,c=0;
String str1,str2,str;

g.drawString("Enter the number in each box",10,50);

try
{
str1=t1.getText();
a=Integer.parseInt(str1);

str2=t2.getText();
b=Integer.parseInt(str2);
}
catch(Exception e)
{
}
c=a+b;
str=String.valueOf(c);

g.drawString("Sum is",10,15);
g.drawString(str,100,75);
}
}
Output

Event Handling

Any program that uses GUI (graphical user interface) such as Java application written for
windows, is event driven. Event describes the change of state of any object. Example : Pressing
a button, Entering a character in Textbox.

Components of Event Handling

Event handling has three main components,

 Events : An event is a change of state of an object.


 Events Source : Event source is an object that generates an event.
 Listeners : A listener is an object that listens to the event. A listener gets notified when an event
occurs.
Important Event Classe and Interface
Event Classe Description Listener Interface

generated when button is pressed, menu-item is selected, list-item


ActionEvent ActionListener
is double clicked

generated when mouse is dragged, moved,clicked,pressed or


MouseEvent MouseListener
released also when the enters or exit a component

KeyEvent generated when input is received from keyboard KeyListener

ItemEvent generated when check-box or list item is clicked ItemListener

TextEvent generated when value of textarea or textfield is changed TextListener

MouseEvent generated when mouse wheel is moved MouseMotionListener

Example of Event Handling


import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/* < applet code="Test.class" width=300, height=100 >


</applet>*/
public class Test extends Applet implements KeyListener
{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
UNIT – VI
Managing Input / Output Files in Java

Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because
it's like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
Let's see the code to get input from console.
1. int i=System.in.read();//returns ASCII code of 1st character
2. System.out.println((char)i);//will print the character

IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to
make input and output operation in java. In general, a stream means continuous flow of data.
Streams are clean way to deal with input/output without having every part of your code
understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of characters.
Character stream uses Unicode and therefore can be internationalized.

Byte Stream Classes


Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream
and OutputStream.
These two abstract classes have several concrete classes that handle various devices such as disk
files, network connection etc.

Some important Byte stream classes.

Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

DataInputStream Contains method for reading java standard datatype

DataOutputStream An output stream that contain method for writing java standard data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method

These classes define several key methods. Two most important are
1. read() : reads byte of data.
2. write() : Writes byte of data.

Character Stream Classes


Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer.
These two abstract classes have several concrete classes that handle unicode character.
Some important Charcter stream classes.

Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output

Let's understand working of Java OutputStream and InputStream by the figure given below.
OutputStream class
OutputStream class is an abstract class.It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
Commonly used methods of OutputStream class

Method Description

1) public void write(int)throws IOException: is used to write a byte to the current output stream.

2) public void write(byte[])throws is used to write an array of byte to the current output
IOException: stream.

3) public void flush()throws IOException: flushes the current output stream.

4) public void close()throws IOException: is used to close the current output stream.

InputStream class
InputStream class is an abstract class.It is the superclass of all classes representing an input
stream of bytes.
Commonly used methods of InputStream class

Method Description

1) public abstract int read()throws reads the next byte of data from the input stream.It returns -1 at
IOException: the end of file.

2) public int available()throws returns an estimate of the number of bytes that can be read
IOException: from the current input stream.

3) public void close()throws


is used to close the current input stream.
IOException:

FileInputStream and FileOutputStream (File


Handling)
In Java, FileInputStream and FileOutputStream classes are used to read and write data in file. In
another words, they are used for file handling in java.
Java FileOutputStream class
Java FileOutputStream is an output stream for writing data to a file.
If you have to write primitive values then use FileOutputStream.Instead, for character-oriented
data, prefer FileWriter.But you can write byte-oriented as well as character-oriented data.
Example of Java FileOutputStream class
import java.io.*;
class Test{
public static void main(String args[]){
try{
FileOutputstream fout=new FileOutputStream("abc.txt");
String s="Sachin Tendulkar is my favourite player";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){system.out.println(e);}
}
}
Output:success...
Java FileInputStream class
Java FileInputStream class obtains input bytes from a file.It is used for reading streams of raw
bytes such as image data. For reading streams of characters, consider using FileReader.
It should be used to read byte-oriented data for example to read image, audio, video etc.
Example of FileInputStream class
import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("abc.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.println((char)i);
}
fin.close();
}catch(Exception e){system.out.println(e);}
}
}
Output:Sachin is my favourite player.
Example of Reading the data of current java file and writing it into another file
We can read the data of any file using the FileInputStream class whether it is java file, image
file, video file etc. In this example, we are reading the data of C.java file and writing it into
another file M.java.
import java.io.*;
class C{
public static void main(String args[])throws Exception{
FileInputStream fin=new FileInputStream("C.java");
FileOutputStream fout=new FileOutputStream("M.java");
int i=0;
while((i=fin.read())!=-1){
fout.write((byte)i);
}
fin.close();
}
}

Java SequenceInputStream class


Java SequenceInputStream class is used to read data from multiple streams. It reads data of
streams one by one.
Constructors of SequenceInputStream class:

Constructor Description

1) SequenceInputStream(InputStream s1, creates a new input stream by reading the data of two
InputStream s2) input stream in order, first s1 and then s2.

creates a new input stream by reading the data of an


2) SequenceInputStream(Enumeration e)
enumeration whose type is InputStream.

Simple example of SequenceInputStream class


In this example, we are printing the data of two files f1.txt and f2.txt.
import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
FileinputStream fin1=new FileinputStream("f1.txt");
FileinputStream fin2=new FileinputStream("f2.txt");

SequenceinputStream sis=new SequenceinputStream(fin1,fin2);


int i;
while((i=sis.read())!=-1){
System.out.println((char)i);
}
sis.close();
fin1.close();
fin2.close();
}
}

Example of SequenceInputStream that reads the data from two files


In this example, we are writing the data of two files f1.txt and f2.txt into another file named
f3.txt.
//reading data of 2 files and writing it into one file

import java.io.*;
class Simple{
public static void main(String args[])throws Exception{

FileinputStream fin1=new FileinputStream("f1.txt");


FileinputStream fin2=new FileinputStream("f2.txt");

FileOutputStream fout=new FileOutputStream("f3.txt");

SequenceinputStream sis=new SequenceinputStream(fin1,fin2);


int i;
while((i.sisread())!=-1)
{
fout.write(i);
}
sis.close();
fout.close();
fin.close();
fin.close();

}
}

Java BufferedOutputStream and


BufferedInputStream

Java BufferedOutputStream class


Java BufferedOutputStream class uses an internal buffer to store data. It adds more efficiency
than to write data directly into a stream. So, it makes the performance fast.

Example of BufferedOutputStream class:


In this example, we are writing the textual information in the BufferedOutputStream object
which is connected to the FileOutputStream object. The flush() flushes the data of one stream
and send it into another. It is required if you have connected the one stream with another.
import java.io.*;
class Test{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("f1.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Sachin is my favourite player";
byte b[]=s.getBytes();
bout.write(b);

bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Output:
success...

Java BufferedInputStream class


Java BufferedInputStream class is used to read information from stream. It internally uses buffer
mechanism to make the performance fast.
Example of Java BufferedInputStream
Let's see the simple example to read data of file using BufferedInputStream.
import java.io.*;
class SimpleRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("f1.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){

System.out.println((char)i);
}
bin.close();
fin.close();
}catch(Exception e){system.out.println(e);}
}
}
Output:
Sachin is my favourite player
Java FileWriter and FileReader (File
Handling in java)
Java FileWriter and FileReader classes are used to write and read data from text files. These are
character-oriented classes, used for file handling in java.
Java has suggested not to use the FileInputStream and FileOutputStream classes if you have to
read and write the textual information.

Java FileWriter class


Java FileWriter class is used to write character-oriented data to the file.
Constructors of FileWriter class

Constructor Description

FileWriter(String file) creates a new file. It gets file name in string.

FileWriter(File file) creates a new file. It gets file name in File object.

Methods of FileWriter class

Method Description

1) public void write(String text) writes the string into FileWriter.

2) public void write(char c) writes the char into FileWriter.

3) public void write(char[] c) writes char array into FileWriter.

4) public void flush() flushes the data of FileWriter.

5) public void close() closes FileWriter.

Java FileWriter Example


In this example, we are writing the data in the file abc.txt.
import java.io.*;
class Simple{
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("abc.txt");
fw.write("my name is sachin");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("success");
}
}
Output:
success...

Java FileReader class


Java FileReader class is used to read data from the file. It returns data in byte format like
FileInputStream class.
Constructors of FileWriter class

Constructor Description

FileReader(String It gets filename in string. It opens the given file in read mode. If file doesn't exist, it
file) throws FileNotFoundException.

It gets filename in file instance. It opens the given file in read mode. If file doesn't
FileReader(File file)
exist, it throws FileNotFoundException.

Methods of FileReader class

Method Description

1) public int read() returns a character in ASCII form. It returns -1 at the end of file.

2) public void close() closes FileReader.

Java FileReader Example


In this example, we are reading the data from the file abc.txt file.
import java.io.*;
class Simple{
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("abc.txt");
int i;
while((i=fr.read())!=-1)
System.out.println((char)i);
fr.close();
}
}
Output:
my name is sachin

You might also like