0% found this document useful (0 votes)
128 views

Java - Material (Unit - 1 To 4)

The document discusses the key concepts of object-oriented programming through Java, including classes, objects, inheritance, interfaces, abstraction, encapsulation, and polymorphism. It provides an overview of the five units covered in the course, which include introduction to classes and objects in Java, inheritance and interfaces, exception handling, multithreading, and graphical user interface components. The document also discusses the reasons for developing the Java programming language to overcome limitations of other languages and its suitability for web applications due to platform independence.

Uploaded by

J developer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
128 views

Java - Material (Unit - 1 To 4)

The document discusses the key concepts of object-oriented programming through Java, including classes, objects, inheritance, interfaces, abstraction, encapsulation, and polymorphism. It provides an overview of the five units covered in the course, which include introduction to classes and objects in Java, inheritance and interfaces, exception handling, multithreading, and graphical user interface components. The document also discusses the reasons for developing the Java programming language to overcome limitations of other languages and its suitability for web applications due to platform independence.

Uploaded by

J developer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

OOP’s through JAVA 1

OBJECT ORIENTED PROGRAMMING THROUGH JAVA


(Common to CSE & IT)

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.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 2

Types of programming language:

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

1 In the procedure- oriented approach, entire concentration is on procedures only.


2 So it doesn’t concentrate on security to the data.
3 It gives the freedom to the data.
4 It will not provide any reusability.

Object Oriented Programming:

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.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 3

Object Oriented Concepts

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.

Reasons for developing java language:


In the case of C language, it supports procedure-oriented approach so that it is giving the freedom to
the data so data can move to any program within the project.
It will not support overloading, reusing, encapsulation type of methodologies. It does not provide
proper integration among different actions and properties. To overcome these drawbacks C++ was
developed. It supports object oriented approach but it is not purely adapt to the oops because both the
languages support pointers. Even though pointers will increase the execution speed and decrease the memory
wastage, it doesn’t provide security to the data. It means pointers violate security.
By considering all these drawbacks and make them advantages, java was developed in 1990 at sun
Microsystems by James Goslings, Bill Joy, Patrick Naughton. Initially java was called as Oak. Its main area
of application is in the field of micro controller. In these micro-controllers, we are able to develop common
program for any type of micro controller. Once program is developed in java, it can be used any where so
the caption for java is “Write Once Run Any Where”
From 1995 onwards, Internet was introduced so there is a need of distribution of data and application
throughout the world on different types of computers and environments, so that java was promoted to
Internet to satisfy the web application requirements. Because of platform independency, same java program
can run on any type of environment. It makes java as powerful, secured, language in Internet era.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 4

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.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 5

JAVA PROGRAM STRUCTURE:


Components of java programmed:
1. Package declaration part
2. Package import statement
3. Class definitions.

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

Save: Sample. Java


Compile: javac Sample. Java
Run: java Sample

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 6

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

Syntax of creating an object:

<class-name> object=new <class-name>();


Example: Sample s=new Sample();

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 7

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

public static void main (String args[])


{
Sample s=new Sample ();
s.test();
}
}

//To add 2 numbers by taking I/p from keyboard


import java.io.*;
class NumberDemo
{
public static void main (String args []) throws Exception
{
InputStreamReader isr=new BufferedReader(System.in)
BufferedReader br=new BufferedReader (isr);
int x,y,z;
System .out.println (“enter 2 no.s:”);
x = Integer.parseInt (br.readLine ());
y = Integer.parseInt (br.readLine());
z = x+y;
System.out.println (“Sum:”+z);
}
}

//To calculate simple interest:


import java.io. *;
class Interest
{
public static void main (String args[]) throws Exception
{
InputStreamReader isr=new InputStreamReader (System.in);
BufferedReader b=new BufferedReader (isr);
int t,p,r;
float si;
System.out.println (‘Enter principle:”);
p = inter.parseint (b.read line ());
System .out.println (“Enter Time”);
t = Integer.parseInt (b.readLine ());
System .out.println(“Enter Rate”);
r = Integer. parseInt (b.readLine ());

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.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 8

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

System .out.println(“Enter “+n+” Elements”);


for(i=0;i<n;i++)
x[i] = Integer.parseInt (br.readLine ());

System .out.println (“Given array:\n”);


for (i=0;i<n;i++)
System.out.println (x[i]);
}
}

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 9

//To calculate standard deviation sd = SQRT( (xi-mean)2/n)


import java.io.*;
class StdDev
{
public static void main (String args [])throws Exception
{
InputStreamReader isr = new InputStreamReader (System.in);
BufferedReader b = new BufferedReader (isr);
int x [],n,I, mean=0;t=0;k=0;
float sd;
System.out.printin(“enter no.of elements”);
n = Integer.parseInt(b.readLine());
x=new int [n] ;
System.out.println(‘Enter “+n+” Elements “);
for (i=0;i<n;i++)
{
x[i] = Integer.parseInt (b.readLine ());
mean = mean + x[i];
}
mean = mean/n;
for(i =0;i<n;i++)
{
k = x [i]-mean;
t = t +(x[i]-mean)*(x[i]-mean);
}
l = t/n
sd = math.sqrt(l);
System.out.println(sd);
}
}
// Program to find the sorted order of given array
import java.io.* ;
class sort
{
public static void main (string args [])throws exception
{
InputStreamReader isr = new BufferedReader(System.in);
BufferedReader b = new BufferedReader (isr);
int x [], i,j,t
System.out.println (“Enter the no.of elements “);
n = Integer.parseInt (b.readLine ());
x = new int [n];
System.out.printin(“enter “+n” elements “);
for(i = 0 ;i<n;i++)
{
x [i] = Integer.parseInt (b.readLine());
}
for(i = 0;i<n; i++)
{
for(j =i+1; j<n; j++)
{
if (x[i]>x[j])
{
t = x[i];
x[j] = x[i];
x [j] = t;
}
}
}
System.out. println ( “Sorted Array:”);
for (i = 0;i < n;i++)
System.out.println (x[i]);
}
}

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 10

//Double Dimensional array


Two dimensional array declaration:
Example:
int[][] a;
int [][]a;
int a[][]; All are valid.(6 ways)
int[] []a;
int[] a[];
int []a[];

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 11

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

System.out.printin (“Given Matrix”);


for(i = 0;i<m;i++)
{
for(j = 0;j<n;j++)
System.out.print(x[i][j]+ “\t”);
System.out.println();
}
}
}

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 12

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 13

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 14

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 push(int ele)


{ top++;
if(top>=size )
{
System.out.println("Stack is Overflow");
top--;
}
else
x[top]=ele;
}

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 15

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

public static void main (String args [])


{ int o;
Stacks s1 = new Stacks ();
Stacks s2 = new Stacks(10);
int n1 = s1.getSize();
int n2 = s2. getSize();
for(i=1;i<=n1;i++)
s1.push(i+i);
for (i = 1;i<= n2;i++)
s2.push(i*i);
s1.show();
s2.show();
s1.pop();
s2.pop();
s1.show();
s2.show();
}
}

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 16

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

//Usage of “this” object to add 2no.s:


import java.io.*;
class Numbers
{
int x;
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
public void getX() throws Exception
{
System.out.println("Enter a No");
x = Integer.parseInt(b.readLine());
}
public Numbers add(Numbers n)
{
Numbers n3 =new Numbers();
n3.x=x+ n.x;
return n3;
}
public Numbers max(Numbers n)
{
if(x>=n.x)
return this;
else
return n3;
}

public void show()


{
System.out.println("X:"+x);
}
public static void main (String args [])throws Exception
{
Numbers n1 = new Numbers();
Numbers n2 = new Numbers ();
n1.getX();
n2.getX();
Numbers n3 = n1.add(n2);
Numbers n4=n1.max(n2);
n1.show();
n2.show();
n3.show();
n4.show();
}
}

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 17

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.

// Multiplication of two complex numbers:


import java.io.*;
class Complex
{
int real,imag;
void getX()
{
System.out.println("enter real & imaginary parts");
real = Integer.parseInt (b.readLine());
imag = Integer.parseInt(b.readLine());
}
Complex multiply(Complex n)
{
Complex n3 =new Complex ();
n3.real = real*n.real-imag*n.imag;
n3.imag = real*n.imag+imag*n.real;
return n3;
}
void show()
{
if (imag >= 0)
System.out.println(real + "+" + imag + "j");
else
System.out.println(real + "" + imag + "j");
}
public static void main (string args[])throws Exception
{
Complex c1 = new Complex();
Complex c2 = new Complex();
c1.getX();
c2.getX();
Complex c3 = c1.multiply(c2);
c1.show();
c2.show();
c3.show();
}
}

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 18

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 19

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 :

3. Lack of overloading in "C" increases complexity of the programming.


4. But in java we can take multiple methods with the same name and different argument types.
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");
}

public static void main(String[] args)


{
Test t=new Test();
t.methodOne();//no-arg method
t.methodOne(10);//int-arg method
t.methodOne(10.5);//double-arg method
}
}

Conclusion : In overloading compiler is responsible to perform method resolution(decision) based on the


reference type(but not based on run time object). Hence overloading is also considered as compile time
polymorphism(or) static polymorphism (or)early biding.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 20

Automatic promotion in overloading:


In overloading if compiler is unable to find the method with exact match we won't get any compile time
error immediately.1st compiler promotes the argument to the next level and checks whether the matched
method is available or not if it is available then that method will be considered if it is not available then
compiler promotes the argument once again to the next level. This process will be continued until all
possible promotions still if the matched method is not available then we will get compile time error.
This process is called automatic promotion in overloading.

The following are various possible automatic promotions in overloading.

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 21

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

class HousingLoan extends Loan {


//Housing loan specific methods.
}

class EducationLoan extends Loan {


//Education Loan specific methods.
}

Example:
class Parent {
public void methodOne(){ }
}

class Child extends Parent {


public void methodTwo() { }
}

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 22

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 23

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 24

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 25

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

// Test Class and Output


public class Test
{
public static void main(String args[]) {
B b = new B();
}
}
Output:
A's one argument constructor
B's one argument constructor
B's no 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);
}
}

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 26

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 27

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 28

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 29

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.

final class parent


{

}
class child extends parent //error can not be inherited
{

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 30

Dynamic method dispatching:


1 In the inheritance, if both parent and child classes having the same function signature then parent class
object is able to call those methods in both parent and child parent object is able to store instance of
child classes.
2 Single parent class object is overloaded with different child class instance at different times, and it will
invoke the related methods according to child class instance, which is held in that object at runtime.
This is called “Dynamic Method Dispatching”.
3 The purpose of dynamic method dispatching is used to hide the some of the services of child class to
provide the protection to the child class.
4 Parent class object cannot invoke the methods, which do not have same signature in parent and child.
5 To know the instance which is held in the parent class object, we have to use “instanceof” keyword.
6 If we want to check the instance, the parent class instance condition must be last condition.
7 Dynamic polymorphism is also called as dynamic bind or late binding or run-time poly morphism.
Example:
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 disp(Number N)throws Exception
{
N.get no();
If (N instanceof Hexa)
System.out.println("Hexa Instance");
else if (N instanceof Octal)
System.out.println ("Octal Instance");
else
System.out.println("Number Instance");
N.show ();
}
public static void main(String args [])throws Exception
{
Disp(new Number ());
Disp(new Hexa ());
Disp(new Octal ());
}
}
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));
}
}
Instance o/p I/p
N Number 13 13
N Hexa 15 15
N Octal 8 10

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 31

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("=============");

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 32

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("==============");

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 33

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 34

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.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 35

Realationship between interface and 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");
}
}

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 36

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 37

class Service_Provider implements Inf3


{
public void m1()
{
System.out.println("Method m1() called");
}
public void m2()
{
System.out.println("Method m2() called");
}
public void m3()
{
System.out.println("Method m3() called");
}
}
class Mainclass
{
public static void main(String args[])
{
Inf3 i;

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 38

char getType()
{
return type;
}
}

class Bank implements AcctInf


{
int i= 0,j,found=0;
static final int nr =50;
Account ac[] = new Account[Bank.nr];

public void open(String acno, char type,double amt)


{
ac[i]=new Account();

ac[i].setAcno(acno);
ac[i].setBal(amt);
ac[i].setType(type);
i++;
}

public double getBal(String acno)


{
for(j=0; j<i; j++)
if (ac[j].getAcno().equals(acno))
return ac[j].getBal();
System.out.println("Invalid Acno");
return -1;
}

public void deposit(String acno, double amt)


{ found=0;
for(j=0;j<i;j++)
{ if(ac[j].getAcno().equals(acno))
{ found=1;
break;
}
}
if(found==1)
ac[j].setBal(ac[j].getBal()+amt);
else
System.out.println("Invalid Account Number");

public void withdraw(String acno, double amt)


{
found=0;
for(j=0;j<i;j++)
{ if(ac[j].getAcno().equals(acno))
{ found=1;
if(ac[j].getBal()-amt>=0)
ac[j].setBal(ac[j].getBal()+amt);
else
System.out.println("Insufficient Balance in your account");

break;
}
}
if(found==0)
System.out.println("Invalid Account Number");

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 39

public void transfer(String sacno, String dacno, double amt)


{
int found1=-1,found2=-1;
for(j=0;j<i;j++)
{
if(ac[j].getAcno().equals(sacno))
found1=j;
else if(ac[j].getAcno().equals(dacno))
found2=j;

if(found1!=-1 && found2!=-1)


break;
}
if(found1==-1 || found2==-1)
System.out.println("Invalid Account numbers");
else if(ac[found1].getBal()-amt>=0)
{ ac[found1].setBal(ac[found1].getBal()-amt);
ac[found2].setBal(ac[found2].getBal()+amt);
}
else
System.out.println("Insufficient amount to transfer");
}

public void showAccounts()


{
for(j=0;j<i;j++)
{
System.out.println("Account"+(j+1)+" details");
System.out.println(ac[j].getAcno());
System.out.println(ac[j].getType());
System.out.println(ac[j].getBal());
System.out.println("==========================");
}
}

public static void main(String args[])throws Exception


{
AcctInf acc=new Bank();
String acno,dacno;
char type;
double bal;
int choice;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 40

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

}
}

Multiple Inheritance in JAVA


Having more than one Parent class at the same level is called multiple inheritance.

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.

Why java won't provide support for multiple inheritance?


There may be a chance of raising ambiguity problems.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 41

Why ambiguity problem won't be there in interfaces?


Interfaces having dummy declarations and they won't have implementations hence no ambiguity problem.

3 Pillars of OOPS:

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 42

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.

Rules to create a package:


1 We have to write the classes with the “package” statement as a first statement, to those classes, which are
required to place into packages.
2 We have to make the class as public, to access that class outside of the package.
3 We can write any number of classes with in a file but only one class must be the public.
4 If you want to make more than one class as public we have to place each and every class in separate
files.
5 File name must be the name of the public class.
6 A class many have more than one method, but at least one method must be public.

Compilation of package class:


javac –d <path> file.java

Where,
path: location to place the package
file: which contains “package” statement

To make package available to Entire system

1. Set class Path=;.; % Class Path%


2. My Computer
|
| Properties
|
|Advanced
|
|Environment Variables
|
|User Variables

Value of classpath: <path>;.;

Ok, Ok

Use of Class path environment variable:

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;

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 43

public class Parent


{
private int x;
public int y;
protected int z;
int t;
public void set ()
{
X=1;
Y=2;
Z=3;
T=4;
}
public void show ()
{
System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println(t);
}
}

package childpack;
import parentpack.Parent;
public class Child extends Parent
{

public void output()


{
set();
show();
X=10;
Y=20;
Z=30;
T=40;
show();
}
}

Save: Parent.java

Compile: javac –d D:\test Parent. java


set classpath =;.;D:\test; %classpath%;

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

Compile: javac Test.java


Run: java Test

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 44

Output:
1 2 3
X 1 1 1
Y 2 20 30
Z 3 30 30
T 4 4 4

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 45

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 46

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 47

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

Compilation of one of the tests


Java c –d d:\test Test. java

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 48

To create the jar file:


Jar file is a collection of package, image files, html files, jsp files. It will compress all files in a single
file so that using and transmitting is easy. It is like WinZip but WinZip will only work on windows platform,
but jar is a platform independent file so that we can place the jar file on any platform and to work with the
packages in the jar file, we have to set the class path to the jar file.

Creating the jar file:

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

To list out the contents of jar file


jar -tvf File.jar
t - table
jar -tvf Test.jar

To extract the jar file:


jar-xvf File.jar
set classpath = e:\proj\Test.jar

To append the new files to the existing files:

jar -uvf Test.jar *.html

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 49

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 50

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.

What is the meaning of exception handling?


Exception handling doesn't mean repairing an exception. We have to define alternative way to continue rest
of the program normally. This way of defining alternative is nothing but exception handling.

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 51

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.

Fully checked Vs Partially checked:


A checked exception is said to be fully checked if and only if all its child classes are also checked.
Example:
1) IOException
2) InterruptedException
A checked exception is said to be partially checked if and only if some of its child classes are unchecked.
Example:
Exception
Note: The only possible partially checked exceptions in java are:
1. Throwable.
2. Exception.

Some built-in Exceptions:


1. Arithmetic exception: If attempt to divide with zero.
2. NumberFormatException: if conversion from string to number contains alphabets.
3. ArrayIndexOutOfBoundsException: if the index exceeds the size of the array.
4. NullPointerException: if you are trying to access members of a class through the object with out
allocating the memory to that object.
5. ClassCastException: improper conversion from one class to other class-type.
6. InterruptedException: if one thread interrupts the other thread.
7. IllegalThreadStateException: if any thread enters into undefined state.
8. UnsupportedOperationException: improper use of methods.
9. IOException: if any problem occurred in the reading and writing from and to devise and memory or
networks.
10. FileNotFoundException: if you are trying to do any operation on a file, which does not exist.
11. EOFException: if there are no more records.
12. MalformedURLException:URL-Uniform Resource Locater
If the format of the url is wrong
eg: correct url:-http://localhost:8080/mail/index.jsp
http://www.yahoomail.com/index.html
13. UnknownHostException: if the give host-name is invalid.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 52

Customized Exception handling by using try-catch:


 It is highly recommended to handle exceptions.
 In our program the code which may raise exception is called risky code, we have to place risky code
inside try block and the corresponding handling code inside catch block.
Example:
try
{
Risky code
}
catch(Exception e)
{
Handling code
}

Control flow in try---catch:


try{
statement1;
statement2;
statement3;
}
catch(X e)
{
statement4;
}
statement5;

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.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 53

Various methods to print exception information:


Throwable class defines the following methods to print exception information to the console.
printStackTrace():
This method prints exception information in the following format.
Name of the exception: description of exception, Stack trace
toString():
This method prints exception information in the following format.
Name of the exception: description of exception
getMessage():
This method returns only description of the exception.
Description.

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 54

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.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 55

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.

The result of following 2 programs is exactly same.


class Test class Test
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
System.out.println(10/0); throw new ArithmeticException("/by zero");
} }
} }

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.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 56

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

Exception handling keywords summary:


1. try: To maintain risky code.
2. catch: To maintain handling code.
3. finally: To maintain cleanup code.
4. throw: To handover our created exception object to the JVM manually.
5. throws: To delegate responsibility of exception handling to the caller method.

Customized Exceptions (User defined Exceptions):


Sometimes we can create our own exception to meet our programming requirements. Such type of
exceptions are called customized exceptions (user defined exceptions).
Example1:
1. InSufficientFundsException
2. TooYoungException
3. TooOldException
Program:
class TooYoungException extends RuntimeException
{
TooYoungException(String s)
{
super(s);
}
}
class TooOldException extends RuntimeException
{
TooOldException(String s)
{
super(s);
}
}

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 57

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:

class UserException extends Exception


{
String mesg;
public UserException ()
{
msg="unknown exception";
}
public UserException (String err)
{
msg = err;
}
public String toString()
{
return "Exception Caught:"+msg;
}
}
class InvalidLoginException extends UserException
{
public InvalidLoginException()
{
super ();
}
public InvalidLoginException(string msg)
{
super (msg);
}
}

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 58

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 59

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.

Thread life cycle:


A thread can be in one of the five states.
1) New: The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.
2) Ready: The thread is in ready 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.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 60

Methods to implement threads:

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.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 61

Defining a Thread by implementing Runnable interface:


We can define a Thread even by implementing Runnable interface also. Runnable interface present in
java.lang.pkg and contains only one method run().

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.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 62

Thread class constructors:


1. Thread t=new Thread();
2. Thread t=new Thread(Runnable r);
3. Thread t=new Thread(String name);
4. Thread t=new Thread(Runnable r,String name);
5. Thread t=new Thread(ThreadGroup g,String name);
6. Thread t=new Thread(ThreadGroup g,Runnable r);
7. Thread t=new Thread(ThreadGroup g,Runnable r,String name);
8. Thread t=new Thread(ThreadGroup g,Runnable r,String name,long stackSize);

Getting and setting name of a Thread:


 Every Thread in java has some name it may be provided explicitly by the programmer or
automatically generated by JVM.
 Thread class defines the following methods to get and set name of a Thread.
Methods:
1. public final String getName()
2. public final void setName(String name)

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 63

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 64

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 65

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.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 66

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.

1. public final void join()throws InterruptedException


2. public final void join(long ms) throws InterruptedException
3. public final void join(long ms,int ns) throws InterruptedException
Every join() method throws InterruptedException, which is checked exception hence compulsory we should
handle either by try catch or by throws keyword. Otherwise we will get compiletime error.
Example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("Sita Thread");
try
{
Thread.sleep(2000);
}
catch (InterruptedException e){}
}
}
}
class ThreadJoinDemo
{
public static void main(String[] args)throws InterruptedException
{
MyThread t=new MyThread();
t.start();
//t.join(); //--->1
for(int i=0;i<5;i++)
{
System.out.println("Rama Thread");
}
}
}
If we are commenting line 1 then both Threads will be executed simultaneously and we can't expect exact
execution order.
If we are not commenting line 1 then main Thread will wait until completing child Thread in this the output
is sita Thread 5 times followed by Rama Thread 5 times.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 67

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 68

public void run ()


{
try
{
while (true)
{
System.out.println("Message From:"+ t.getName()+":"+i);
i++;
Thread.sleep(stime);
}
}

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

public static void main (String args[])


{
Test t1 = new Test();
Test t2 = new Test("One");
Test t3 = new Test ("Two",250);
}
}

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 69

}
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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 70

Inter Thread communication (wait(),notify(), notifyAll()):


 Two Threads can communicate with each other by using wait(), notify() and notifyAll() methods.
 The Thread which is required updation it has to call wait() method on the required object then
immediately the Thread will entered into waiting state. The Thread which is performing updation of
object, it is responsible to give notification by calling notify() method. After getting notification the
waiting Thread will get those updations.
1. wait (): it is used to specify the methods commonly be waiting to access a resource.
2. notify(): to give the notification to a particular thread, which is waiting to access that resource.
3. notifyAll(): this is used to give notification to all those threads, which are waiting to access that
resource.
All the above methods must be written in synchronized block.
The above concept will be treated as producer and consumer problem, and the operations involved in that
problem will be as follows.
Producer consumer problem:
Producer(producer Thread) will produce the items to the queue and consumer(consumer thread) will
consume the items from the queue. If the queue is empty then consumer has to call wait() method on the
queue object then it will entered into waiting state. After producing the items producer Thread call notify()
method on the queue to give notification so that consumer Thread will get that notification and consume
items.
Source Code:
import java.io.*;
//critical section: buffer object is passed into both producer and consumer threads
class Buffer
{
String data;
boolean avail=false;
public synchronized void put(String data)//used by producer
{
while (avail==true)
{
try
{
wait ();
}
catch(Exception e)
{System.out.println(e);}
}
this.data=data;
System.out.println("Produced:"+data);
avail = true;
notify();
}
public synchronized String get() // used by consumer
{
while(avail==false)
{
try
{
wait (); // it throws InterruptedException
}
catch (exception e)
{System.out.println(e);}
}
avail = false;
notify ();
return data;
}
}
class Producer extends Thread
{
String data;
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
Buffer buf;
public Producer(Buffer buf)

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 71

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 72

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.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 73

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 create a ThreadGroup by using the following constructors


ThreadGroup g=new ThreadGroup(String gName);

We can attach a Thread to the ThreadGroup by using the following constructor of Thread class
Thread t=new Thread(ThreadGroup g, String name);

ThreadGroup g=new ThreadGroup("Printing Threads");


MyThread t1=new MyThread(g,"Header Printing");
MyThread t2=new MyThread(g,"Footer Printing");
MyThread t3=new MyThread(g,"Body Printing");
-----------
g.stop();

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 74

IO Streams or File Handling

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.

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 75

File class constructors:


1. File f=new File(String name);
Creates a java File object that represents name of the file or directory in current working directory.
2. File f=new File(String subdirname,String name);
Creates a File object that represents name of the file or directory present in specified sub directory.
3. File f=new File(File subdir,String name);

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 76

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

Example7: Write a program to display only file names


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) {
File f1=new file(f,s1);
if(f1.isFile()) {
count++;
System.out.println(s1);
}
}
System.out.println("total number : "+count);
}
}

Example8: Write a program to display only directory names


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)
{
File f1=new file(f,s1);
if(f1.isDirectory())
{
count++;
System.out.println(s1);

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 77

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

//stream closing operations


fis.close();
fos.close();
}
}

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 78

Limitation of byte streams:


It reads the data only one byte at a time hence it takes more time to copy.
Must close the streams always.
These streams always hitting hard disk to retrieve the data it reduces the performance.
Character streams:
Program uses character stream to perform input & output of character data. All character stream classes
developed based on Reader & Writer classes.

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 79

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.

To overcome above limitations use buffered streams.


 Bufferd input stream read the data from buffered memory and it interacting with hard disk only when
buffered memory is empty.
 Buffered output stream write the data to buffer memory.
There are four buffered stream classes.
Buffered byte streams,
1. BufferedInputStream
2. BufferedOutputStream
A program can convert an un buffered stream into buffered streams.
new BufferedInputStream(new FileInputStream("xanadu.txt"));
new BufferedOutputStream(new FileOutputSream("byteoutput.txt"));
Buffered Character streams,
3. BufferedReader
4. BufferedWriter
A program can convert an un buffered stream into buffered streams.
new BufferedReader(new FileReader("ratan.txt"));
new BufferedWriter(new FileWriter("characteroutput.txt"));

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)

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 80

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

Example12:Program to Write the Data into the File using FileWriter


import java.io.*
class FileWrite
{
public static void main(String args [])
{
try
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
File f=new File(args[0]);
String data;
BufferedWriter fout=new BufferedWriter(new FileWriter(f));
while(true)
{
System.out.println("Enter some lines of text (end-stop):");
data=b.readLine();
if(data.equals("end"))
break;
fout.write(data,0,data.length());
}
fout.close ();
}catch(Exception e)
{
System.out.println(e);
}

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 81

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 82

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

Application: compiler designing, spelling check etc

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

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem


OOP’s through JAVA 83

sal=Double.parseDouble(b.readLine ());
ps.println(eno);
ps.println(ename);
ps.println(sal);
ps.close();
}catch(Exception e)
{System.out.println(e);}
}
}

M. Srinu, Dept of CSE. Aditya Engineering College, Surampalem

You might also like