Java - Material (Unit - 1 To 4)
Java - Material (Unit - 1 To 4)
UNIT-I:
Introduction to Java: History of Java, Java features, JVM architecture, Classes and objects, Program
structure, methods, Passing arguments through command line.
Building Blocks of Java: Variables, primitive data types, identifiers, literals, Operators, expressions,
primitive type conversion and casting, flow of control.
UNIT-II:
Introduction to Classes: Class declaration, creating objects, constructors, Method Overloading, constructor
overloading, garbage collector, importance of static keyword and examples, this keyword, Arrays, Strings,
nested classes.
Inheritance & Interfaces: Inheritance- types of inheritance, super keyword, final keyword, overriding.
Interfaces- Defining an interface, Implementing interfaces through classes, Multiple inheritance through
interfaces, abstract class.
Packages: Creating the packages, using packages, importance of CLASSPATH, Access Specifiers, java.
lang package.
UNIT-III:
Exception Handling: Exception handling, importance of try, catch, throw throws and finally block, user
defined exceptions.
Multithreading: Introduction, thread life cycle, creation of threads, thread priorities, thread
synchronization, communication between threads.
UNIT-IV:
Input / Output: Byte Streams and Character Streams, Predefined Streams, Reading Console inputs-
Reading characters, Reading Strings, Reading and writing Files.
Event Handling: Event delegation model, sources of event, Event Listeners, adapter classes, inner classes.
UNIT-V:
AWT: Introduction, components and containers, Button, Label, Checkbox, Radio Buttons, List Boxes,
Choice Boxes, Container class, Layouts, Menu and Scrollbar.
Swing: Introduction, Swing Components- J Frame, J Panel, Layout Managers, J List, J Table, J Tree, Dialog
Box.
Prepared By
M. Srinu,
Dept. of CSE,
Aditya Engineering College,
Surampalem.
Non-procedural Approach:
It is a language, which doesn’t support any structured or systematic way in its execution. It will
increase the complexity. Debugging is very difficult because it will not support procedure-orientation or
modularity.
Procedure-oriented Approach
:
Divide the program into different sections and each and every section will do some specific task.
That section is called module or procedure or a function. Whatever the set of statements which are
repeated number of times will be placed into a module will decrease the
1. Complexity
2. Memory wastage
3. Retyping time
4. Compilation time
It follows top-down approach
It contains set of steps, which are required to develop a project
1 Planning
2 Analysis
3 Designing
4 Coding
5 Debugging
6 Testing
7 Documentation
8 Maintenance
Drawbacks of Procedure Oriented Approach: -
To overcome the above drawbacks, we have to introduce Object-Oriented approach. It will support
both procedure-oriented and object oriented methodologies.
Every object must have set of properties to express its behaviour and sets of
actions are used to change the behaviour while modifying the properties so that more than 1 object may
have set of properties and actions commonly, without repeating these properties and actions common to
more than 1 object in a single unit to maintain the reusability. That unit is called class.
Class:
Class is a template, which contains the set of properties and actions to specify the behaviour of objects
and provide security to the data. It will give an abstract view of given real life entity to create model.
Object:
It is a communicate entity to provide the communication among set of classes. It will store the state
of a class at a particular time.
Instance:
It is a state of a class at a particular time but it cannot preserve that state for future use. But in the
case of objects, they are the preserving mechanisms to maintain the state for future use.
Data abstraction:
Whatever the set of properties, those are able to differentiate from one object to another object; we
have to extract these properties, by that create a model to simulate the real – time entity. This process of data
extraction is called data abstraction. It will reduce the complexity and memory wastage.
Data encapsulation:
Bind the data and hide the data in a single unit to provide the security and to reduce the accidental
modifications is called data encapsulation. It hides the complexity and gives the simplicity to end-users.
Inheritance:
It is a process of extracting some of the properties from the existing class by that creating a new class
and adds some more features, so that new class contains both the features. This is called reusability means
without modifying the existing properties uses them again and again.
Data polymorphism:
It is the process of assigning more than one task to a single entity so that the entity will work
differently at different situations according to the user requirement. It will introduce overloading so that
there is no need to define different entities for different purposes. A single entity is overloaded with different
behaviours.
Types of languages:
High-level language:
The human being only understands it. Most of all high-level languages will use mediators. So
execution time will be increased because of translation. They will not provide any direct interaction to the
hardware so that searching time and storing time will be increased. But they are providing flexibility in their
development.
Assembly language:
It is a symbolic language and these symbols are called mnemonics. The instructions directly interact
with hardware or memory. Even though there is need of translation, it will take less time when compared to
high – level language so it increase the execution speed.
Main drawback of assembly language is platform dependency. Whenever you write a program
related to particular hardware or operating system. It will not work on another hardware or operating system
so that there is a need to develop same program number of times on different platforms. It will increase the
cost and time of development.
It is an expert –friendly language means it doesn’t have any instructions for frequently used tasks so
that we have to develop our own instructions according to our requirement. Since normal developers cannot
develop programs by using this language.
Low-level language:
The machines only understand it. This is fully in ones and zeroes.
Java Buzzwords
1) Simple:
Java is simple to develop for large-scale application like window based or Internet based.
2) Architectural neutral:
It can run in any type of hardware architecture.
3) Portable:
It can run on any type of operating system.
4) Platform Independent:
If we write java program once, we can run on any platform. i.e java follows Write Once Run
Anywhere principle (WORA).
5) Robust:
In some cases, there is a change of some run time errors to occur in the case of program execution.
They will bad to abnormal program termination, so that the data and application may be lost. Such
type of errors is called exceptions.
If any language handling these exceptions in a systematic way then those languages will be
treated as strictly written languages.
Any application developed by using these types of languages is called robust applications.
They will provide safety and security to applications they will provide safety and security to
application and data
6) Object Oriented:
Java is a purely object oriented approach. It supports all the concepts oops such as data abstraction,
encapsulation, polymorphism, and inheritance.
7) Secure:
Java provides an excellent security from unauthorized access and provides firewall facility from the
viruses.
8) Dynamic:
In java, every object will be allocated dynamic to reduce the memory wastage. In the case of
Internet applications, reduction in the memory wastage will reduce the transmission time and
increases the down loading speed and transmission speed.
9) Interpreted:
In any language, language translation is handled by the compilers. But in the case of java, program is
first compiled by the java compiler. Then it will generate a code called byte code.
This byte code is a universal code, which can be understood, by any type of JVMs (java
virtual machine) so it will interpret that byte code according to the platform on which it was installed.
This feature makes the program as platform independent. But JVMs are platform dependant.
10) Distributed:
Java is a net based application so that we have to share the data and application a among different
users. This makes the code as reusable.
11) High performance:
Even though more than 1 user is passing their quest at a time, system is able to respond within a
reasonable amount of time. This feature java application is increasing the no. of subscribers to java
environment.
12) Multi-Threaded:
To do more than 1 task simultaneously, we have to place each and every logic of a main program in
different threads. Thread is a unit of execution. It will increase the utilization of CPU.
class syntax:
class <class-name>
{ data
Private members – methods
Public members
Protected members
No modifier members
}
class contains following types of access specifies.
1. private:
These members are accessible only with in the class.
2. public:
These members can be accessed anywhere.
3. protected:
These members can be accessed with in the class and within its child classes of
same package and from other packages also.
4. No modifier:
In Java, if you do not specify any access specified it will not be treated as private.
The scope of these variables is within the package
class Sample
{
public static void main (String args[])
{
System.out.println (“Java Demo”);
}
}
Commandline Arguments:
The arguments which are passing from command prompt at the time program execution are called command
line arguments.
The main objective of command line arguments are we can customize the behaviour of the main().
class sample
{
public static void main (String args [])
{
System.out.println (“Total Args:”+args.length);
System.out.println (“Given Args”);
for (int i=0; i<args.length;i++)
System.out.println (args[i]);
}
}
Compile: javac sample.java
Run: java Run 10 20 30 40
Expected Output:
Total Args:4
Given Args
10
20
30
40
“+” Operator overloading used to concatenate the value to string.
static depends on class
Normal depends on objects
Example:
class Sample
{
public static void main (String args[])
{
int x=Integer.parseInt(arg[0]); //Converts Given String Integer type.
int y=integer. parseInt (args[i]);
int z=x+y;
System.out.println (“Sum:”+z);
}
}
Run c:\> java Sample 10 20
Sum: 30
new operator.
This is equivalent to malloc() but there is no need of typecasting and size. For normal functions we have
create objects in main to access them. Object stores the address just like pointer in C.
class Sample
{
void wish ()
{
System.out.print in (“have a nice day”);
}
public static void main (String args [])
{
Sample s=new Sample();
s.wish ();
}
}
To call normal functions in normal functions, we do not need objects if they are in same class.
class Sample
{
void wish ()
{
System.out.println (“Test Fun”);
}
void test()
{
wish ();
}
si=(float)*p*r/100;
System.out.println (“Simple Interest: ”+si);
}
}
readLine () function is available in java.io.BufferedReader class
In the System.out.println()
System is a class in java.lang package.
“out” is an Object to the PrintStream.
Array
An array is an indexed collection of fixed number of homogeneous data elements.
The main advantage of arrays is we can represent multiple values with the same name so that readability of
the code will be improved.
But the main disadvantage of arrays is:
Fixed in size that is once we created an array there is no chance of increasing or decreasing the size based on
our requirement that is to use arrays concept compulsory we should know the size in advance which may not
possible always.
We can resolve this problem by using collections.
Single dimensional array declaration:
Example:
int[] a; //recommended to use because name is clearly separated from the type
int []a;
int a[];
At the time of declaration we can't specify the size otherwise we will get compile time error.
Example:
int[] a; //valid
int[5] a; //invalid
Every array in java is an object hence we can create by using new operator.
Example:
int[] a=new int[3];
Diagram:
Example:
import java.io.*;
class Array
{
public static void main (String args[])throws Exception
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader (isr);
int x[],i,n;
System .out.println (“Enter no.of elements:”);
n = Integer parseInt(br.readLine());
x = new int[n];
In java multidimensional arrays are implemented as array of arrays approach but not matrix form. The main
advantage of this approach is to improve memory utilization.
Example1:
int[][] a=new int[2][];
a[0]=new int[3];
a[1]=new int[2];
Diagram:
Example 2:
int[][][] a=new int[2][][];
a[0]=new int[3][];
a[0][0]=new int[1];
a[0][1]=new int[2];
a[0][2]=new int[3];
a[1]=new int[2][2];
Diagram:
Whenever we are creating an array every element is initialized with default value automatically.
Example3:
int[] a=new int[3];
System.out.println(a);//[I@3e25a5
System.out.println(a[0]);//0
import java.io.*;
class Matrix
{
public static void main (String args [])throws Exception
{
int x[][],i,j,m,n;
BufferedReader b = new BufferedReader (new InputStreamReader (System. in));
System.out.printin(“enter no.of rows &columns”);
m = Integer.parseInt (b.readLine());
m = Integer. parseInt (b.readLine ());
x =new int [m] [n];
System.out.printin (“enter”+(m*n) “elements”);
for (i = 0;i<m;i++)
for (j = 0;j<n;j++)
x[i][j] = Integer.parseInt (b.readLine());
Constructor
Object creation is not enough compulsory we should perform initialization then only the object is in a
position to provide the response properly. Whenever we are creating an object some piece of the code will be
executed automatically to perform initialization of an object this piece of the code is nothing but constructor.
Hence the main objective of constructor is to perform initialization of an object.
Constructor is a special type of member function. It is used to initialize the member variables at the time of
creating objects.
Rules:
1. Constructor name is always same as class-name
2. Constructor will take arguments but will not return any value.
3. Even though it is not returning the value, we should not use void before constructor name.
4. We can define more than 1 constructor with in a class.
Types of constructor:
1. Default constructor: - It will not take arguments.
2. Parameterized constructor: It will take arguments.
3. Copy constructor: It will copy the values of one object into other object.
Destructors:
It is also a special type of member function, which is used to destroy the objects, which are
constructed by the constructor.
Note: Java does not support destructors. But it supports garbage collectors. It is a special type of program
which will destroy the objects which are not referred for long time the time value which is used for garbage
collection is called lease value.
Whenever any object will not be referred within that lease time it will automatically garbage
collected by systems default garbage collector.
Example1:
class Test
{
public Test() // Default Constructor
{
System.out.println(“Default Constructor”);
System.out.println(“Welcome to Guest”);
}
public Test(String name) // Parameterized Constructor
{
System.out.println(“Parameterized Constructor”);
System.out.println(“Welcome to “+name);
}
Public static void main(String args[])
{
Test t1=new Test(); // called Default Constructor
Test t2=new Test(“Srinu”); // called Parameterized Constructor
}
}
Example2:
class Student
{
String name;
int rollno;
Student(String name,int rollno) //Constructor
{
this.name=name;
this.rollno=rollno;
}
public static void main(String[] args)
{
Student s1=new Student("vijayabhaskar",101);
Student s2=new Student("bhaskar",102);
}
}
Example3:
class demo
{
int a,b;
demo()
{
a=10;
b=20;
}
public void print()
{
System.out.print("a= "+a+" b = "+b);
}
}
class one
{
public static void main(String args[])
{
demo obj1=new demo();
demo obj2=obj1;
obj1.a+=1;
obj1.b+=1;
System.out.println("values of obj1: ");
obj1.print();
System.out.println("\nvalues of obj2: ");
obj2.print();
}
}
Output:
D:\java_prog>java one
values of obj1:
a= 11 b = 21
values of obj2:
a= 11 b = 21
Overloaded Constructors
A class can contain more than one constructor and all these constructors having the same name but different
arguments and hence these constructors are considered as overloaded constructors.
Example1:
class Test
{
int x;
public Test ()
{
System.out.println("Default Constructor");
x = 1;
}
public Test (int v)
{
System.out.println("Parameterized constructor");
x = v;
}
public Test (Test t)
{
x = t.x;
System.out.println("Copy Consturctor");
}
void show()
{
System.out.println("X:"+x);
}
public static void main (String args [])
{
Test t1 = new test (); // default
Test t2 = new test (13); // parameterized
Test t3 = new test (t2); // copy
T1.show (); // 1
T2. show (); // 13
T3.show (); // 13
}
}
Example2: //Stacks using Constructors
class Stacks
{ int x[], top, size;
public Stacks ()
{ top = -1;
size = 5;
x = new int [size];
}
public Stacks (int s)
{ top = -1;
size = s;
x = new int [s];
}
int getSize ()
{
return size ;
}
void pop()
{
if(top<0)
System.out.println("Stack is Underflow");
else
{
System.out.println ("Deleted Ele:" + x[top]);
top--;
}
}
void show ()
{
if (top>= 0)
{
for (int i =top; i >= 0; i--)
System.out.println(x[I]);
}
}
this Object
It is an implicit, dynamic, generic object to store the address, which is in the currently executing
object. It is used to differentiate local variable with member variable, if both of these variables having same
name. We have to place “this” keyword before the member variable name.
Eg:
class Stack
{
int x[],top, size.
public stack (int size)
{
top = -1;
this .size = size;
x = new int [size]
}
}
Note:
In java, call by reference cannot be applied to the normal variables. Objects cannot use call by value.
Whenever you pass object into a function, it will always be treated as call by reference.
Static Members
Whenever we declare some properties within a class, if we want to access those properties we have
to create objects to that class. Such type of properties is called normal property. For those properties values
are different from one object to another object but properties are common. In some of the cases, properties as
well as their values are common to any object. Such types of properties are called “Static Properties”. They
are independent from objects. So we cannot use objects to call those properties. We have to use class name
to invoke static members. ”this” object cannot be applied to the static members.
import java.io. *;
class Emp
{
int eno;
String ename;
float sal;
static int totsal;
static BufferedReader b = new BufferedReader (new InputStreamReader(System.in));
void getemp ()throws Exception
{
System.out.println ("Enter eno, ename, sal:");
eno = Integer.parseInt(Emp.b.readLine());
ename = Emp.b.readLine ();
sal = Float.parseFloat (Emp.b.readLine ());
Emp.totsal += sal;
}
void showEmp ()
{
System.out.println("Eno:"+eno);
System.out.println ("Name:"+ename);
System.out.println("Sal:"+ sal);
}
static void showTotal ()
{
System.out.println ("Total:"+totsal);
}
public static void main (string args [])throws Exception
{
int i,n;
System.out.println ("Enter no. Of Emps");
n = Integer.parseInt(b.readLine ());
Emp e[]=new Emp [n];
for (i = 0; i<n; i++)
{
e[i] = new Emp();
e[i].getEmp();
}
System.out.println("Given Emps:");
for (i = 0 ;i<n; i++)
e[i]. showEmp();
showTotal ();
}
}
Method Overloading
If a class have multiple methods with same name but with different parameters list, it is known as Method
Overloading.
Parameters lists should differ in either,
Number of parameters.
Data type of parameters.
Sequence of data type of parameters.
1. Two methods are said to be overload if and only if both having the same name but different argument
types.
2. In 'C' language we can't take 2 methods with the same name and different types. If there is a change in
argument type compulsory we should go for new method name.
Example :
5. Having the same name and different argument types is called method overloading.
6. All these methods are considered as overloaded methods.
7. Having overloading concept in java reduces complexity of the programming.
Example:
Example:
class Test
{
public void methodOne()
{
System.out.println("no-arg method");
}
public void methodOne(int i)
{
System.out.println("int-arg method"); //overloaded methods
}
public void methodOne(double d)
{
System.out.println("double-arg method");
}
Example:
class Test
{
public void methodOne(int i)
{
System.out.println("int-arg method");
}
public void methodOne(float f) //overloaded methods
{
System.out.println("float-arg method");
}
public static void main(String[] args)
{
Test t=new Test();
//t.methodOne('a');//int-arg method
//t.methodOne(10l);//float-arg method
t.methodOne(10.5);//C.E:cannot find symbol
}
}
Inheritance
1 It is a process of extracting some of the properties of existing class and adds some more features, by
that create a new class.
2 The existing class is called super class or base class or parent class.
3 The new class is called derived class or sub-class or child class.
4 It introduces the concept of reusability, i.e. without modifying the existing properties use them again
& again
Types of Inheritances:
The common methods which are required for housing loan, vehicle loan, personal loan and education loan
we can define into a separate class in parent class loan. So that automatically these methods are available to
every child loan class.
Example:
class Loan {
//common methods which are required for any type of loan.
}
Example:
class Parent {
public void methodOne(){ }
}
Conclusion:
1. Whatever the parent has by default available to the child but whatever the child has by default not
available to the parent. Hence on the child reference we can call both parent and child class methods. But on
the parent reference we can call only methods available in the parent class and we can't call child specific
methods.
2. Parent class reference can be used to hold child class object but by using that reference we can call only
methods available in parent class and child specific methods we can't call.
3. Child class reference cannot be used to hold parent class object.
Example:
class Parent
{ int Currency1=20000;
String Gold="2KG";
String Properites="Building";
public void Take()
{
System.out.println("Currency+ Gold+Properties");
}
}
class Child extends Parent
{
public void own()
{
System.out.println("Own Properties");
}
public static void main(String args[])
{
Child c=new Child();
c.Take();
c.own();
System.out.println(c.Currency1);
System.out.println(c.Gold);
System.out.println(c.Properites);
}
}
Output:
D:\java_prog>java Child
Currency+ Gold+Properties
Own Properties
20000
2KG
Building
Example:
class A
{
private int x;
public int y;
protected int z;
int t;
public void set ()
{
x = 1;
x = 2;
z = 3;
t = 4;
}
}
class B extends A
{
void show ()
{
System.out.println("X:"+x);
// x cannot be accessed if in same directory
}
public static void main (string args [])
{
B bob = new B ();
bob.set();
bob.show ();
bob.x =10; // x cannot be accessed
bob.y = 20;
bob.z = 30;
bob.t = 40;
bob.show ();
}
}
super() vs this()
The 1st line inside every constructor should be either super() or this() if we are not writing anything
compiler will always generate super().
Case 1: We have to take super() (or) this() only in the 1st line of constructor. If we are taking anywhere else
we will get compile time error.
Example:
class Test
{
Test()
{
System.out.println("constructor");
super();
}
}
Output:
Compile time error.
Call to super must be first statement in constructor.
Case 2: We can use either super() (or) this() but not both simultaneously.
Example:
class Test
{
Test()
{
super();
this();
}
}
Output:
Compile time error.
Call to this must be first statement in constructor
Case 3: We can use super() (or) this() only inside constructor. If we are using anywhere else we will get
compile time error.
Example:
class Test
{
public void methodOne()
{
super();
}
}
Output:
Compile time error.
Call to super must be first statement in constructor
class A
{
A(){
System.out.println("A's no argument constructor");
}
A(String args){
System.out.println("A's one argument constructor");
}
}
class B extends A
{
B(){
this(""); // calling one arg constructor of class B
System.out.println("B's no argument constructor");
}
B(String args){
super(""); // calling one argument constructor of class A
System.out.println("B's one argument constructor");
}
}
Example:
class A
{
int x;
A(int p)
{
x=p;
}
void show()
{
System.out.println("Class A");
System.out.println("X= "+x);
}
}
class B extends A
{
int y;
B(int p,int q)
{
super(p);
y=q;
}
public void display()
{
System.out.println("Class B");
System.out.println("Y= "+y);
}
}
class C extends B
{
int z;
C(int p,int q,int r)
{
super(p,q);
z=r;
}
public void message()
{
System.out.println("Class C");
System.out.println("Z= "+z);
}
}
class Inheritance_Demo
{
public static void main(String args[])
{
C c=new C(10,20,30);
c.show();
c.display();
c.message();
}
}
Output:
D:\java_prog>java Inheritance_Demo
Class A
X= 10
Class B
Y= 20
Class C
Z= 30
Method Overriding
In inheritance, if both parent class and child class having same method signatures, then child class methods
will not allow the parent class methods to be executed. This is called “Member over-riding”.
1 This is used to execute its own behaviour by hiding the implementations of parent class.
2 But in some cases, there is a need to call parent class methods through child class. Then we have to
use ‘super’ keyword before the parent class member method.
3 It refers to the parent class up to 1 level back because java supports single-level inheritance only.
4 ‘super ‘keyword cannot be applied with in static methods.
5 We cannot use the objects to call super keyword.
Example1:
class A
{
int x;
A()
{
System.out.println("A Constructor called");
x=100;
}
}
class B extends A
{
int x;
B(int x)
{ super();
this.x=x;
}
public void show()
{
System.out.println("x from A class is: "+super.x);
System.out.println("x from B class is: "+x);
}
}
class super_Demo
{
public static void main(String args[])
{
B b=new B(200);
b.show();
}
}
Output:
D:\java_prog>java super_Demo
A Constructor called
x from A class is: 100
x from B class is: 200
Example2:
import java.io. *;
class Number
{
protected int x;
BufferedReader b = new BufferedReader (new InputStreamReader (System.in));
public void getNo ()throws Exception
{
System.out.println("Enter a No");
x = Integer.parseInt(b.readLine ());
}
void show ()
{
System.out.println("Decimal:"+x);
}
public static void main (String args [])
{
Number n = new number ();
Hexa h = new Hexa ();
Octal o = new Octal ();
n.getNo ();
h.getNo ();
o.getNo ();
n.show ();
h.show ();
o.show ();
}
}
class Hexa extends Number
{
void show ()
{
super.show ();
System.out.println("Hexa:"+Integer.toHexString(x));
}
}
class Octal extends Number
{
void show()
{
super.show();
System.out.println("Octal:" + Integer.toOctalString(x));
}
}
final keyword
1. To create constants in java. (Just like #define in c)
Eg: final float pi = 3.14f;
2. To avoid Member Over-Riding, we have to use final keyword before the parent class member
method.
class parent
{
final void show () { }
}
class child extends parent
{
void show () // error is displayed
{
}
}
3. To make a class as terminal class i.e. if you use final keyword before the class name, we cannot
create child class to that class.
}
class child extends parent //error can not be inherited
{
abstract class
1 In some of the cases, it is not possible to give definition to the some of the methods.
2 Even though you are trying to give definition to the methods, it is meaningless. Such types of methods
are called abstract methods.
3 The class, which contains these abstract methods, will be treated as abstract class.
4 The abstract methods only specify what to do, but not how to do. Abstract class may or may not have
non-abstract or concrete methods
5 We cannot create instance to the abstract class. But we can-create objects to the abstract class and it is
able to store instances of child class
6 So abstract classes are always treated as parent classes
7 We have to use ‘abstract’ keyword to make the class or method as abstract.
Example1:
import java.io.*;
abstract class Shape
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
float s1,s2,a;
final float pi=3.14f;
public abstract void get_Input()throws Exception;
public abstract void Cal_Area();
public void show_Area()
{
System.out.println("Area is:"+a);
}
}
class Rect extends Shape
{
public void get_Input()throws Exception
{
System.out.println("Enter L and B values");
s1=Float.parseFloat(br.readLine());
s2=Float.parseFloat(br.readLine());
}
public void Cal_Area()
{
a=s1*s2;
}
}
class Circle extends Shape
{
public void get_Input()throws Exception
{
System.out.println("Enter radius of the Circle");
s1=Float.parseFloat(br.readLine());
}
public void Cal_Area()
{
a=pi*s1*s1;
}
}
class Mainclass
{
public static void main(String args[])throws Exception
{
Shape s;
s=new Rect();
System.out.println("Rectangle:");
s.get_Input();
s.Cal_Area();
s.show_Area();
System.out.println("=============");
s=new Circle();
System.out.println("Circle:");
s.get_Input();
s.Cal_Area();
s.show_Area();
System.out.println("=============");
}
}
Example2:
abstract class Vehicle
{
public abstract int get_No_Wheels();
public abstract int seating_Capacity();
}
class Bike extends Vehicle
{
public int get_No_Wheels()
{
return 2;
}
public int seating_Capacity()
{
return 2;
}
}
class Auto extends Vehicle
{
public int get_No_Wheels()
{
return 3;
}
public int seating_Capacity()
{
return 4;
}
}
class Car extends Vehicle
{
public int get_No_Wheels()
{
return 4;
}
public int seating_Capacity()
{
return 5;
}
}
class Mainclass
{
public static void main(String args[])
{
Vehicle v;
int w,c;
v=new Bike();
System.out.println("==============");
System.out.println("Bike:");
w=v.get_No_Wheels();
c=v.seating_Capacity();
System.out.println("No of Wheels: "+w);
System.out.println("Seating Capacity: "+c);
System.out.println("==============");
v=new Auto();
System.out.println("==============");
System.out.println("Auto:");
w=v.get_No_Wheels();
c=v.seating_Capacity();
System.out.println("No of Wheels: "+w);
System.out.println("Seating Capacity: "+c);
System.out.println("==============");
v=new Car();
System.out.println("==============");
System.out.println("Car:");
w=v.get_No_Wheels();
c=v.seating_Capacity();
System.out.println("No of Wheels: "+w);
System.out.println("Seating Capacity: "+c);
System.out.println("==============");
}
}
Interface
1 Interface is a mechanism to provide the security to the server-side application by hiding some of the
services and gives only those services which are required to the end-users.
2 Interface itself is an abstract and all the methods in interface are public abstract by default
3 We cannot create instance to the interface but we can create objects to the interface
4 We have to implement the methods of the interface by using a class. The class which implements
interface must implement all the methods in the interface otherwise we have to make the class as abstract
5 Interface object is able to store the instance of the class, which implements it.
6 Interface is used to provide multiple inheritance type of mechanism so that we can implement more than
one interface by using a class.
7 One interface may be extended from more than one interface.
8 Interface object is able to call only those methods, which are having same method signature. Interfaces
don’t have concrete methods and variables.
9 Interface only contains constants.
10 ‘super’ keyword cannot be applied to the interface methods.
Syntax:
interface <interface-name>
{
declaration of methods
}
class <class-name> implements <interface names>
{
definition of methods in the interface
definition of its own methods
}
Example:
interface FactInf
{
int fact (int x);
}
class Dev1 implements FactInf //iteration way of calculating
{
int fact (int x)
{
Int I,f = 1;
For (I = 1;I< = x;I++)
F * = I;
Return f;
}
}
class Dev2 implements FactInf //recurrence way of calculating
{
int fact (int x)
{
int f = 1;
if (x> = 1)
f = x*fact (x-1);
return f;
}
}
class MainClass
{
public static void main (String args [])
{
FactInf fi;
fi = new Dev1();
System.out.println(fi.fact(5));
Fi =new Dev2 ();
System.out.println(fi.fact(8));
}
}
Interface hides other functions in class from the end-user. He can access only some functions in the class as
per his need. So it’s better to create object for the interface rather than the class.
Example2:
interface Inf1
{
void method1();
void method2();
}
class Provider implements Inf1
{
public void method1()
{
System.out.println("Hello!");
}
public void method2()
{
System.out.println("Good Morning to All");
}
}
class Mainclass
{
public static void main(String args[])
{
Inf1 i1;
i1=new Provider();
i1.method1();
i1.method2();
}
}
Example3:
interface Inf1
{
void m1();
void m2();
}
interface Inf2
{
void m2();
void m3();
}
class Service_Provider implements Inf1,Inf2
{
public void m1()
{
System.out.println("Hello!");
}
public void m2()
{
System.out.println("Welcome to ");
}
public void m3()
{
System.out.println("Java Programming");
}
}
class Mainclass
{
public static void main(String args[])
{
Inf1 i1;
Inf2 i2;
i1=new Service_Provider();
i1.m1();
i1.m2();
i1.m3(); // Error m3() is not available in Inf1
i2=new Service_Provider();
i2.m1(); // Error m1() is not available in Inf2
i2.m2();
i2.m3();
}
}
Example4:
interface Inf1
{
void m1();
}
interface Inf2 extends Inf1
{
void m2();
}
class Service_Provider implements Inf2
{
public void m1()
{
System.out.println("Method m1() called");
}
public void m2()
{
System.out.println("Method m2() called");
}
}
class Mainclass
{
public static void main(String args[])
{
Inf2 i;
i=new Service_Provider();
i.m1();
i.m2();
}
}
Example5:
interface Inf1
{
void m1();
}
interface Inf2
{
void m2();
}
interface Inf3 extends Inf1,Inf2
{
void m3();
}
i=new Service_Provider();
i.m1();
i.m2();
i.m3();
}
}
Example6:
import java.io.*;
interface AcctInf
{
void open(String acno, char type,double amt);
void deposit(String acno, double amt);
void withdraw(String acno, double amt);
void transfer(String sacno, String dacno, double amt);
double getBal(String acno);
void showAccounts();
}
class Account
{
private String acno;
private char type;
private double bal;
public void setAcno(String ano)
{
acno = ano;
}
public void setType(char c)
{
type=c;
}
public void setBal(double bal)
{
this.bal=bal;
}
String getAcno()
{
return acno;
}
double getBal()
{
return bal;
}
char getType()
{
return type;
}
}
ac[i].setAcno(acno);
ac[i].setBal(amt);
ac[i].setType(type);
i++;
}
break;
}
}
if(found==0)
System.out.println("Invalid Account Number");
while(true)
{
System.out.println("1. Open Account\n2. Deposit\n3. WithDraw\n4. Transfer Amount\n5.
Check Balance\n6. Show Accounts\n7. Exit");
choice=Integer.parseInt(br.readLine());
switch(choice)
{
case 1:
System.out.println("Enter Account Number, Type of Account and
balance");
acno=br.readLine();
type=(char)br.read();
br.readLine();
bal=Double.parseDouble(br.readLine());
acc.open(acno,type,bal);
break;
case 2:
System.out.println("Enter Account number and Balance to Deposit");
acno=br.readLine();
bal=Double.parseDouble(br.readLine());
acc.deposit(acno,bal);
break;
case 3:
System.out.println("Enter Account number and Balance to Withdraw");
acno=br.readLine();
bal=Double.parseDouble(br.readLine());
acc.withdraw(acno,bal);
break;
case 4:
System.out.println("Enter Source ACNO, Destination ACNO and
Balance to transfer");
acno=br.readLine();
dacno=br.readLine();
bal=Double.parseDouble(br.readLine());
acc.transfer(acno,dacno,bal);
break;
case 5:
System.out.println("Enter the acno to get the balance");
acno=br.readLine();
System.out.println("Balance is: "+acc.getBal(acno));
break;
case 6:
acc.showAccounts();
break;
case 7:
System.exit(0);
}
}
}
}
Any class can extends only one class at a time and can't extends more than one class simultaneously hence
java won't provide support for multiple inheritance.
But an interface can extends any no. Of interfaces at a time hence java provides support for multiple
inheritance through interfaces.
3 Pillars of OOPS:
PACKAGE
1 Package is a collection of java classes. It is used to separate the set of classes according to their category
and usage.
2 If you unite more than one class in a single package and if you want to use only some of the classes in
that package, then at the time of importing the package will increase the memory wastage and
compilation time so that it is better to distribute set of classes among different packages.
3 It is used to provide the security.
4 After developing of projects in java we can place all the java class files into different packages and bind
them into a single package to make the installation flexible.
Where,
path: location to place the package
file: which contains “package” statement
Ok, Ok
In the java, there is a separate program called “Class loader” which will load the dot class files into
the memory from the hard disk to make them available to the compilation and interpretation. But the class-
loader will load the class by searching the path, which is placed in the separate system variable called
“classpath”.
If you are not placing the path of your packages into class path, the class loader will not load those
classes so that java compiler will generate errors like “package does not exist”. So before importing those
classes we have to set the path in the “classpath” variable.
Note: The classes, which are placed in the packages, should not contain main method.
package parentpack;
package childpack;
import parentpack.Parent;
public class Child extends Parent
{
Save: Parent.java
Save: Child.java
Compile: javac –d D:\text Child. Java
import childpack.Child;
class Test
{
public static void main(String args [])
{
Child c = new Child();
c.output();
c.x = 40;
c.y = 80;
c.z = 13;
c.t = 15;
c.show();
}
}
Output:
1 2 3
X 1 1 1
Y 2 20 30
Z 3 30 30
T 4 4 4
//Product.java
package com.aditya.cse;
public class Product
{
private String pno;
private int qoh;
private double cost;
public void setPno(String pno)
{
this.pno=pno;
}
public String getPno()
{
return pno;
}
public void setCost(double cost)
{
this.cost =cost;
}
public double getCost()
{
return cost;
}
public void setQoh(int qoh)
{
this.qoh =qoh;
}
public int getQoh()
{
return qoh;
}
}
// ProdInf.java
package com.aditya.cse;
import com.aditya.cse.Product;
public interface ProdInf
{
void addProd (Product p);
Product getProd (String pno);
}
//ProdImp.java
package com.aditya.cse;
import com.aditya.cse.Product;
import com.aditya.cse.ProdInf;
public class ProdImp implements ProdInf
{
final int np=10;
Product list[] = new Product[np];
int i=0,j;
public void addProd (Product p)
{
list [i]=p;
i++;
}
public Product getProd(String pno)
{
for(j=0;j<i;j++)
if (list[j].getPno().equals(pno))
return list[j];
System.out.println("Invalid pno");
return null;
}
}
// Shop.java
import com.aditya.cse.Product;
import com.aditya.cse.ProdInf;
import com.aditya.cse.ProdImp;
import java.io.*;
class Shop
{
public static void main(String args[]) throws Exception
{
int ch;
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
Product p;
ProdInf pi=new ProdImp();
while(true)
{
System.out.println("1.Add\n2.GetProd\n3.Exit");
System.out.println("Enter ur choice:");
ch= Integer.parseInt(b.readLine());
switch (ch)
{
case 1:
System.out.println("Enter pno, cost, qoh");
p=new Product();
p.setPno(b.readLine());
p.setCost(Double.parseDouble(b.readLine()));
p.setQoh(Integer.parseInt(b.readLine()));
pi.addProd(p);
break;
case 2:
System.out.println("Enter pno to find");
p = pi.getProd(b.readLine());
if(p!=null)
{
System.out.println("Pno:"+p.getPno());
System.out.println("Cost:"+p.getCost());
System.out.println("Qoh:"+p.getQoh());
}
break;
case 3:
System.exit(0);
}
}
}
}
Compilation:
set classpath = .;d:\test; %class path%;
javac -d d:\test Product java
javac -d d:\test ProdInf.java
javac -d d:\test ProdImp.java
javac Shop. Java
Run:
java Shop
If more than one package have same class name, we should specify the package name explicitly.
Eg: sample.Test t1 = new sample.Test();
dummy.Test t2 = new dummy.Test();
Where d:
Test
Sample
Test. class
Dummy
Test. Class
Import samp.test;
Import dummy. Test;
Class main class
{
public static void main (string args [])
{
Samp.test t1 = new samp.test ();
Dummy. Test t2 = new dummy. Test ();
}
Package dummy;
Class test
{
}
Java c -d d:\test test. Java
F:\Test
Mainclass.class
Sample
First-class
Second-class
Third-class
F:\test> jar - cvf TestFile. jar <list of files>
Eg: jar -cvf Test.jar *.java *.class
jar -cvf Test.jar
EXCEPTION HANDLING
In programming languages there is a possibility to generate 3 types of errors:
1 Compile-time errors: These are generated because of programming syntaxes.
2 Run-time errors: These will be generated at the time of execution.
3 Logical errors: These will be generated because of the programmer’s mistakes.
Exception:
This is a run-time error; it will be generated at the time of program execution. This will make the program to
be terminated abnormally. Without handling of these exceptions, we cannot provide safety to the application.
If any language having proper exception handling facilities will be treated as strictly written language. If any
application is developed using such type of languages will be treated as ‘Robust’ applications.
It is highly recommended to handle exceptions. The main objective of exception handling is graceful
(normal) termination of the program.
Example: Suppose our programming requirement is to read data from remote file locating at London. At
runtime if London file is not available then our program should not be terminated abnormally.
We have to provide a local file to continue rest of the program normally. This way of defining alternative is
nothing but exception handling.
Example:
try
{
read data from London file
}
catch(FileNotFoundException e)
{
use local file and continue rest of the program normally
}
Exception Hierarchy:
Throwable acts as a root for exception hierarchy. Throwable class contains the following two child classes.
Exception:
Most of the cases exceptions are caused by our program and these are recoverable.
Ex : If FileNotFoundException occurs then we can use local file and we can continue rest of the program
execution normally.
Error:
Most of the cases errors are not caused by our program these are due to lack of system resources and these
are non-recoverable.
Ex :If OutOfMemoryError occurs being a programmer we can't do anything the program will be terminated
abnormally. System Admin or Server Admin is responsible to raise/increase heap memory.
Checked Vs Unchecked Exceptions:
The exceptions which are checked by the compiler whether programmer handling or not, for smooth
execution of the program at runtime, are called checked exceptions.
1. HallTicketMissingException
2. PenNotWorkingException
3. FileNotFoundException
The exceptions which are not checked by the compiler whether programmer handing or not, are called
unchecked exceptions.
1. BombBlastException
2. ArithmeticException
3. NullPointerException
Note: RuntimeException and its child classes, Error and its child classes are unchecked and all the
remaining are considered as checked exceptions.
Note: Whether exception is checked or unchecked compulsory it should occurs at runtime only and there is
no chance of occurring any exception at compile time.
Case 1:
if there is no exception.
1, 2, 3, 5 normal termination.
Case 2:
if an exception raised at statement 2 and corresponding catch block matched
1, 4, 5 normal termination.
Case 3:
if an exception raised at statement 2 but the corresponding catch block not matched
1 followed by abnormal termination.
Case 4:
if an exception raised at statement 4 or statement 5 then it's always abnormal termination of the
program.
Note:
1. Within the try block if anywhere an exception raised then rest of the try block won't be executed even
though we handled that exception. Hence we have to place/take only risk code inside try block and
length of the try block should be as less as possible.
2. If any statement which raises an exception and it is not part of any try block then it is always
abnormal termination of the program.
3. There may be a chance of raising an exception inside catch and finally blocks also in addition to try
block.
Example:
Note: Default exception handler internally uses printStackTrace() method to print exception information to
the console.
Try with multiple catch blocks:
The way of handling an exception is varied from exception to exception. Hence for every exception type it is
recommended to take a separate catch block. That is try with multiple catch blocks is possible and
recommended to use.
Note:
If try with multiple catch blocks present then order of catch blocks is very important. It should be from child
to parent by mistake if we are taking from parent to child then we will get Compile time error saying
finally block:
It is not recommended to take clean up code inside try block because there is no guarantee for the
execution of every statement inside a try.
It is not recommended to place clean up code inside catch block because if there is no exception then
catch block won't be executed.
We require some place to maintain clean up code which should be executed always irrespective of
whether exception raised or not raised and whether handled or not handled. Such type of best place is
nothing but finally block.
Hence the main objective of finally block is to maintain cleanup code.
The speciality of finally block is it will be executed always irrespective of whether the exception raised or
not raised and whether handled or not handled.
return Vs finally:
Even though return statement present in try or catch blocks first finally will be executed and after that only
return statement will be considered. i.e finally block dominates return statement.
Example:
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("try block executed");
return;
}
catch(ArithmeticException e)
{
System.out.println("catch block executed");
}
finally
{
System.out.println("finally block executed");
}
}
}
Output:
try block executed
Finally block executed
finally vs System.exit(0):
There is only one situation where the finally block won't be executed is whenever we are using
System.exit(0) method.
When ever we are using System.exit(0) then JVM itself will be shutdown , in this case finally block won't be
executed.
i.e., System.exit(0) dominates finally block.
Example:
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("try");
System.exit(0);
}
catch(ArithmeticException e)
{
System.out.println("catch block executed");
}
finally
{
System.out.println("finally block executed");
}
}
}
Output:
try
throw statement:
Sometimes we can create Exception object explicitly and we can hand over to the JVM manually by using
throw keyword.
In this case creation of ArithmeticException In this case we are creating exception object
object and handover to the jvm will be performed explicitly and handover to the JVM manually.
automatically by the main() method.
Throws Statement:
In our program if there is any chance of raising checked exception then compulsory we should handle either
by try catch or by throws keyword otherwise the code won't compile.
Example:
import java.io.*;
class Test3
{
public static void main(String[] args)
{
PrinterWriter out=new PrintWriter("abc.txt");
out.println("hello");
}
}
CompileTime Error :
Unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown.
Example:
class Test3
{
public static void main(String[] args)
{
Thread.sleep(5000);
}
}
Compiletime Error:
Unreported exception java.lang.InterruptedException; must be caught or declared to be thrown.
We can handle this compile time error by using the following 2 ways.
By using try catch By using throws keyword
class Test3 We can use throws keyword to delegate the
{ responsibility of exception handling to the caller
public static void main(String[] args) method. Then caller method is responsible to handle
{ that exception.
try{ class Test3
Thread.sleep(5000); {
} public static void main(String[] args)throws
catch(InterruptedException e){} InterruptedException
} {
} Thread.sleep(5000);
Output: }
Compile and running successfully }
Output:
Compile and running successfully
class CustomizedExceptionDemo
{
public static void main(String[] args)
{
int age=Integer.parseInt(args[0]);
if(age>60)
{
throw new TooYoungException("please wait some more time.... u will get best match");
}
else if(age<18)
{
throw new TooOldException("u r age already crossed....no chance of getting married");
}
else
{
System.out.println("you will get match details soon by e-mail");
}
}
}
Output:
1)D:\Programs>java CustomizedExceptionDemo 61
Exception in thread "main" TooYoungException:
please wait some more time.... u will get best match
at CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:21)
2) D:\Programs>java CustomizedExceptionDemo 27
You will get match details soon by e-mail
3) D:\Programs>java CustomizedExceptionDemo 9
Exception in thread "main" TooOldException:
u r age already crossed....no chance of getting married
at CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:25)
Example2:
import java.io. *;
class Account
{
public static void main (String args [])
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
try
{
String user, pass;
System.out.println("Enter user & password");
user=b.readLine ();
pass=b.readLine ();
Login l=new Login(user, pass);
System.out.println("Login Success”);
//If exception is generated, this statement will not be displayed.
//Control will go directly to catch block
}catch (Exception e)
{
System.out.println(e);
}
}
}
MULTI THREADING
1. In the multitasking environment there is a chance to create more than one process is created it requires
some set of resources.
2. Every process, which is created, is stored in different memory locations, so that if you want to shift from
one process to another process, takes so much of time.
3. Switching from one process to another process is called context switch.
4. It is very expensive in terms of time.
5. In some of the cases one process may have more than one sub-process, if you make the sub-process as
main process again it requires separate resources.
6. So to avoid such type of extra allocation we have to run the sub process with in the some Process
memory area.
7. It will increase the performance of the system.
8. A sub-process which is placed in the unit of memory location which can be run in unit of time and is
treated as unit of execution. This is called a thread.
9. It doesn’t require any extra resources.
10. Switching form one thread to another thread is called thread switching.
11. It is inexpensive, when compared with the context switch.
Advantage:
If the CPU is capable to do more than one task at a time, then if you give only one task to the CPU,
utilization CPU is very poor. But in multithreading, Executing several tasks simultaneously where each task
is a separate independent part of the same program, it will increase the throughput of the CPU and utilization
of CPU is high. By assign more than one task; we can speed up the processes
The main important application areas of multithreading are:
1. To implement multimedia graphics.
2. To develop animations.
3. To develop video games etc.
4. To develop web and application servers
Whether it is process based or Thread based the main objective of multitasking is to improve performance of
the system by reducing response time.
1. Runnable interface: This interface contains only one method called run(). We have to implement our
own class by using Runnable interface.
2. Thread class in java.lang package: This Thread class is already implemented Runnable interface, so
that we have to write our own class and make that class as child class to the Thread class and override
run method.It contains some set of life cycle methods
Defining a Thread by extending "Thread class":
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread(); //Instantiation of a Thread
t.start(); //starting of a Thread
for(int i=0;i<5;i++)
{
System.out.println("main thread");
}
}
}
Thread Scheduler:
If multiple Threads are waiting to execute then which Thread will execute 1st is decided by "Thread
Scheduler" which is part of JVM. Which algorithm or behaviour followed by Thread Scheduler we can't
expect exactly it is the JVM vendor dependent hence in multithreading examples we can't expect exact
execution order and exact output.
The following are various possible outputs for the above program.
Example:
class ThreadDemo
{
public static void main(String[] args)
{
MyRunnable r=new MyRunnable();
Thread t=new Thread(r);//here r is a Target Runnable
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main thread");
}
}
}
Output:
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
We can't expect exact output but there are several possible outputs.
Best approach to define a Thread:
Among the 2 ways of defining a Thread, implements Runnable approach is always recommended.
In the 1st approach our class should always extends Thread class there is no chance of extending any
other class hence we are missing the benefits of inheritance.
But in the 2nd approach while implementing Runnable interface we can extend some other class also.
Hence implements Runnable mechanism is recommended to define a Thread.
Example:
class MyThread extends Thread
{
}
class ThreadDemo
{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName()); //main
MyThread t=new MyThread();
System.out.println(t.getName()); //Thread-0
Thread.currentThread().setName("Aditya Thread");
System.out.println(Thread.currentThread().getName()); //Aditya Thread
}
}
Note: We can get current executing Thread object reference by using Thread.currentThread() method.
Thread Priorities:
Every Thread in java has some priority it may be default priority generated by JVM (or) explicitly provided
by the programmer.
The valid range of Thread priorities is 1 to 10[but not 0 to 10] where 1 is the least priority and 10 is highest
priority.
Thread class defines the following constants to represent some standard priorities.
1. Thread. MIN_PRIORITY----------1
2. Thread. MAX_PRIORITY----------10
3. Thread. NORM_PRIORITY--------5
Thread scheduler uses these priorities while allocating CPU.
The Thread which is having highest priority will get chance for 1st execution.
If two Threads having the same priority then we can't expect exact execution order it depends on
Thread scheduler whose behavior is vendor dependent.
We can get and set the priority of a Thread by using the following methods.
1. public final int getPriority()
2. public final void setPriority(int newPriority); //the allowed values are 1 to 10
The allowed values are 1 to 10 otherwise we will get runtime exception saying "IllegalArgumentException".
Default priority:
The default priority only for the main Thread is 5. But for all the remaining Threads the default priority will
be inheriting from parent to child. That is whatever the priority parent has by default the same priority will
be for the child also.
Example 1:
class MyThread extends Thread
{
}
class ThreadPriorityDemo
{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getPriority()); //5
Thread.currentThread().setPriority(9);
MyThread t=new MyThread();
System.out.println(t.getPriority()); //9
}
}
Example 2:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("child thread");
}
}
}
class ThreadPriorityDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
//t.setPriority(10); //----> 1
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main thread");
}
}
}
If we are commenting line 1 then both main and child Threads will have the same priority and hence we
can't expect exact execution order.
If we are not commenting line 1 then child Thread has the priority 10 and main Thread has the priority 5
hence child Thread will get chance for execution and after completing child Thread main Thread will get the
chance in this the output is:
Output:
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
Some operating systems(like windowsXP) may not provide proper support for Thread priorities. We have to
install separate bats provided by vendor to provide support for priorities.
The Methods to Prevent a Thread from Execution:
We can prevent(stop) a Thread execution by using the following methods.
1. yield();
2. join();
3. sleep();
yield():
1. yield() method causes "to pause current executing Thread for giving the chance of remaining waiting
Threads of same priority".
2. If all waiting Threads have the low priority or if there is no waiting Threads then the same Thread will be
continued its execution.
3. If several waiting Threads with same priority available then we can't expect exact which Thread will get
chance for execution.
4. The Thread which is yielded when it get chance once again for execution is depends on mercy of the
Thread scheduler.
5. public static native void yield();
Example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
Thread.yield();
System.out.println("child thread");
}
}
}
class ThreadYieldDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
for(int i=0;i<5;i++)
{
System.out.println("main thread");
}
}
}
Output:
main thread
main thread
main thread
main thread
main thread
child thread
child thread
child thread
child thread
child thread
In the above program child Thread always calling yield() method and hence main Thread will get the chance
more number of times for execution. Hence the chance of completing the main Thread first is high.
Note: Some operating systems may not provide proper support for yield() method.
join():
If a Thread wants to wait until completing some other Thread then we should go for
join() method.
Example: If a Thread t1 executes t2.join() then t1 should go for waiting state until completing t2.
sleep() method:
If a Thread don't want to perform any operation for a particular amount of time then we should go for sleep()
method.
1. public static native void sleep(long ms) throws InterruptedException
2. public static void sleep(long ms,int ns)throws InterruptedException
Example:
class ThreadJoinDemo
{
public static void main(String[] args)throws InterruptedException
{
System.out.println("M");
Thread.sleep(3000);
System.out.println("E");
Thread.sleep(3000);
System.out.println("G");
Thread.sleep(3000);
System.out.println("A");
}
}
Output:
M
E
G
A
Examples:
class Test implements Runnable
{
long stime;
Thread t;
int i=1;
public Test()
{
t = new thread (this, "Default");
System.out.println("Name:"+ t.getName());
stime=1000;
t.start ();
}
public Test(String tname)
{
t=new Thread(this, tname);
stime=500;
System.out.println(t);
t.start ();
}
public test (String tname, long time)
{
stime=time
t = new Thread(this,name);
System.out.println(t);
t.start ();
}
catch (Exception e)
{
System.out.println(e);
}
}
Thread Synchronization:
In the multithreading environment, there is a chance to access a common area by more than one thread at a
time. The threads, which are trying to access this common area, will be treated as cooperative threads. And
the common area is called critical section. The threads are can share nothing will be treated as independent
threads. More than one thread must not be enter into critical section at a time, it leads to deadlock [or] loss of
data. So to overcome this problem we have to make the critical section in such a way so that only one thread
is able to enter into critical section at a time. The first thread is trying to access critical section it must lock
that section, then only it continue with its work. If any other thread is passing request at the same time, it has
to wait, until resource will release by the first thread. This is called Synchronization.
1. Synchronized is the keyword applicable for methods and blocks but not for classes and variables.
2. If a method or block declared as the synchronized then at a time only one Thread is allow to execute
that method or block on the given object.
3. The main advantage of synchronized keyword is we can resolve data inconsistency problems. But the
main disadvantage of synchronized keyword is it increases waiting time of the Thread and effects
performance of the system.
4. Hence if there is no specific requirement then never recommended to use synchronized keyword.
5. Internally synchronization concept is implemented by using lock concept. Every object in java has a
unique lock. Whenever we are using synchronized keyword then only lock concept will come into
the picture.
6. If a Thread wants to execute any synchronized method on the given object 1st it has to get the lock of
that object. Once a Thread got the lock of that object then it's allow to execute any synchronized
method on that object. If the synchronized method execution completes then automatically Thread
releases lock.
7. While a Thread executing any synchronized method the remaining Threads are not allowed execute
any synchronized methods on that object simultaneously. But remaining Threads are allowed to
execute any non-synchronized method simultaneously. [lock concept is implemented based on object
but not based on method].
Example:
class Display
{
public synchronized void wish(String name)
{
for(int i=0;i<5;i++)
{
System.out.print("good morning:");
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{}
System.out.println(name);
}
}
}
class MyThread extends Thread
{
Display d;
String name;
MyThread(Display d,String name)
{
this.d=d;
this.name=name;
}
public void run()
{
d.wish(name);
}
}
class SynchronizedDemo
{
public static void main(String[] args)
{
Display d1=new Display();
MyThread t1=new MyThread(d1,"dhoni");
MyThread t2=new MyThread(d1,"yuvaraj");
t1.start();
t2.start();
}
}
If we declare wish()method as synchronized then the Threads will be executed one by one that is until
completing the 1st Thread the 2nd Thread will wait in this case we will get output as:
Output:
good morning:dhoni
good morning:dhoni
good morning:dhoni
good morning:dhoni
good morning:dhoni
good morning:yuvaraj
good morning:yuvaraj
good morning:yuvaraj
good morning:yuvaraj
good morning:yuvaraj
If we are not declaring wish() method as synchronized then both Threads will be executed simultaneously
and we will get irregular output.
Output:
good morning:good morning:yuvaraj
good morning:dhoni
good morning:yuvaraj
good morning:dhoni
good morning:yuvaraj
good morning:dhoni
good morning:yuvaraj
good morning:dhoni
good morning:yuvaraj
dhoni
{
super("Producer");
this.buf=buf;
start();
}
public void run ()
{
try
{
while (true)
{
System.out.println("Enter data");
data=b.readLine ();
buf.put(data);
Thread.sleep(500); //InterruptedException
}
}catch (Exception e)
{System.out.println(e);}
}
}
class Consumer extends Thread
{
Buffer buf;
public Consumer(buffer buf)
{
super ("Consumer");
this.buf=buf;
start ();
}
public void run ()
{
try
{
while (true)
{
System.out.println("Consumed:"+ buf.get());
Thread.sleep (500);
}
}catch(Exception e)
{System.out.println(e);}
}
}
class Product
{
public static void main (String args [])
{
Buffer buf = new Buffer ();
Producer p = new Producer (buf);
Consumer c = new Consumer (buf);
}
}
Daemon Threads:
The Threads which are executing in the background are called daemon Threads. The main objective of
daemon Threads is to provide support for non-daemon Threads like main Thread.
Example:
Garbage collector
Whenever the program runs with low memory the JVM will execute Garbage Collector to provide free
memory. So that the main Thread can continue it's execution.
We can check whether the Thread is daemon or not by using isDaemon() method of Thread class.
public final boolean isDaemon();
We can change daemon nature of a Thread by using setDaemon () method.
public final void setDaemon(boolean b);
But we can change daemon nature before starting Thread only. That is after starting the Thread if we are
trying to change the daemon nature we will get R.E saying IllegalThreadStateException.
Default Nature: Main Thread is always non daemon and we can't change its daemon nature because it's
already started at the beginning only. Main Thread is always non daemon and for the remaining Threads
daemon nature will be inheriting from parent to child that is if the parent is daemon child is also daemon and
if the parent is non daemon then child is also non daemon.
Whenever the last non daemon Thread terminates automatically all daemon Threads will be terminated.
Example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("lazy thread");
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{}
}
}
}
class DaemonThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.setDaemon(true); //-->1
t.start();
System.out.println("end of main Thread");
}
}
Output:
End of main Thread
If we comment line 1 then both main & child Threads are non-Daemon, and hence both threads will be
executed untill there completion.
If we are not comment line 1 then main thread is non-Daemon and child thread is Daemon. Hence when ever
main Thread terminates automatically child thread will be terminated.
ThreadGroup:
Based on functionality we can group threads as a single unit which is nothing but ThreadGroup.
ThreadGroup provides a convenient way to perform common operations for all threads belongs to a
particular group.
We can attach a Thread to the ThreadGroup by using the following constructor of Thread class
Thread t=new Thread(ThreadGroup g, String name);
Class Runtime
class RunTimeDemo
{
public static void main(String args[])
{
Runtime r=Runtime.getRuntime();
System.out.println(r.freeMemory ());
System.out.println(r.totalMemory ());
r.gc (); // (or) system.gc(); Grabage Collection
r.exec("notepad");//Executes the specified string command in a separate process.
r.exec("mspaint")
r.exec("calc");
}
}
Java.io package contains classes to perform input and output operations. By using java.io package we are
performing file handling java.
Stream:
Stream is a logical connection between java program and a file. Stream can be defined as “it is continuous
flow of data between java program and persistence media.
Types of Streams:
Generally streams are divided into two types based on data flow direction.
InputStream: the stream that allows data to come into the java application from the persistent media is
called InputStream.
OutputStream: The stream that allows data to send out from the java application to be stored into the
persistent media is called OutputStream.
I/O Streams:
An I/O stream represents input source or an output destination. Streams represent many kind of source and
destination like disk files & devices & memory arrays.
Streams support different kind of data
Simple bytes.
Primitive data types
Localized characters
Objects …..etc
Stream is a communication channel between source and destination & a stream is a sequence of data.
Input stream:- Program uses Input stream to read the data from a source one item at a time.
Output stream:- Program uses output stream to write the data to a destination one item at a time.
In java we are allowed to send data through streams only either in the format of bytes or characters.
Byte Streams:
The streams which read and write data in the format of bytes called Binary Streams.
Character Streams:
The streams which read and write data in the format of character is called character streams.
Programs:
Example1:
import java.io.*;
class FileDemo
{
public static void main(String[] args)throws IOException
{
File f=new File("cricket.txt");
System.out.println(f.exists()); //false
f.createNewFile();
System.out.println(f.exists()); //true
}
}
Example2:
A java File object can represent a directory also.
import java.io.*;
class FileDemo
{
public static void main(String[] args)throws IOException
{
File f=new File("cricket123");
System.out.println(f.exists());//false
f.mkdir();
System.out.println(f.exists());//true
}
}
Example3: Write code to create a file named with demo.txt in current working directory.
import java.io.*;
class FileDemo
{
public static void main(String[] args)throws IOException
{
File f=new File("demo.txt");
f.createNewFile();
}
}
Example4: Write code to create a directory named with SaiCharan123 in current working directory and
create a file named with abc.txt in that directory.
import java.io.*;
class FileDemo
{
public static void main(String[] args)throws IOException
{
File f1=new File("SaiCharan123");
f1.mkdir();
File f2=new File("SaiCharan123","abc.txt");
f2.createNewFile();
}
}
Example5: Write code to create a file named with demo.txt present in c:\saicharan folder.
import java.io.*;
class FileDemo
{
public static void main(String[] args)throws IOException
{
File f=new File("c:\\saiCharan","demo.txt");
f.createNewFile();
}
}
Example6: Write a program to display the names of all files and directories present in c:\\charan_classes.
import java.io.*;
class FileDemo
{
public static void main(String[] args)throws IOException
{
int count=0;
File f=new File("c:\\charan_classes");
String[] s=f.list();
for(String s1:s) {
count++;
System.out.println(s1);
}
System.out.println("total number : "+count);
}
}
}
}
System.out.println("total number : "+count);
}
}
Byte Streams:
Program uses byte stream to perform input & output of byte data. All byte stream classes developed based
on InputStream & OutputStream. Program uses byte stream to perform input and output of 8-bit bytes.
To demonstrate how the byte stream works file I/O provided two main classes
FileInputStream
It is used to read the data from source one item at a time.
To read the data from source use read() method of FileInputStream class.
public int read() throws java.io.IOException;
read() method returns first character Unicode value in the form of integer value.
FileOutputStream
It is used to write the data to destination one item at a time.
To write the data to destination use write() method of FileOutputStream class.
public void write(int unicode) throws java.io.IOException;
write() method is taking Unicode value of the character as a parameter.
Example8:
import java.io.*;
class Test
{
public static void main(String[] args)throws FileNotFoundException,IOException
{
//Byte oriented channel creation
FileInputStream fis = new FileInputStream("abc.txt");
FileOutputStream fos = new FileOutputStream("xyz.txt");
int c;
while((c=fis.read())!=-1)
{
System.out.print((char)c);
fos.write(c);
}
System.out.println("read() & write operatoins are completed");
To demonstrate how the character stream works file I/O provided two main classes
FileReader
It is used to read the data from source one item at a time.
To read the data from source use read() method of FileInputStream class.
public int read() throws java.io.IOException;
read() method returns first character Unicode value in the form of integer value.
FileWriter
It is used to write the data to destination one item at a time.
To write the data to destination use write() method of FileOutputStream class.
public void write(int unicode) throws java.io.IOException;
write() method is taking Unicode value of the character as a parameter.
Example9:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Test
{
public static void main(String[] args) throws IOException
{
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("abc.txt");
outputStream = new FileWriter("characteroutput.txt");
int c;
while ((c = inputStream.read()) != -1)
{
outputStream.write(c);
}
}
finally
{
if (inputStream != null)
{
inputStream.close();
}
if (outputStream != null)
{ outputStream.close();
}
}
}
}
Note:
In CopyCharacters, the int variable holds a character value in its last 16 bits; in CopyBytes, the int variable
holds a byte value in its last 8 bits.
Buffered Streams:
In previous examples we are using un-buffered I/O .This means each read and write request is handled
directly by the underlying OS. In normal streams each request directly triggers disk access it is relatively
expensive & performance is degraded.
Example10:
import java.io.*;
class Test
{
public static void main(String[] args)
{
BufferedReader br;
BufferedWriter bw;
try{
br=new BufferedReader(new FileReader("Test1.java"));
bw=new BufferedWriter(new FileWriter("States.java"));
String str;
while ((str=br.readLine())!=null)
{
bw.write(str);
}
br.close();
bw.close();
}
catch(Exception e)
{
System.out.println("getting Exception");
}
}
}
Example11:
import java.io.*;
class Test
{
public static void main(String[] args)
{
BufferedInputStream bis;
BufferedOutputStream bos;
try{
bis=new BufferedInputStream(new FileInputStream("abc.txt"));
bos=new BufferedOutputStream(new FileOutputStream("xyz.txt"));
int str;
while ((str=bis.read())!=-1)
{
bos.write(str);
}
bis.close();
bos.close();
}
catch(Exception e)
{
System.out.println(e);
System.out.println("getting Exception");
}
}
}
}
}
Example13: Program to Write the Data into the File using DataOutputStream
import java.io.*;
class DataWrite
{
public static void main(String args[])
{
try
{
int eno;
String ename;
double sal;
BufferedReader b;
b=new BufferedReader(new InputStreamReader(System.in));
DataOutputStream fout;
while (true)
{
fout=new DataOutputStream(new FileOutputStream(args[0],true));
System.out.println("Enter No,Name & Sal");
eno = Integer.parseInt(b.readLine());
ename = b.readLine();
sal = Double.parseDouble(b.readLine());
fout.writeInt(eno);
fout.writeBytes ("\n"+ename+"\n");
fout.writeDouble (sal);
fout.writeBytes("\n");
System.out.println("Do you want to continue: \n");
int ch=System.in.read(); //similar to getch ()
if(ch=='y' || ch=='Y')
break;
}
fout.close ();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Example14: Program to Read the Data from the File using DataInputStream
import java.io. *;
class DataRead
{
public static void main(String args[])
{
DataInputStream fin;
try
{
int eno;
String ename;
double sal;
File f = new File(args[0]);
if(!f.exists())
{
System.out.println("File does not exist");
System.exit(0);
}
fin=new DataInputStream(new FileInputStream(f));
while (true)
{
eno= fin.readInt();
ename= fin.readLine();
sal=fin.readDouble();
System.out.println("No:"+eno);
System.out.println("Name:"+ename);
System.out.println ("Sal:"+sal);
}
}catch(EOFException e)
{ fin.close ();
}
catch(Exception e)
{System.out.println(e);}
}
}
Example15: StreamTokenizers
import java.io.*;
class TokenDemo
{
public static void main(String args[])
{
try
{
File f=new File(args[0]);
FileInputStream fin=new FileInputStream(f);
StreamTokenizer st=new StreamTokenizer(fin);
int token;
while(true)
{
token=st.nextToken();
if(token==StreamTokenizer.TT_WORD)
System.out.println(st.sval);
else if(token==StreamTokenizer.TT_NUMBER)
System.out.println(st.nval):
else if (token==StreamTokenizer.TT_EOF)
break:
}
fin.close();
}catch(Exception e)
{
System.out.println (e);
}
}
}
Example16: Program to Write the Data into the File using PrintStream
import java.io. *;
class PrintDemo
{
public static void main (String args[])
{
try
{
BufferedReader b;
b=new BufferedReader(new InputStreamReader(System.in));
FileOutputStream fout=new FileOutputStream(args[0],true);
PrintStream ps=new PrintStream(fout);
int eno;
String ename;
double sal;
System.out.println("Enter No,Name & Sal");
eno=Integer.parseInt(b.readLine());
ename=b.readLine();
sal=Double.parseDouble(b.readLine ());
ps.println(eno);
ps.println(ename);
ps.println(sal);
ps.close();
}catch(Exception e)
{System.out.println(e);}
}
}