Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Principles Of Object oriented programming
Object orientation is one of the programming styles or methodologies. As far as
application development is concerned, following are the important object oriented
features.
1. Encapsulation
2. Inheritance
3. Polymorphism
Encapsulation: We develop applications mostly for data processing. Application’s
data is stored in variables. Code (instructions grouped in functions) acts upon these
variables to process data. “ The act of combining data and eligible code that acts
upon data” is known as encapsulation. Encapsulation allows us to hide information
from ineligible code of the application and there by data processing is secure.
In an object oriented system (application), encapsulation is realized through class
& object. In a class, we combine variables and eligible functions (methods in java).
Total application is divided into classes. Variables and methods (functions) of one
class are not accessible in other classes unless access permissions are granted. By
defining a class in an application, we are defining a user defined data type. In order
to store data and process it, we have to instantiate the class. An instance of a class
is nothing but an object. An object holds data and code that acts upon the data. “An
object oriented system is a collection of objects”.
Inheritance: Creating new classes from already existing classes through is-a
relationship is known as inheritance. Already existing classes are known as super
classes and newly created classes are known as a sub classes. Sub classes inherit
variables and methods from super classes. Therefore, inheritance offers reusability of
code. Code reusability improves productivity and consequently software can be
developed at competitive prices.
Polymorphism: An object behaving differently in different situations is nothing but
the object is exhibiting polymorphism. One interface, multiple forms is the key
feature of polymorphism. Here, interface means method of the object. With same
method name, multiple definitions will be there in a class. Each definition performs
one task. With same method call we can get multiple services from the object.
Polymorphism offers flexibility and extensibility of code.
Core Java
1
Introduction to Java Programming Language
Java is an object oriented programming language from Sun Microsystems.
Gosling has developed Java language.
James
Even though Java is used in many areas,
programming community treats Java as a language for Internet programming (web
programming). Syntactically Java is similar to “C” programming language. Java was
first released publicly in November 1995.
Versions of Java
Versions of Java language usually correspond to the Java Development Kit (JDK). If
we want to develop, compile and execute Java programs, we need to install the Java
software (JDK) in our computer. When Java was first released, its version was 1.0.
Few additional features have been added with every new release (1.1,1.2,1.3,1.4
etc). Even though the current version of Java is 6 (at the time writing of this book),
industry is widely using J2SE 5 platform (JDK1.5 version). Therefore, we will learn
Java programming language version 5.0.
Java language Features
When Java was first created, Sun Microsystems described it with a series of
buzzwords.
performance,
“Java is simple, object oriented, robust, secure, portable, higharchitectural,
interpreted,
multithreaded,
distributed,
dynamic
language”.
Simple: - Java programming language is very easier. It is syntactically similar to C
and C++. Complex features of these languages are either simplified or totally
eliminated in Java.
Object Oriented: Object orientation is a new programming paradigm (principle).
Java language has built-in support to develop applications using this methodology.
Robust: - Applications (programs) developed in java withstand against failure.
Automatic dynamic memory reclaiming and excellent exception handling mechanism
contribute to this feature.
Secure:
Java is the language for the Internet.
system resources in the Internet environment.
Any malicious code can spoil the
Java programs are insulated from
that. The moment any malicious code trying to influence the system resources, java
programs get terminated instead of spoiling the system. Java Runtime Environment
contributes here.
Portable: Programs developed in Java can be compiled in a variety of operating
environments without modifications to the source code.
Core Java
Memory size of Java
2
variables is the same in any environment.
This is another contributing factor for the
portability of java applications.
High-Performance: - When compared to other interpreted languages, Java offers
high performance. Just-in-time compiler contributes towards this.
Architectural-neutral: This feature is in accordance with the Sun Microsystems
slogan about java programs.
“Write once and run anywhere”.
famously known as platform independence.
This feature is
A Java Program is compiled to class
file(s). These files can run on any machine with any host operating system as long
as JVM is available for that OS.
Interpreted: Java programs are both compiled and interpreted. JVM interprets the
class file into machine code.
Multithreaded: Performing more than one job at a time (concurrently) is the main
goal of either multitasking or multithreading.
In case of multitasking, multiple
processes are required to perform multiple jobs. Where as, in case of multithreading
a single program performs multiple jobs concurrently. Java has built-in features to
implement multithreaded applications. Java’s contribution towards multithreading is
that it has brought system level programming concept to application level.
Distributed:
computing.
Java has rich libraries for network programming and distributed
As java is mainly meant for Internet based programming, it is no
surprise that java is distributed.
An application is said to be distributed if the
business objects are geographically dispersed in the network and communicating one
another.
Dynamic: Memory allocation for application objects and libraries inclusion in
programs is dynamic in java.
First Java Program
/*
This program prints “Hello, Java World” on the screen
Source Code: - one.java
*/
class ProgramOne
{
public static void main(String args[])
{
System.out.println(“Hello, Java World”);
}
}
Core Java
3
Data Types
Java language has 8 primitive data types.
int
short
byte
long
float
double
char
boolean
int, short, byte and long are integral data types. All these data types are used to
declare variables that can store non-decimal numbers.
Data type
Memory in bytes
Range of values
int
4
-21474883648 to 21474883647
short
2
-32768 to 32767
byte
1
-128 to 127
long
8
-9223372036854775808
to 9223372036854775807
Numeric values that are not integral are stored in floating-point numbers. float and
double are used to store decimal numbers. If we need accuracy up to 7 digits after
decimal point, we use float type. If we need accuracy up to 17 digits after decimal
point, we use double type.
Floating-point literals are by default double type. If we want to specify a floating
point literal, we should explicitly mention f or F. For example,
float a=45.6F;
char primitive type variable occupy 2 bytes of memory in Java. In C & C++
languages it takes only 1 byte of memory. Java supports Unicode characters. While
assigning a character literal to a variable in Java, we have to enclose it in single
quotes (similar to C and C++). For example,
char grade=’A’;
We can use arithmetic on char variables.
grade +=1;//Earlier grade holds ‘A’ and now it holds B.
Variables of type boolean can have only one of two values, true or false.
For example,
boolean ismanager=false;//ismanager variable holds false literal now.
Core Java
4
Operators in Java
Almost all the operators in Java are similar to that of C & C++ programming
languages with very few exceptions. Their meaning and functionality is similar in
Java as well.
Arithmetic Operators:
+, -, *, /, %
Relational Operators:
==, !=, >, < , >=, <=
Assignment operators:
=, +=, -=
Logical Operators:
!, ||, &&
Note: - Bitwise operators in Java are similar to that of C except unsigned right shift
operator >>>. It is seldom used in applications.
Variable Declaration: - In Java, variables are declared with C & C++ syntax only.
<data type> variablename;
Key points about variables declaration and their usage
We can declare variables any where within the program. The kind of
restriction in ‘C’ is removed.
No format specifiers (unlike in ‘C’)
Initializing variables, or assigning values to variables is similar to that of ‘C’.
Variables declared in a method are known as local variables. Local variables
must not be used without giving a value to them.
No garbage values for variables in Java.
/*
Program to add two numbers and display the sum
Source code: - add.java
*/
class AddTwoNumbers
{
public static void main(String args[])
{
int n1,n2,sum;
n1=20;
n2=30;
sum=n1+n2;
System.out.println(“The sum of two numbers is:”+sum);
}
}
Core Java
5
Observations to be made
1. Plus operator acts as the string concatenation operator. To separate the string
and the variable “sum” we use + operator in Java.
2. We did not prompt the user to enter data from the keyboard. Java supports
that kind of programming (similar to printf & scanf in C). Without knowing
exception handling & IO streams concepts we cannot do that in Java.
/*
Program to display the bigger of the two numbers
Source code: - bigger.java
*/
class BiggerNumber
{
public static void main(String args[])
{
int n1=23;
int n2=32;
if(n1>n2)
System.out.println(n1+ “ is bigger than “+n2);
else
System.out.println(n2+ “ is bigger than “+n1);
}
}
Observations to be made
1. Decision making in a Java program is similar to ‘C’ programming.
2. All kinds of “if” conditions are available in Java. I.e. simple if, if else, if else
ladder, nested if etc.
/*
Program to display the gross salary of an employee.
Source code: - gross.java
*/
class GrossSalary
{
public static void main(String args[])
{
float basic=5000;
Core Java
6
float da=0.4f*basic;
float hra=0.3f * basic;
float gross=basic+da+hra;
System.out.println(“Gross salary of the employee is Rs.”+gross);
}//main
}//class
Observations to be made
1. When we use a float literal value in a Java program, by default it is treated as
double value in Java. Therefore compilation error comes. To explicitly mention
that it is float value, we append f or F to the decimal number.
2. Variables can be dynamically initialized in Java. In the above example, “gross”
variable is declared and at the same time initializing it through some result of
a calculation. This feature is not there in ‘C’.
Program to print numbers from 1 to 5 three times, each time using a different loop.
Source code: - loop.java
class PrintOneToFive
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
System.out.println(i);
int i=1;
while(i<=5)
{
System.out.println(i);
i++;
}
i=1;
do
{
System.out.println(i);
i++;
} while(i<=5);
}//main()
}//class
Core Java
7
Observations to be made
1. All kinds of loops in Java are similar to that of ‘C’ as far as syntax is
concerned.
2.
If we write a “for loop” in ‘C’, the loop counter will be declared before we
write the loop. In Java, within the “for loop” itself we can declare it and
initialize it.
3. Variable declared within for loop is available in that loop only. Therefore we
could declare a variable ‘i’ again.
/*Program that prints a multiplication table of 5 up to 10 multiples.
Source code:- table.java */
class MultiplicationTable
{
public static void main(String args[])
{
int n=5;
int product;
for(int i=1;i<=10;i++)
{
product=n*i;
System.out.println(n+" X "+i+" = "+product);
}
}//main()
}//class
Output of the program
5X1=5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
Core Java
8
Q) What is the output of the following program?
class Output
{
public static void main(String args[])
{
int i;
System.out.println(i);
}
}
The above program will not print any garbage value. It causes a compilation error.
The variable “i” is local. We did not give proper value to it. We are trying to use it.
The following compilation error is generated.
variable i might not have been initialized
Q) What is the output of the following program?
class Output
{
public static void main(String args[])
{
int sum;
for(int i=1;i<=5;i++)
sum=sum+i;
System.out.println(“The sum of first five natural numbers is:”+sum);
}
}
The above program also causes compilation error. The variable “sum” is declared
locally in the main method. It is used in the for loop without proper value in it before
first use.
The following compilation error is generated.
variable sum might not have been initialized
Note:- All the previous examples are meant for proving that syntax wise java is
similar to ‘C’. Wherever java differs also we have seen. But the purpose of Java is
not yet explored. Java is mostly used in Object oriented business system
development.
Core Java
9
Object Oriented Programming in Java
Q) Write a program to represent 2 books information.
class Book
{
String title;
String author;
float price;
void giveDataToBook(String t,String a, float p)
{
title=t;
author=a;
price=p;
}
void displayBookDetails()
{
System.out.println("Book Title:"+title);
System.out.println("Author of the Book:"+author);
System.out.println("Book price:Rs."+price);
}
}
class ExecuteBook
{
public static void main(String args[])
{
Book b1=new Book();
b1.giveDataToBook("Complete Reference","Herbert Schildt",310);
System.out.println("The first book details");
b1.displayBookDetails();
Book b2=new Book();
b2.giveDataToBook("Thinking in Java","Bruce Euckle",350);
System.out.println("The second book details");
b2.displayBookDetails();
}//main
}//class
Core Java
10
Output of the above program
The first book details
Book Title:Complete Reference
Author of the Book:Herbert Schildt
Book price:Rs.310.0
The second book details
Book Title:Thinking in Java
Author of the Book:Bruce Euckle
Book price:Rs.350.0
Observations to be made in the above program
1. In the above program we defined two classes. Book class and ExecuteBook
class. The first class is defined to create a user defined data type “Book”.
Given question is to represent 2 books information. Programmatically they are
two book objects. To create an object we need a class. Hence Book class is
defined.
2. ExecuteBook class defined only to encapsulate main(). We could have written
main() in Book class also. But it is not a good programming practice to do so.
3. In the Book class we created 3 variables. They are the properties of each
book instance. They are known as instance variables in Java(data members
in C++).
4. giveDataToBook() and displayBookDetails() are the functions of Book class. In
Java we should not call them functions. They are known as method. Precisely
“instance methods”.
5. In the Book class we combined variables and code(methods) that act upon
the variables. I.e. we are wrapping up of data and code in a class. Therefore
we say that class is the basis of encapsulation.
6.
In main method, we created 2 book objects. Syntax to create an object in
Java is as follows.
new classname();
With the above syntax, an object is created. But we cannot use it later in a
Java program. Therefore, we write the Object creation syntax to hold the
reference of the object so that we can use the object later.
Book b1=new Book();// b1 is the reference of the first book object.
Book b2=new Book();//b2 is the reference of the second book object.
7. Using the references b1 and b2 we called 2 methods on the book objects.
Core Java
11
Q) Write a program to represent one car information.
//Source code: Car.java
class Car
{
String regno;
String color;
String make;
float price;
void giveDataToCar(String r,String c, String m,float p)
{
regno=r;
color=c;
make=m;
price=p;
}
void displayCarDetails()
{
System.out.println("Registration No:"+regno);
System.out.println("Color:"+color);
System.out.println("Car Make:"+make);
System.out.println("Price:Rs."+price);
}
}//Car
class ExecuteCar
{
public static void main(String args[])
{
Car c=new Car();
c.giveDataToCar("AP11Q3579","white","Maruti 800 A.C",220000);
System.out.println("Car details....");
c.displayCarDetails();
}main()
}//class
Core Java
12
Output of the program
Car details....
Registration No:AP11Q3579
Color:white
Car Make:Maruti 800 A.C
Price:Rs.220000.0
Constructors in Java
A constructor is a specialized method in Java whose name and class name is the
same and is called automatically as soon the object is created. Primary purpose of a
constructor is object initialization. If we don’t write any constructor in a class, Java
compiler provides a zero argument constructor for the class by default. We can write
our own zero argument constructor also in a class. We can have parameterized
constructor also in a class.
class Student
{
int regno; String name;
Student(int rno,String n)
{
regno=rno;
name=n;
}//Parameterised constructor
Student()
{
regno=1001;
name="Rama";
}//zero argument constructor
void displayStudentDetails()
{
System.out.println("Student Registration No:"+regno);
System.out.println("Name:"+name);
}
} //Student class
Core Java
13
class ExecuteStudent
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println("First student details.....");
s1.displayStudentDetails();
Student s2=new Student();
System.out.println("Second student details.....");
s2.displayStudentDetails();
Student s3=new Student(1003,"Ravi");
System.out.println("Third student details.....");
s3.displayStudentDetails();
}//main
}//class
Program output
First student details.....
Student Registration No:1001
Name:Rama
Second student details.....
Student Registration No:1001
Name:Rama
Third student details.....
Student Registration No:1003
Name:Ravi
Observations to be made
1.
When we use zero argument constructor syntax in the object, every object is
getting the same data.
2.
If we use parameterized constructor in the syntax of the object creation, we
can give different data for different object.
Student s1=new Student();//zero argument constructor
Student s2=new Student();//zero argument constructor
Student s3=new Student(1003,”Ravi”);//Parameterized constructor
Core Java
14
Q) What is the output of the following program?
class Student
{
int regno;
String name;
Student(int rno,String n)
{
regno=rno;
name=n;
}//Parameterised constructor
void displayStudentDetails()
{
System.out.println("Student Registration No:"+regno);
System.out.println("Name:"+name);
}
}
class ExecuteStudent
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println("First student details.....");
s1.displayStudentDetails();
}
}
The above program causes compilation error as follows.
cannot resolve symbol
symbol : constructor Student ()
location: class Student
Student s1=new Student();
^
1 error
Reason
class has no zero argument constructor that we used in the object creation syntax.
Core Java
15
Q) What is the output of the following program?
class Student
{
int regno;
String name;
Student(int regno,String name)
{
regno=regno;
name=name;
}//Parameterised constructor
void displayStudentDetails()
{
System.out.println("Student Registration No:"+regno);
System.out.println("Name:"+name);
}
}
class ExecuteStudent
{
public static void main(String args[])
{
Student s1=new Student(100001,"David");
System.out.println("student details.....");
s1.displayStudentDetails();
}
}
When we compile and execute the above program the following Output is generated.
student details.....
Student Registration No:0
Name:null
Observations to be made
1. We supplied values to the constructor of the student class while creating the
object.
2. Because of the name clash between instance variables and parameters, we
are getting the above output.
3. To remove the name clash we have to use this keyword in the constructor.
Core Java
16
Student(int regno,String name)
{
this.regno=regno;
this.name=name;
}
Access specifiers in Java
private, protected and public are the access specifiers in Java. We apply these access
specifiers to the members of the class. I.e. variables and methods of the class. If a
member is not associated with these three keywords, it will have default accessibility
mode in Java.
If a member of a class has private accessibility mode, it is accessible only
from the methods of the same class.
If a member of a class has default accessibility mode, it is accessible to all the
methods of those classes that are present in the same package.
If a member of a class has protected accessibility mode, it is accessible to all
the methods of those classes that are present in the same package plus all
child class methods.
If a member of a class has public accessibility mode, it is accessible to all the
methods of the entire java environment.
Note: - In Java, a class can also be declared public.
Class A
{
private int a;
A(int a)
{
this.a=a;
}
void display()
{
System.out.println(“a=”+a);
}
}
Core Java
17
class Main
{
public static void main(String args[])
{
A o=new A(10);
o.a=30;//error
o.display();
}
}
The above program raises compilation error as follows.
a has private access in A
Reason
main method cannot directly modify “a” value. Main method is not the member of
class A.
Method Overloading
If we define multiple methods with the same name with different signatures in a
class, such concept is known as method overloading. We implement polymorphism in
Java using this concept.
For example,
class A
{
void add(int a, float b)
{
}
void add(float a, int b)
{
}
}
In class A add method is overloaded. In a class, signatures of methods with same
name are said to be different if at least any one of the following criteria mismatches.
1. number of parameters
2. order of parameters
3. type of parameters
Core Java
18
Q) Example program on method overloading
class Car
{
String regno; String color; String make; float price;
void giveDataToCar(String r,String c, String m,float p)
{
regno=r;
color=c;
make=m;
price=p;
}
void giveDataToCar(float p)
{
price=p;
}
void displayCarDetails()
{
System.out.println("Registration No:"+regno);
System.out.println("Color:"+color);
System.out.println("Car Make:"+make);
System.out.println("Price:Rs."+price);
}
}//Car
class ExecuteCar
{
public static void main(String args[])
{
Car c=new Car();
c.giveDataToCar("AP11Q3579","white","Maruti 800 A.C",22000);
System.out.println("Car details....");
c.displayCarDetails();
c.giveDataToCar(220000);//Overloaded method call
System.out.println("Car details....");
c.displayCarDetails();
}main()
}//class
Core Java
19
Implementing inheritance in Java
Creating child classes from the parent classes using “extends” keyword is nothing
but implementing inheritance in Java. In the following example, Vehicle is the super
class and “Car” is the sub class.
Sub class inherits variables and methods of the super class. This promotes code
reusability.
Q) Example program on Inheritance.
class Vehicle
{
int wheels;
Vehicle()
{
wheels=4;
}
void move()
{
System.out.println("Every vehicle will move this way");
}
}//super class
class Car extends Vehicle
{
void display()
{
System.out.println("car has "+ wheels+" wheels");
}
}//sub class
class Main
{
Core Java
20
public static void main(String args[])
{
Car c=new Car();
c.move();//inherited method
c.display();
}
}
Output
Every vehicle will move this way
car has 4 wheels
Q) Example program on inheritance
class Person
{
protected int age;
protected String name;
void giveDataToAnyPerson(int age,String name)
{
this.age=age;
this.name=name;
}
void displayPersonDetails()
{
System.out.println("Age:"+age);
System.out.println("Name:"+name);
}
}//super class
class Employee extends Person
{
int empno;
float salary;
void giveDataToEmployee(int age,String name,int eno,float sal)
{
giveDataToAnyPerson(age,name);
empno=eno;
Core Java
21
salary=sal;
}
void displayEmployeeDetails()
{
displayPersonDetails();
System.out.println("Empno:"+empno);
System.out.println("Salary:Rs."+salary);
}
}//sub class 1
class Student extends Person
{
int rollno;
int marks;
void giveDataToStudent(int age,String name,int rno,int m)
{
giveDataToAnyPerson(age,name);
rollno=rno;
marks=m;
}
void displayStudentDetails()
{
displayPersonDetails();
System.out.println("Rollno:"+rollno);
System.out.println("marks."+marks);
}
}//sub class 2
class InheritanceExample
{
public static void main(String args[])
{
Employee e1=new Employee();
e1.giveDataToEmployee(23,"Rahim",10001,6000);
System.out.println("employee details");
e1.displayEmployeeDetails();
Student s1=new Student();
Core Java
22
s1.giveDataToStudent(18,"Rama",1,46);
System.out.println("student details");
s1.displayStudentDetails();
}//main()
}//class
Output of the program
employee details
Age:23
Name:Rahim
Empno:10001
Salary:Rs.6000.0
student details
Age:18
Name:Rama
Rollno:1
marks.46
Method overriding
Changing the definition of the parent class method in the sub class is known as
method overriding. To implement method overriding we have to follow the given
rules.
1. super class method and sub class method signatures should be the same.
2. Their return type should be the same.
3. sub class method should not have weaker access privileges than that of super
class method
4. sub class method should not have more number of checked exceptions in the
throws clause list.
Note: - After implementing method overriding, if we call the method on the sub
class object, sub class version only be called.
Q) Example program on method overriding.
class Vehicle
{
void move()
{
System.out.println("Every vehicle moves this way");
Core Java
23
}//overridden method
}//super class
class Car extends Vehicle
{
void move()
{
System.out.println("As a car I want to move in my own way");
}//overriding method
}
class OverridingExample
{
public static void main(String args[])
{
Car c=new Car();
c.move();
}
}
When we execute the above program, the following output comes.
As a car I want to move in my own way
Some times we may have to have our own functionality and also in need of the
parent given functionality. In such a case, super keyword is used as follows
class Car extends Vehicle
{
void move()
{
super.move();
System.out.println("As a car I want to move in my own way");
}//overriding method
}
When we execute the above program, the following output comes.
Every vehicle moves this way
As a car I want to move in my own way
Note:- super keyword must be used from sub class only.
Core Java
24
Dynamic Method Dispatch
When super class reference is referring to sub class object and method overriding is
implemented, making a method call is nothing but dynamic method dispatch.
Q) Example program on dynamic method dispatch
class Vehicle
{
void move()
{
System.out.println("Every vehicle moves this way");
}//overridden method
}
class Car extends Vehicle
{
void move()
{
System.out.println("As a car I want to move in my own way");
}//overriding method
}
class DynamicMethodDispatch
{
public static void main(String args[])
{
Vehicle v=new Car();
v.move();
}
}
When the above program is executed the following output comes.
As a car I want to move in my own way
Observations to be made
1. Reference is of type super class
2. “v” is referring to sub class object
3. Using the super class reference, the call is made.
Core Java
25
Constructors in inheritance
Whenever sub class object is created, super class zero argument constructor is
executed first and then sub class one executed. Whenever the sub class object is
created, its constructor is called first. From there an implicit call is made to the super
class zero argument constructor. If it is found, it will be executed. If not found, error
will be reported. Sub class object creation fails.
Q) What is the output of the following program ?
class A
{
A()
{
System.out.println("super cnstr");
}
}
class B extends A
{
B()
{
System.out.println("sub cnstr");
}
}
class C
{
public static void main(String args[])
{
B b=new B();
}
}
When the above program is executed, the following output is displayed.
super cnstr
sub cnstr
Core Java
26
Q) What is the output of the following program?
class A
{
A(int a)
{
System.out.println("super cnstr");
}
}
class B extends A
{
B()
{
System.out.println("sub cnstr");
}
}
class C
{
public static void main(String args[])
{
B b=new B();
}
}
The above program generates compilation error. Object creation fails at compilation
level itself. The reason is, in the super class there is no zero argument constructor
available.
To overcome this problem we have 2 options. Either defining the zero argument
constructor in the super class or to make an explicit call from the sub class
constructor to the super class constructor as follows.
B()
{
super(10);
System.out.println("sub cnstr");
}
Note:- Call to the super class constructor should be the first statement in the sub
class constructor.
Core Java
27
Modifiers in Java
static, abstract and final are three important modifiers in Java. When we apply
them to the members of a class their meaning will be changed.
static variables
These are used to represent the whole class level information rather than
individual object information. Per class only one copy of static variables is
created. A static variable can be referred by class name.
Q) Example program on static variable usage.
class Employee
{
static int count;
Employee()
{
count++;
System.out.println("Employee appointed");
}
void getEmpCount()
{
System.out.println("No. of employees appointed:"+count);
}
}
class StaticExample
{
public static void main(String args[])
{
System.out.println("No. of employees appointed:"+Employee.count);
Employee e1=new Employee();
e1.getEmpCount();
Employee e2=new Employee();
e2.getEmpCount();
}//main()
}//class
Core Java
28
When the program is executed the following output comes.
No. of employees appointed:0
Employee appointed
No. of employees appointed:1
Employee appointed
No. of employees appointed:2
static methods
If a method of a class is declared static, it becomes the class method. We can call
that method directly on the class.
ClassName.method();
In the previous example, if “count” variable is made private, we cannot access it
directly from main method. In such a case, getEmpCount() should have been
made static.
Q) Static method example
class Employee
{
private static int count;
Employee()
{
count++;
System.out.println("Employee appointed");
}
static void getEmpCount()
{
System.out.println("No. of employees appointed:"+count);
}//static method definition
}
class StaticExample
{
public static void main(String args[])
{
Employee.getEmpCount();//static method call
Employee e1=new Employee();
e1.getEmpCount();
Core Java
29
Employee e2=new Employee();
e2.getEmpCount();
}
}
Note:- Without a reference we should not reference an instance variable or an
instance method in a static method. If object is available, a static method can be
called using object reference also.
final modifier
We can associate this modifier with variables, methods and classes also.
final variables: - We declare constants in java using final. Final variables must be
defined. Their value cannot be changed once they are defined.
For example,
class A
{
final int a=10;
}
final methods:- If a method is declared final, it can be inherited but it cannot be
overridden.
For example,
class A
{
final void x() { }
}
class B extends A
{
void y()
{
x();//allowed because final method is inherited
}
void (x){}//not allowed because final methods cannot be overridden.
}
final class: - If a class is declared final, it cannot be inherited. In a hierarchy of
classes, the most specialized class can generally be declared “final” if we want.
For example,
final class A{} class B extends A{} // not allowed
Core Java
30
abstract modifier
abstract modifier is associated with methods and classes only. If a class is declared
abstract, it has all the features of a non-abstract class except in one thing. We
cannot create the instance of an abstract class. An abstract method has only
declaration but no definition. Declaring a method abstract means that we are forcing
all the sub classes to override (implement) that method.
For example,
abstract class Diagram
{
abstract void draw();
}
If a method is declared abstract, the class in which it is declared also must declared
abstract. In a hierarchy of classes the most generalized class is generally declared
abstract. Every sub class of an abstract class must implement all the abstract
methods of its super class.
For example,
class Square extends Diagram
{
void draw()
{
System.out.println(“square is drawn”);
}
}
class Rectangle extends Diagram
{
void drawSquare()
{
}
}
When we compile the source code, Compiler reports an error saying that “Rectangle”
class should be declared abstract. It is inheriting from an abstract class “Diagram”,
but not overriding the draw() method. To rectify the error, either we have to declare
the Rectangle class abstract OR implement the draw() method.
Note: - We cannot declare a variable as abstract in Java.
Core Java
31
INTERFACES
An interface is a named collection of method declarations (without implementations).
An interface can have only abstract methods. It also can have constants (only) also.
For example,
interface I1
{
public static final int VALUE=10;
public abstract void x();
}
In the above example, VALUE is the constant. We need not use the 3 keywords for it.
It is implicitly public, static and final. For the method x() public and abstract are
implicitly available.
A class can inherit an interface. For example,
interface I2{}
class A implements I2
{
}
In the above example, I2 is the parent and A is the sub class. If a class is inheriting
from an interface, the class must implement all the abstract methods of the
interface. Otherwise, the class also should be declared abstract.
All the members of an interface are by default public. A class can inherit from any
number of interfaces.
For example,
class A implements I1, I2 {}
An interface reference can be created. But its instance cannot be created.
Q) Example program on interface.
interface I1
{
void y();
}
class A implements I1
{
public void y()
{
Core Java
32
System.out.println(“ Some functionality”);
}
}//sub class
class InterfaceExample
{
public static void main(String args[])
{
I1 i=new A();
i.y();
}
}
Observations to be made
1. I1 is acting as the parent type of class A.
2. Parent type reference can refer to the sub class object.
3. In the interface I1, y() is public and abstract. Therefore, we must override it
in the sub class A.
One interface can inherit from another interface. Here, extends keyword is used. If a
class is implementing sub interface, the class should implement all the methods of
super interface as well as the sub interface.
interface I1
{
void x();
}
interface I2 extends I1
{
void y();
}
class A implements I2
{
public void x()
{
//some implementation
}
void y()
{
//some implementation
}
}//sub class
Core Java
33
PACKAGES
A package is a collection of related class files. To make classes easier to locate and
use, to control access and to control class-naming conflicts, we bundle collection of
related classes and interfaces into packages. Packages are classified into standard
and user defined. lang, util, io, net, awt, applet etc. are some of the important
standard packages. In these packages library class files are stored. For every Java
program lang package is automatically available. We have to include any other
package explicitly into the Java program if we need any library class file from that
package. For example, in order to include io package we use the import statement
import java.io.*;
We can create our own packages known as user defined packages. We group our
own application class files into the user-defined package. In order to create our own
package, in the java program we have to use the package statement as the first
statement.
For example, package mypack;
Q) Example program that creates a user defined package.
package mypack;
public class A
{
public void x()
{
System.out.println(“user defined package example”);
}
}
Now we compile the program as follows. javac –d . A.java
With the above command, mypack directory(package) is created in the current
working directory. A.class file is stored in mypack. In order to use the user defined
package, we need to set the classpath to the directory in which mypack is stored.
Then import the mypack and make use of class A and its method.
import mypack.A;
class C{
public static void main(String args[]){
A a=new A(); a.x();
}
}
Core Java
34
Arrays in Java
An array is a collection of homogeneous elements referred by the same name. An
array is also known as sub-scripted variable. An array is created in Java with the
following syntax.
datatype arrayriable[]=new datatype[size];
For example,
int a[]=new int[10];
The above syntax creates an integer array of size 10. In Java, arrays are internally
represented as objects. Every array has property known as length that gives the size
of the array.
Q) Write a program to store first 5 natural numbers in an array and display them.
/*
source code:- ArrayExample.java
*/
class ArrayExample
{
public static void main(String[] args)
{
int arr[]=new int[5];
for(int i=0;i<arr.length;i++)
arr[i]=i+1;
System.out.println("elemtns of the array..........");
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
}
Program output
elemnts of the array..........
1
2
3
4
5
Core Java
35
User defined arrays
Whenever an array of user defined data type is created, an array of objects is not
created. Instead, an array of references is created.
For example, Student s[]=new Student[5];
Q) Example program on user defined arrays
class Student
{
int rollno;
Student(int rno)
{
rollno=rno;
}
void display()
{
System.out.println("Rollno:"+rollno);
}
}
class ArrayOfObjects
{
public static void main(String[] args)
{
Student s[]=new Student[4];;
for(int i=0;i<s.length;i++)
s[i]=new Student(i+1);
System.out.println("Objects are...");
for(int i=0;i<s.length;i++)
s[i].display();
}
}
Objects are...
Rollno:1
Rollno:2
Rollno:3
Rollno:4
Core Java
36
Exception Handling
An exception is an abnormal situation that arises during program execution. I.e. an
exception is a runtime error. An exception in Java is an object that describes the
exceptional or abnormal event that occurred during program execution. This
exception object holds information about the nature of the problem. Whenever an
abnormal situation arises during program execution, the object identifying the
exceptional circumstance is tossed as an argument to the exception handler. We say
that the exception is thrown by the JVM and is caught by the handler. Exceptions
are classified into two kinds.
1. Standard exceptions
2. User defined exceptions
Pre-created exception classes are known as standard exceptions. Our own created
exceptions are known as user defined exceptions.
java.lang.Throwable class is the super class of all exception classes in Java. It has 2
sub classes.
1. Error
2. Exception
Application developers cannot handle Java.lang.Error class and its sub classes
representing abnormal conditions. Java.lang.Exception class has 2 kinds of sub
classes.
1. Checked exception classes
2. Unchecked exception class
Java.lang.RuntimeException and its sub classes are unchecked exception classes.
Except this class, all other sub classes of Exception class are checked exceptions.
Java’s exception handling mechanism has provided 5 keywords to deal with
exceptions.
1. try
2. catch
3. throw
4. throws
5. finally
try keyword is used to keep the doubtful code under observation. catch is the
exception handler. throw is used to explicitly throw exceptions. throws keyword is
used to announce that a method has doubtful body. finally
Core Java
keyword is used to
37
create a block of statements that execute definitely in both the cases. I.e. in
exception generated case and non-generated class also.
Q) Example program on exception handling.
//source code: - ArithmeticExample.java
class ArithmeticExample
{
public static void main(String[] args)
{
int numerator,denominator,quotient;
numerator=Integer.parseInt(args[0]);
denominator=Integer.parseInt(args[1]);
try
{
quotient=numerator/denominator;
System.out.println(“The result of division is:”+quotient);
}
catch(ArithmeticException e)
{
System.out.println(“please ensure that second argument is a non-zero”);
e.printStackTrace();
}
}//main
}//class
Observations to be made
1. At the command prompt we give the following command to run this program.
>java ArithmeticExample 12 2
2. Because of the proper input, no exceptions is raised and hence output of the
program will be The result of division is 6
3. If exception is not raised, catch is not at all executed.
4. If we supply the second command line argument 0, ArithmeticException is
raised in the try block and control comes to the catch block.
5. When the exception is raised, instead of program getting terminated, try
block gets terminated.
6. The message in the catch block will be displayed to the end user.
Core Java
38
7. printStackTrace() displays the error type, error message and its originated
place.
Q) Example program on multiple catch blocks for a single try block.
//source code: - MultiCatchExample.java
class MultiCatchExample
{
public static void main(String[] args)
{
int numerator,denominator,quotient;
try
{
numerator=Integer.parseInt(args[0]);
denominator=Integer.parseInt(args[1]);
quotient=numerator/denominator;
System.out.println(“The result of division is:”+quotient);
}
catch(ArithmeticException e)
{
System.out.println(“please ensure that second argument is a non-zero”);
e.printStackTrace();
}
catch(NumberFormatException e)
{
System.out.println(“Only digits as arguments please.”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Supply 2 arguments please”);
}
}//main
}//class
Observations to be made
1. Whenever try block has doubtful code that may raise different kinds of
exceptions, we go for multiple catch blocks.
Core Java
39
2. Even though multiple catch blocks are there, only one catch block is
executed.
Creating and throwing user defined exceptions
Our own created exceptions are known as user defined exceptions as we have said
earlier. In case of user defined exceptions, we have to define our own exception
class that extends java.lang.Exception
or its sub class. Whenever our application
rule is failed, we treat it as an abnormal event and throw the user defined exception.
Q) Example program on user-defined exception
class VotingException extends Exception
{
VotingException(String s)
{
super(s);
}
}
class Voting
{
static void diplayCandidateEligibilityForVoting(int age) throws VotingException
{
if(age<19)
throw new VotingException("invalid age to cast the vote");
System.out.println(" candidate is eligible to vote");
}
}
class UserDefinedException{
public static void main(String args[]){
int age=Integer.parseInt(args[0]);
try
{
Voting.diplayCandidateEligibilityForVoting(age);
}
catch(VotingException e) {
System.out.println(e.getMessage());
}
}//main() }//class
Core Java
40
Multithreading
A thread is said to be a sub process. As we know, a process is nothing but a program
under execution. If a process (application) has multiple sub processes (threads),
such application is known as a multithreaded application. How (and why) to develop
multithreaded Java applications is the goal of multithreading.
A single sequential flow of control OR an independent path of execution in a
process is known as a thread.
In Java, a thread is an instance of a class that extends java.lang.Thread class or
that implements java.lang.Runnable interface. Sometimes we create a thread by
directly instantiating the Thread class.
Thread Life cycle
Thread life cycle is described by the following four states.
1. new state
2. active state (running/ready to run state)
3. blocked state (suspended state)
4. dead state
When a thread is created, it is said to be in new state. When the thread is in new
state, it will not have body. If we call start method on the thread object it becomes
active. If it is the only thread, it gets CPU cycles and it becomes running. If multiple
threads are there it becomes ready to run. When a thread is in new state it has the
body. If a thread is taken out of service temporarily by calling sleep(), join() or
wait(), it assumes the blocked state. At that time it will not get CPU cycles. IF the
body of thread is completely executed, the thread dies. We can explicitly also kill the
threads.
To implement multithreaded applications, we define a class that extends
java.lang.Thread class or implements java.lang.Runnable interface. If our class is
already extending some other class, we implement multithreading by implementing
Runnable interface.
To develop a multithreaded application we identify the number of concurrent
tasks our application has to perform and create as many number of threads. Once
we activate them, multiple independent paths are created and multiple tasks are
performed concurrently.
Core Java
41
Q) Write a program that performs the following two tasks concurrently (at the same
time).
1. Printing hello 20 times
2. Printing “hai” 20 times
/*
Source code: - MultiThreadingEXample.java
*/
class MyThreadOne extends Thread
{
public void run()
{
for(int i=1;i<=20;i++)
System.out.println("hello");
}
}
class MyThreadTwo extends Thread
{
public void run()
{
for(int i=1;i<=20;i++)
System.out.println("hai");
}
}
class MultiThreadingExample
{
public static void main(String[] args)
{
MyThreadOne t1=new MyThreadOne();
MyThreadTwo t2=new MyThreadTwo();
t1.start();
t2.start();
}
}
The above program prints “hello” for few times and “hai” few times. Again “hello” few
times and “hai” few times.
Core Java
42
Observations to be made
1. Task performing code we write in the run method. It acts as the body of the
thread.
2. When we called start method on the two threads, the threads are activated
and run method is called. Concurrently two flows are executed.
Q) Modify the above program using Runnable interface.
/*
Source code: - MultiThreadingEXampleTwo.java
*/
class MyThreadOne implements Runnable
{
public void run()
{
for(int i=1;i<=20;i++)
System.out.println("hello");
}
}
class MyThreadTwo implements Runnable
{
public void run()
{
for(int i=1;i<=20;i++)
System.out.println("hai");
}
}
class MultiThreadingExampleTwo
{
public static void main(String[] args)
{
Thread t1=new Thread(new MyThreadOne());
Thread t2=new Thread(new MyThreadTwo());
t1.start();
t2.start();
}
}
Core Java
43
Observations to be made
1. When our class implements Runnable interface, start method is not available
to the thread object as Runnable interface has only one method run().
2. We created threads by instantiating the Thread class and to ensure our own
run method as the body of the thread, we supplied our class object as the
argument for the constructor of the Thread class.
Q) Program to perform multiple tasks by defining only one class that inherits from
the Thread class.
class MyThread extends Thread
{
String name;
public void run()
{
name=getName();
if(name.equals("one"))
for(int i=1;i<=20;i++)
System.out.println("hello");
else
for(int i=1;i<=20;i++)
System.out.println("hai");
}
}
class MultiThreadingExampleThree
{
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.setName("one");
t2.setName("two");
t1.start();
t2.start();
}
}
Core Java
44
Observations to be made
1. When we define only one class that extends Thread class, we need to write
the body of all the threads in only one run method.
2. To differentiate body of each thread, we give different names for threads by
calling setName(). In the run method we retrieve the name of the current
thread and associate task with that thread.
Q) Program in which, task performing code writing in a separate class in different
methods and call them in run method.
class A
{
void x()
{
for(int i=1;i<=20;i++)
System.out.println("hello");
}
void y()
{
for(int i=1;i<=20;i++)
System.out.println("hai");
}
}
class MyThread extends Thread
{
A a=new A();
String name;
public void run()
{
name=getName();
if(name.equals("one"))
a.x();
else
a.y();
}
}
Core Java
45
class MultiThreadingExampleFour
{
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.setName("one");
t2.setName("two");
t1.start();
t2.start();
}
}
Thread Priorities
All threads have a priority that determines which thread is executed when several
threads are waiting for their turn. The possible values for thread priority are defined
as public static final integer values in Thread class.
1. MIN_PRIORITY (its value is 1)
2. MAX_PRIORITY (its values is 10)
3. NORM_PRIORITY (its value is 5)
The value of the default priority that is assigned to the main thread in a program is
5. When we create a thread, its priority will be same as that of the thread that
created it. We can modify the priority of a thread by calling the setPriority() method
on the thread object. This method takes an argument of type int that defines the
new priority for the thread. This method will throw an IllegalArgumentException if we
supply a value beyond the range between 1 and 10. To know the priority of a thread
we can call the method getPriority().
Actual priority of a thread that we set by calling setPriority() depends upon the
mapping between Java thread priorities and the underlying operating system
priorities. The thread-scheduling algorithm that the Os uses also affects how our
application threads execute and what proportion of the process time they are
allocated.
If we want to set the priority for a thread we have to do so before it is activated.
For example,
MyThread t=new MyThread();
t.setPriority(6); t.start();
Core Java
46
Q) Example program in which priority is set for a particular thread.
/*
Source code: - MultiThreadingExampleFive.java
*/
class MyThreadOne extends Thread
{
public void run()
{
for(int i=1;i<=20;i++)
{
System.out.println("hello");
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}//for
}//run
}
class MyThreadTwo extends Thread
{
public void run()
{
for(int i=1;i<=20;i++)
{
System.out.println("hai");
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
Core Java
47
e.printStackTrace();
}
}//for
}//run()
}
class MultiThreadingExampleFive
{
public static void main(String[] args)
{
MyThreadOne t1=new MyThreadOne();
MyThreadTwo t2=new MyThreadTwo();
t2.setPriority(7);
t1.start();
t2.start();
}
}
Observations to be made
1. The thread “t1” has the priority of 5.
2. We have set the priority of “t2” as 7.
3. Even though t1 is activated first, thread scheduler assigns CPU cycles for t2 first
as its priority is more than that of t1.
4. If priority of all the threads are the same, CPU cycles are allotted on first come
first serve basis.
5.
We are suspending t1 and t2 for 500 milliseconds in each iteration of the loop
by calling the static method sleep().
6. As sleep() method throws a checked exception, we must handle it.
Thread synchronization
Whenever multiple threads are trying to access the same resource, allowing only
thread
at
a
time
is
nothing
but
multithreaded applications thread-safe.
synchronization.
Synchronization
makes
We can implement synchronization in two
ways.
1. Method level synchronization
2. Block level synchronization.
In both the cases we make use of the modifier “synchronized”.
Core Java
48
We define whole method as synchronized in case of method level synchronization.
For example,
synchronized void withdraw(float balance)
{
//code
}
Once withdraw method is called on one object in one thread, the object is locked. No
other thread can call the withdraw method on that object unless withdraw method is
completely executed.
We can apply synchronization at block level also.
synchronized(Object)
{
//code
}
When we implement block level synchronization, unless the code in that block is
completely executed, no other thread can access that object’s synchronized code.
Dead Lock
Whenever multiple threads have circular dependency on synchronized objects, a
nasty bug called deadlock occurs. Improper synchronization leads to dead locks.
Dead locks have to be prevented by designing the multithread application properly.
Once they occur, fixing them is very difficult.
Interthread Communication
Threads communicate one another using 3 methods of java.lang.Object class. All
these methods can be called only in the synchronized context.
1. wait()
2. notify()
3. notifyAll()
wait():-Causes the current thread to wait until another thread invokes the notify()
method or the notifyAll() method for this object. The current thread must own this
object's monitor. The thread releases ownership of this monitor and waits until
another thread notifies threads waiting on this object's monitor to wake up either
through a call to the notify method or the notifyAll method. The thread then waits
until it can re-obtain ownership of the monitor and resumes execution.
Core Java
49
notify(): - Wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened. The choice
is arbitrary and occurs at the discretion of the implementation. A thread waits on an
object's monitor by calling one of the wait methods. The awakened thread will not be
able to proceed until the current thread relinquishes the lock on this object. The
awakened thread will compete in the usual manner with any other threads that
might be actively competing to synchronize on this object; for example, the
awakened thread enjoys no reliable privilege or disadvantage in being the next
thread to lock this object. A thread that is the owner of this object’s monitor should
only call this method. A thread becomes the owner of the object's monitor in one of
three ways:
1. By executing a synchronized instance method of that object.
2. By executing the body of a synchronized statement that synchronizes on the
object.
3. For objects of type Class, by executing a synchronized static method of that
class.
Only one thread at a time can own an object's monitor.
notifyAll(): -Wakes up all threads that are waiting on this object's monitor. A thread
waits on an object's monitor by calling one of the wait methods. The awakened
threads will not be able to proceed until the current thread relinquishes the lock on
this object. The awakened threads will compete in the usual manner with any other
threads that might be actively competing to synchronize on this object; for example,
the awakened threads enjoy no reliable privilege or disadvantage in being the next
thread to lock this object. A thread that is the owner of this object’s monitor should
only call this method.
Core Java
50
IOStreams
Java programs perform input and output operations through streams. A stream is an
object that takes information from the Java program or that gives information to the
Java program. A stream is attached to a physical device. All streams behave in the
same manner, even though they are connected to different devices. Therefore, we
can develop device independent programs. We have 2 kinds of streams.
1. Byte streams
2. Character streams
Byte streams are used to handle input and output of binary data and hence they are
also known as binary streams. java.io.InputStream and java.io.OutputStream are
the top level classes that represent binary or byte streams.
Character streams are used to handle input and output of characters. They use
Unicode and hence internationalization is possible. java.io.Reader and java.io.Writer
are the top level classes that represent character streams.
Reading data from the keyboard
java.io.DataInputStream and java.io.BufferedReader classes can be used to accept
input from the keyboard in convenient way.
Q) Program to read data from keyboard.
/*
source code: - Keyboard.java
*/
import java.io.*;
class Keyboard
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
System.out.print("Enter your name:");
String name=dis.readLine();
System.out.println("Hello !"+name);
dis.close();
}
}
Core Java
51
Observations to be made
1. System.in represents the keyboard
2. This program gives warning about deprecation of readLine(). Even then it
works.
3. DataInputStream is a binary stream
4. Instead of handling the IOException, we are passing it.
Q) Program to read data from the keyboard using character oriented streams.
import java.io.*;
class Keyboard
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter book title:");
String name=br.readLine();
System.out.print("Enter author:");
String author=br.readLine();
System.out.print(“Enter price:”);
float price=Float.parseFloat(br.readLine());
System.out.println("Book details....");
System.out.println("Title:"+name);
System.out.println("Author:"+author);
System.out.println(“Price:Rs.”+price);
br.close();
}
}
Observations to be made
1. System.in cannot be directly supplied as argument to the BufferedReader
constructior.
2. InputStreamReader converts the binary stream System.in into characteroriented stream.
3. readLine() method returns String.
4. By calling the Float.parseFloat(), we are translating the string representation
of float value into actual float value.
Core Java
52
Reading from the file
To perform reading operation from the files we have FileInputStream and FileReader.
To perform reading operation, first of all we create the stream object.
FileInputStream fis=new FileInputStream(“filename”);
OR
FileReader fr=new FileReader(“filename”);
When we perform read operation on the stream, we get the file contents. Once read
operation is done, we need to close the stream.
Q) Program to read the contents of a disk file and display the contents.
import java.io.*;
class FileReading
{
public static void main(String[] args) throws IOException
{
FileInputStream fis=new FileInputStream(args[0]);
int c=fis.read();
while(c !=-1)
{
System.out.print((char)c);
c=fis.read();
}
fis.close();
}//main()
}//class
Observations to be made
1. File name is supplied as command line argument to the FileInputStream
constructor.
2. read() method reads the next byte of data from the input stream. The value
byte is returned as an int in the range 0 to 255. If no byte is available because
the end of the stream has been reached, the value -1 is returned. This
method blocks until input data is available, the end of the stream is detected,
or an exception is thrown.
3. To print the character of the corresponding int value we are type casting it to
char so that the character is printed on the screen.
Core Java
53
Q) Program to read the contents of a disk file using character oriented stream.
/*
Source code: - FileReading.java
*/
import java.io.*;
class FileReading
{
public static void main(String[] args) throws IOException
{
FileReader fr=new FileReader(args[0]);
int c=fr.read();
while(c !=-1)
{
System.out.print((char)c);
c=fr.read();
}
fr.close();
}//main()
}//class
Observations to be made
1. FileReader is used instead of FileInputStream.
2. Reading logic remained the same when compared to FileInputStream.
Reading a file efficiently
To improve the performance of reading we make use of BufferedInputStream in case
of byte streams. Where as in case of Character oriented streams, BufferedReader is
used.
Q) Example program that reads the contents of a disk file efficiently
/*
Source code: - ReadEfficiently.java
*/
import java.io.*;
class ReadEfficiently
{
public static void main(String[] args) throws IOException
Core Java
54
{
FileReader fr=new FileReader(args[0]);
BufferedReader br=new BufferedReader(fr);
String line=br.readLine();
while(line !=null)
{
System.out.println(line);
line=br.readLine();
}
br.close();
}//main()
}//class
Observations to be made
1. readLine( ) method returns one line of text. If it encounters the end of file, it
returns “null”.
2. Once the outer stream is closed, inner stream also will be closed.
Writing into the file
In order to store some information into the file from the Java program, we make use
of either FileOutputStream or FileWriter.
FileOutputStream fos=new FileOutputStream(“filename”);
OR
FileWriter fw=new FileWriter(“filename”);
In both the cases, if file already exists, its contents will be overwritten. If the
specified file not there, a new file with that name is created.
Q) Write a program to store some information into a disk file using byte oriented
stream.
/*
source code: - StoringIntoFile.java
*/
import java.io.*;
class StoringIntoFile
{
public static void main(String[] args) throws IOException
{
FileOutputStream fos=new FileOutputStream("one.txt");
Core Java
55
String s="This will be stored into file";
byte b[]=s.getBytes();
fos.write(b);
fos.close();
}//main()
}//class
Observations to be made
1. write() method of the FileOutputStream does not take String as the argument. It
takes byte array as the argument. Therefore, by calling getBytes() method of the
String class, the string is converted into byte array and is supplied as argument to it.
2. After writing operation Is over, the stream is closed.
Q) Write a program to store some information into a disk file using character
oriented stream.
/*
source code: - StoringIntoFile.java
*/
import java.io.*;
class StoringIntoFile
{
public static void main(String[] args) throws IOException
{
FileWriter fw=new FileWriter("one.txt");
String s="This will be stored into file";
fw.write(s);
fw.close();
}//main()
}//class
Observations to be made
1. Being a character-oriented stream, FileWriter class takes String as the
argument directly.
2. If we want to append the content of the file rather than overwriting its
contents, we have to supply appendability indicating true value as the second
argument to the constructor of the FileWriter OR FileOutputStream
Core Java
56
Object Serialization
Object serialization is the process of storing an object state into a stream. Through
serialization, objects become persistent. To implement serialization, the rule is that
the class should implement java.io.Serializable interface.
Q) Program to implement Object deserialization.
/*
source code:- ObjectDeSerialization.java
*/
import java.io.*;
class Student implements Serializable
{
int rollno;
Student(int rno)
{
rollno=rno;
}
void display()
{
System.out.println("Rollno:"+rollno);
}
}
class ObjectSerialization
{
public static void main(String[] args) throws Exception
{
FileOutputStream fos=new FileOutputStream("student.dat");
ObjectOutputStream oos=new ObjectOutputStream(fos);
Student s=new Student(1002);
oos.writeObject(s);
oos.close();
}
}
Core Java
57
/*
Source code: - ObjectDeserialization.java
*/
import java.io.*;
class Student implements Serializable
{
int rollno;
Student(int rno)
{
rollno=rno;
}
void display()
{
System.out.println("Rollno:"+rollno);
}
}
class ObjectDeSerialization
{
public static void main(String[] args) throws Exception
{
FileInputStream fis=new FileInputStream("student.dat");
ObjectInputStream ois=new ObjectInputStream(fis);
Student s=(Student)ois.readObject();
s.display();
ois.close();
}
}
Core Java
58