OOP Using Java
OOP Using Java
OOP Using Java
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
JAVA Page
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
Benefits of Inheritance
One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent code
exists in two related classes, the hierarchy can usually be refactored to move the common
code up to a mutual superclass. This also tends to result in a better organization of code and
smaller, simpler compilation units.
Inheritance can also make application code more flexible to change because classes that
inherit from a common superclass can be used interchangeably. If the return type of a
method is superclass
Reusability - facility to use public methods of base class without rewriting the same.
Extensibility - extending the base class logic as per business logic of the derived class.
JAVA Page
Data hiding - base class can decide to keep some data private so that it cannot be
altered by the derived class
Procedural and object oriented programming paradigms
JAVA Page
Java Programming- History of Java
The history of java starts from Green Team. Java team members (also known
as Green Team), initiated a revolutionary task to develop a language for digital
devices such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was
suited for internet programming. Later, Java technology as incorporated by
Netscape.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green
Team.
2) Originally designed for small, embedded systems in electronic appliances like set-
top boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green
project.
There are many java versions that has been released. Current stable release of Java
is Java SE 8.
JAVA Page
Features of Java
There is given many features of java. They are also known as java buzzwords. The Java Features
given below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12.Distributed
Java Comments
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement. It can also be used to hide program code for specific time.
Syntax:
JAVA Page
Example:
Output:
10
Syntax:
/*
This
is
multi line
comment
*/
Example:
Output:
10
JAVA Page
Java Documentation Comment
The documentation comment is used to create documentation API. To create documentation API, you need
to use javadoc tool.
Syntax:
/**
This
is
documentation
comment
*/
Example:
/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
public class Calculator {
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b){return a+b;}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b){return a-b;}
}
j C l l t j
j d C l l t j
Now, there will be HTML files created for your Calculator class in the current directory. Open the HTML
files and see the explanation of Calculator class provided through documentation comment.
JAVA Page
Data Types
Data types represent the different values to be stored in the variable. In java, there are two types of data types:
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Output:20
JAVA Page
Variables and Data Types in Java
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.
There are two types of data types in java: primitive and non-primitive.
Types of Variable
There are three types of variables in java:
o local variable
o instance variable
o static variable
1) Local Variable
2) Instance Variable
A variable which is declared inside the class but outside the method, is called instance variable . It
is not declared as static.
3) Static variable
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
Constants in Java
A constant is a variable which cannot have its value changed after declaration. It uses the
'final' keyword.
Syntax
final dataType variableName = value;
JAVA Page
Scope and Life Time of Variables
The scope of a variable defines the section of the code in which the variable is visible. As a
general rule, variables that are defined within a block are not accessible outside that block.
The lifetime of a variable refers to how long the variable exists before it is destroyed.
Destroying variables refers to deallocating the memory that was allotted to the variables when
declaring it. We have written a few classes till now. You might have observed that not all
variables are the same. The ones declared in the body of a method were different from those
that were declared in the class itself. There are three types of variables: instance variables,
formal parameters or local variables and local variables.
Instance variables
Instance variables are those that are defined within a class itself and not in any method or
constructor of the class. They are known as instance variables because every instance of the
class (object) contains a copy of these variables. The scope of instance variables is determined
by the access specifier that is applied to these variables. We have already seen about it earlier.
The lifetime of these variables is the same as the lifetime of the object to which it belongs.
Object once created do not exist for ever. They are destroyed by the garbage collector of Java
when there are no more reference to that object. We shall see about Java's automatic garbage
collector later on.
Argument variables
These are the variables that are defined in the header oaf constructor or a method. The scope
of these variables is the method or constructor in which they are defined. The lifetime is
limited to the time for which the method keeps executing. Once the method finishes
execution, these variables are destroyed.
Local variables
A local variable is the one that is declared within a method or a constructor (not in the
header). The scope and lifetime are limited to the method itself.
One important distinction between these three types of variables is that access specifiers can
be applied to instance variables only and not to argument or local variables.
In addition to the local variables defined in a method, we also have variables that are defined
in bocks life an if block and an else block. The scope and is the same as that of the block
itself.
JAVA Page
Operators in java
Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in java which are given below:
o Unary Operator,
o Arithmetic Operator,
o shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Operators Hierarchy
JAVA Page
Expressions
Expressions are essential building blocks of any Java program, usually created to produce a new
value, although sometimes an expression simply assigns a value to a variable. Expressions are
built using values, variables, operators and method calls.
Types of Expressions
While an expression frequently produces a result, it doesn't always. There are three types of
expressions in Java:
For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.
JAVA Page
Java Enum
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST)
etc. The java enum constants are static and final implicitly. It is available from JDK 1.5.
Java Enums can be thought of as classes that have fixed set of constants.
Output:
WINTER
SPRING
SUMMER
FALL
The control flow statements in Java allow you to run or skip blocks of code when special
conditions are met.
if (condition) {
// execute this code
}
JAVA Page
The condition is Boolean. Boolean means it may be true or false. For example you may put a
mathematical equation as condition. Look at this full example:
Next, find the "My Computer" icon (on your Start menu or desktop), right-click it, and select
properties. Click on the Advanced tab, and then click on the Environment variables button.
Look at the variables listed for all users, and click on the Path variable. Do not delete the
contents of this variable! Instead, edit the contents by moving the cursor to the right end,
entering a semicolon (;), and pressing Ctrl-V to paste the path you copied earlier. Then go
ahead and save your changes. (If you have any Cmd windows open, you will need to close
them.)
10. If you're using Windows, go to the Start menu and type "cmd" to run a program that
brings up a command prompt window. If you're using a Mac or Linux machine, run the
Terminal program to bring up a command prompt.
11. In Windows, type dir at the command prompt to list the contents of the current directory.
On a Mac or Linux machine, type ls to do this.
JAVA Page
12. Now we want to change to the directory/folder that contains your compiled code. Look at
the listing of sub-directories within this directory, and identify which one contains your code.
Type cd followed by the name of that directory, to change to that directory. For example, to
change to a directory called Desktop, you would type:
cd Desktop
cd ..
Every time you change to a new directory, list the contents of that directory to see where to go
next. Continue listing and changing directories until you reach the directory that contains
your .class files.
13. If you compiled your program using Java 1.6, but plan to run it on a Mac, you'll need to
recompile your code from the command line, by typing:
14. Now we'll create a single JAR file containing all of the files needed to run your program.
Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using
indexed variables.
Example:
JAVA Page
The following code snippets are examples of this syntax:
double[] // f d
myList;
or // k b t t f d
Creating Arrays:
You can create an array by using the new operator with the following syntax:
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:
Example:
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:
JAVA Page
Processing Arrays:
When processing array elements, we often use either for loop or for each loop because all of the
elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
JAVA Page
This would produce the following result:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
The Java Console class is be used to get input from console. It provides methods to read texts and
passwords.
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console class is
introduced since 1.5.
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);
import java.io.Console;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
JAVA Page
System.out.println("Welcome "+n); } }
JAVA Page
Output
Constructors
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}}
Output: Bike is created
JAVA Page
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.
class Student4{
int id;
String name;
Output:
111 Karan
222 Aryan
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
JAVA Page
s2.display();
}}
Output:
111 Karan 0
222 Aryan 25
Java Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using java
constructor.
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
Output:
111 Karan
111 Karan
JAVA Page
Java - Methods
A Java method is a collection of statements that are grouped together to perform an operation.
When you call the System.out.println() method, for example, the system actually executes
several statements in order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke a
method with or without parameters, and apply method abstraction in the program design.
Creating Method
Considering the following example to explain the syntax of a method −
Syntax
a, b − formal parameters
Method definition consists of a method header and a method body. The same is shown in the
following syntax −
Syntax
modifier − It defines the access type of the method and it is optional to use.
nameOfMethod − This is the method name. The method signature consists of the method
name and the parameter list.
JAVA Page
Parameter List − The list of parameters, it is the type, order, and number of parameters
of a method. These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the statements.
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it
is known as call by value. The changes being done in the called method, is not affected in the
calling method.
Output:before change
50
In Java, parameters are always passed by value. For example, following program prints
i = 10, j = 20.
// Test.java
class Test {
// swap() doesn't swap i and j
public static void swap(Integer i, Integer j) {
Integer temp = new Integer(i);
i = j;
j = temp;
}
public static void main(String[] args) {
Integer i = new Integer(10);
Integer j = new Integer(20);
swap(i, j);
System.out.println("i = " + i + ", j = " + j);
JAVA Page
JAVA Page
}
}
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the class
than instance of the class.
o The static variable can be used to refer the common property of all objects (that is not unique for
each object) e.g. company name of employees,college name of students etc.
o The static variable gets memory only once in class area at the time of class loading.
JAVA Page
String name;
static String college ="ITS";
Student8(int r,String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1.display();
s2.display();
}}
Output:111 Karan ITS
222 Aryan ITS
If you apply static keyword with any method, it is known as static method.
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
JAVA Page
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}}
Output:111 Karan
BBDIT 222 Aryan
BBDIT
Access Control
There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor
or class.
JAVA Page
JAVA Page
1. private
2. default
3. protected
4. public
//save by B.java
package mypack;
import pack.*;
JAVA Page
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error } }
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't
be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}}
Output:Hello
JAVA Page
Example of public access modifier
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}}
Output:Hello
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
JAVA Page
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
111 ankit 5000
112 sumit 6000
Constructor is used to initialize the state of an Method is used to expose behaviour of an object.
object.
Constructor must not have return type. Method must have return type.
The java compiler provides a default Method is not provided by compiler in any case.
constructor if you don't have any constructor.
Constructor name must be same as the class Method name may or may not be same as class name.
name.
JAVA PROGRAMMING Page 30
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
JAVA Page
Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called recursive method.
Output:
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
gc() method
JAVA Page
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
ssame as:
1. String s="javatpoint";
2. Java String class provides a lot of methods to perform operations on string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
3. The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.
CharSequence Interface
JAVA Page
The CharSequence interface is used to represent sequence of characters. It is implemented by
String, StringBuffer and StringBuilder classes. It means, we can create string in java by using
these 3 classes.
The java String is immutable i.e. it cannot be changed. Whenever we change any
string, a new instance is created. For mutable string, you can use StringBuffer and StringBuilder
classes.
There are two ways to create String object:
1. By string literal
2. By new keyword
String Literal
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in
the pool, a new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object
in heap (non pool).
JAVA Page
strings
exam Immutable String in Java
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
Let's try to understand the immutability concept by the example given below:
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
} }
Output:Sachin
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
} } Output:Sachin Tendulkar
JAVA Page
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object. Inheritance represents the IS-A relationship, also known as parent-
child relationship.
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}}
Bonus of programmer
Programmeris:10000
salary is:40000 0
JAVA Page
Types of inheritance in java
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
JAVA Page
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.e at();
}}
Output:
weeping...
barkin
g
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating
JAVA Page
Member access and Inheritance
super keyword in java
A subclass includes all of the members of its super class but it cannot access those
members The super
of the superkeyword in have
class that java is a reference
been declaredvariable which
as private. is used
Attempt to to referaimmediate
access private parent class
variable would
object.cause compilation error as it causes access violation. The variables declared
as private, is only accessible by other members of its own class. Subclass have no access to
it
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
JAVA Page
d.printColor();
}}
Output:
black
h
Final Keyword in Java
The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called blank
final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block only.
The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:
1. Object obj=getObject();//we don't know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
JAVA Page
Usage of Java Method Overriding
o Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
o Method overriding is used for runtime polymorphism
1. class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}}
Output:
SBI Rate of Interest: 8
JAVA Page
JAVA Page
ICICI Rate of
Interest: 7 AXIS
Abstract class in Java
A class that is declared with abstract keyword is known as abstract class in java. It can have
abstract and non-abstract methods (method with body). It needs to be extended and its method
implemented. It cannot be instantiated.
abstract method
1. abstract void printStatus();//no body and abstract
Unit-2
JAVA Page
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction. There can be only abstract methods
in the java interface not method body. It is used to achieve abstraction and multiple inheritance in
Java.
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
JAVA Page
Internal addition by compiler
interface Printable{
JAVA Page
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}}
utput:Hello
Abstract class Interface
Welcome
1) Abstract class can have abstract Interface can have only abstract methods. Since
and non-abstract methods. Java 8, it can have default and static
methods also.
2) Abstract class doesn't support Interface supports multiple inheritance.
multiple inheritance.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to The interface keyword is used to declare
declare abstract class. interface.
6) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
JAVA Page
Advantage of java inner classes
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
Inner class is a part of nested class. Non-static nested classes are known as inner classes.
There are two types of nested classes non-static and static nested classes.The non-static nested
classes are also known as inner classes.
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}}
JAVA Page
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
JAVA Page
Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception: The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked
at compile-time.
2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
JAVA Page
Hierarchy of Java Exception classes
JAVA Page
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw exception
3. }finally{}
Java catch block is used to handle the Exception. It must be used after the try block only.
As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
JAVA Page
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}}
1. Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
Output:task1
completed rest
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
JAVA Page
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
1. }
Java finally block
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always
executed rest of the code
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
1. throw exception;
JAVA Page
Java throw keyword example
In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
Output:
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
JAVA Page
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow..."); } }
Output:
exception
handled
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
JAVA Page
Multithreading
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
JAVA Page
How to create thread
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
JAVA Page
Commonly used methods of Thread class:
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
JAVA Page
Java Thread Example by extending Thread class
JAVA Page
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
JAVA Page
public void run(){c.deposit(10000);}
}
start();
}}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit
completed
ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such way, we can
suspend, resume or interrupt group of threads by a single method call.
ThreadGroup(String name)
ThreadGroup(ThreadGroup parent, String name)
Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is the
class that implements Runnable interface and "one", "two" and "three" are the thread names.
1. Thread.currentThread().getThreadGroup().interrupt();
JAVA Page
UNIT-3
Collection Framework in Java
Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:
JAVA Page
Hierarchy of Collection Framework
JAVA Page
ArrayList class declaration
Constructor Description
Ravi
Vi
ja
y
JAVA Page
vector
ArrayList and Vector both implements List interface and maintains insertion order.
But there are many differences between ArrayList and Vector classes that are given below.
ArrayList Vector
2)ArrayList increments 50% of Vector increments 100% means doubles the array
current array size if number of size if total number of element exceeds than its
element exceeds from its capacity. capacity.
5) ArrayLis tuses Iterator interface Vector uses Enumeration interface to traverse the
to traverse the elements. elements. But it can use Iterator also.
Let's see a simple example of java Vector class that uses Enumeration interface.
1. import java.util.*;
2. class TestVector1{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();//creating vector
5. v.add("umesh");//method of Collection
6. v.addElement("irfan");//method of Vector
7. v.addElement("kumar");
8. //traversing elements using Enumeration
JAVA Page
9. Enumeration e=v.elements();
10. while(e.hasMoreElements()){
11. System.out.println(e.nextElement());
12. } } }
Output:
umesh
irfan
ku
Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary
class and implements the Map interface.
o A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is
identified by calling the hashcode() method. A Hashtable contains values based on the
key.
o It contains only unique elements.
o It may have not have any null key or value.
o It is synchronized.
JAVA Page
Constructors of Java Hashtable class
Constructor Description
Hashtable(int size) It is used to accept an integer parameter and creates a hash table
that has an initial size specified by integer value size.
Hashtable(int size, float It is used to create a hash table that has an initial size specified by
fillRatio) size and a fill ratio specified by fillRatio.
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
Stack
Stack only defines the default constructor, which creates an empty stack. Stack includes all the
methods defined by Vector, and adds several of its own.
JAVA Page
Stack( ) Example
The following program illustrates several of the methods supported by this collection −
import java.util.*;
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println(a);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
JAVA Page
}}}
Output
stack: [ ]
push(42) stack:
[42] push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack
Enumeration
The Enumeration Interface
The Enumeration interface defines the methods by which you can enumerate (obtain one at a time)
the elements in a collection of objects.
The methods declared by Enumeration are summarized in the following table −
1
boolean hasMoreElements( )
When implemented, it must return true while there are still more elements to extract, and
false when all the elements have been enumerated.
2
Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.
Example
import java.util.Vector;
import
java.util.Enumeration;
Vector();
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while
Output
Sunday
Monday
Tuesday
Wednes
day
Thursda
y Friday
Iterator
JAVA Page
It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can
perform both read and remove operations. It is improved version of Enumeration with additional
functionality of remove-ability of a element.
Iterator must be used whenever we want to enumerate elements in all Collection framework
implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of Map
interface. Iterator is the only cursor available for entire collection framework.
Iterator object can be created by calling iterator() method present in Collection interface.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc.
JAVA Page
Constructor Description
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
Let's see the simple example of StringTokenizer class that tokenizes a string "my name is khan"
on the basis of whitespace.
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
JAVA Page
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}}}
Output:my
name
is
k
Example of nextToken(String delim) method of StringTokenizer class
import java.util.*;
public class Test {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("my,name,is,khan");
// printing next token
System.out.println("Next token is : " + st.nextToken(","));
} }
Output:Next token is : my
java.util.Random
For using this class to generate random numbers, we have to first create an instance of this
class and then invoke methods such as nextInt(), nextDouble(), nextLong() etc using that
instance.
We can generate random numbers of types integers, float, double, long, booleans using this
class.
We can pass arguments to the methods for placing an upper bound on the range of the
numbers to be generated. For example, nextInt(6) will generate numbers in the range 0 to 5
both inclusive.
// A Java program to demonstrate random number generation
// using java.util.Random;
import java.util.Random;
JAVA Page
// Print random integers
System.out.println("Random Integers: "+rand_int1);
System.out.println("Random Integers: "+rand_int2);
There are various ways to read input from the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive types using regular
expression.
Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
Method Description
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and returns the value
as a string.
JAVA Page
public short nextShort() it scans the next token as a short value.
Let's see the simple example of the Java Scanner class which reads the int, string and double
value as an input:
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
} } Output:
Enter your
rollno 111
Enter your
name Ratan
Enter
450
000
JAVA Page
Java Calendar Class
Java Calendar class is an abstract class that provides methods for converting date between a
specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It
inherits Object class and implements the Comparable interface.
import java.util.Calendar;
public class CalendarExample1 {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("The current date is : " + calendar.getTime());
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}}
Output:
JAVA Page
Java - Files and I/O
The java.io package contains nearly every class you might ever need to perform input and output
(I/O) in Java. All these streams represent an input source and an output destination. The stream
in the java.io package supports many data such as primitives, object, localized characters, etc.
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly used
examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of
these two classes to copy an input file into an output file −
Example
import java.io.*;
FileOutputStream out =
null; try {
in = new FileInputStream("input.txt");
out = new
FileOutputStream("output.txt"); int c;
This
}finally { is test for copy file.
As a next step, compile the above program and execute it, which will result in creating output.txt
if (in != null) {
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java
in.close();
file and do the following −
}
$javac CopyFile.java
Character Streams
$java ifCopyFile
(out !=
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
null)
Java{ Character streams are used to perform input and output for 16-bit unicode. Though there
are many classes related to character streams but the most frequently used classes
out.close();
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input
file (having unicode characters) into an output file −
Example
import java.io.*;
JAVA Page
FileReader in =
Now let's have a file input.txt with the following content −
null; FileWriter
This try
out = null; is test
{ for copy file.
As a next step, compile the above program and execute it, which will result in creating output.txt
in = new
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java
FileReader("input.txt"); out =−
file and do the following
new FileWriter("output.txt");
$javac CopyFile.java
Standard Streams
$java int c;
CopyFile
All the programming languages provide support for standard I/O where the user's program can
while ((cinput
take = in.read()) != -
from a keyboard and then produce an output on the computer screen. Java provides the
1)following three standard streams −
{ out.write(c);}
}finally { Standard Input − This is used to feed the data to user's program and usually a keyboard
is used as standard input stream and represented asSystem.in.
if (in != null) {
in.close();}
if (out !=
null) {
JAVA Page
Standard Output − This is used to output the data produced by the user's program and
usually a computer screen is used for standard output stream and represented
as System.out.
Standard Error − This is used to output the error data produced by the user's program
and usually a computer screen is used for standard error stream and represented
as System.err.
Following is a simple program, which creates InputStreamReader to read standard input stream
until the user types a "
Example
import java.io.*;
try {
quit."); char c;
do {
c = (char)
cin.read();
System.out.print(
c);
} while(c != 'q');
}finally {
if (cin !=
This program continues to read and output the same character until we press 'q' −
$javac ReadConsole.java
$java ReadConsole
JAVA Page
JAVA Page
Enter characters,
Reading'q'and
to Writing Files
quit. 1
As described earlier, a stream can be defined as a sequence of data. The InputStream is used to
1
read data from a source and the OutputStream is used for writing data to a destination.
e
e Here is a hierarchy of classes to deal with Input and Output streams.
q
q
FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the
file −
JAVA Page
Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows −
ByteArrayInputStream
DataInputStream
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the
file −
Example
import java.io.*;
args[]) { try {
JAVA Page
byte bWrite [] = {11,21,3,40,5};
os.close();
is.close();
} catch (IOException e) {
System.out.print("Exception");
} }}
Java.io.RandomAccessFile Class
The Java.io.RandomAccessFile class file behaves like a large array of bytes stored in the file
system.Instances of this class support both reading and writing to a random access file.
Class declaration
Following is the declaration for Java.io.RandomAccessFile class −
Class constructors
S.N. Constructor & Description
1
RandomAccessFile(File file, String mode)
This creates a random access file stream to read from, and optionally to write to, the file
specified by the File argument.
This creates a random access file stream to read from, and optionally to write to, a file with
the specified name.
Methods inherited
This class inherits methods from the following classes −
Java.io.Object
defines an abstract file name for the geeks file in directory /usr/local/bin. This is an absolute
abstract file name.
Program to check if a file or directory physically exist or not.
// In this program, we accepts a file or directory name from
// command line arguments. Then the program will check if
// that file or directory physically exist or not and
// it displays the property of that file or directory.
*import java.io.File;
Output:
File name
:file.txt Path:
file.txt
Absolute
path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt
Parent:null
Exists :true
Is
writeable:true
Serialization
Serialization: The process of saving (or) writing state of an object to a file is called serialization but
strictly speaking it is the process of converting an object from java supported form to either network
supported form (or) file supported form.
By using FileOutputStream and ObjectOutputStream classes we can achieve serialization process.
Diagram:
JAVA Page
De-Serialization: The process of reading state of an object from a file is called DeSerialization but
strictly speaking it is the process of converting an object from file supported form (or) network
supported form to java supported form.
• By using FileInputStream and ObjectInputStream classes we can achieve DeSerialization.
Diagram:
Example 1: import
java.io.*;
class Dog implements Serializable
{
int i=10; int j=20;
}
class SerializableDemo
{
public static void main(String args[])throws Exception
{
Dog d1=new Dog();
System.out.println("Serialization started");
FileOutputStream fos=new FileOutputStream("abc.ser");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d1);
System.out.println("Serialization ended");
JAVA Page
System.out.println("Deserialization started");
FileInputStream fis=new FileInputStream("abc.ser");
ObjectInputStream ois=new ObjectInputStream(fis);
Dog d2=(Dog)ois.readObject();
System.out.println("Deserialization ended");
System.out.println(d2.i+"................"+d2.j);
}
}
Output: Serialization started
Serialization ended
Deserialization started
Deserialization ended
10 20
JAVA Page
JAVA Page