Object Oriented Programming in Java: Qasim Ali

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 204
At a glance
Powered by AI
Some of the key concepts of OOP discussed are objects, classes, inheritance, polymorphism, abstraction and encapsulation.

The main concepts of OOP are objects, classes, inheritance, polymorphism, abstraction and encapsulation.

Some advantages of OOP over procedural programming discussed are code reusability, easier maintenance of large projects, data hiding and better ability to model real world problems.

Object Oriented Programming In Java

OOPs (Object Oriented Programming System)

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

Collection of objects is called class. It is a logical entity.

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.

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.

In java, we use method overloading and method overriding to achieve polymorphism.

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.

In java, we use abstract class and interface to achieve abstraction.

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.

Qasim Ali Page 1


Object Oriented Programming In Java

Why Need OOP.

Advantage of OOPs over Procedure-oriented programming language

1) OOPs makes development and maintenance easier where as in Procedure-oriented programming language it is

not easy to manage if code grows as project size grows.

2) OOPs provides data hiding whereas in Procedure-oriented programming language a global data can be accessed

from anywhere.

3) OOPs provides ability to simulate real-world event much more effectively. We can provide the solution of real

word problem if we are using the Object-Oriented Programming language.


Different between Classes and Structure
Class
1. Class is a reference type and its object is created on Heap memory.
2. Class provides the flexibility of combining data and methods (functions ) and it provides the re-usability
called inheritance.
3. Classes allow to perform cleanup
4. Class can inherit the another class.
5. Class can have constructor and destructor of all types.
6. The member variable can be initialized directly.
7. Class object cannot be created without using the new keyword, it means we have to use it. Eg: Demo
obj=new Demo();
8. Class can be abstract.
9. Sizeof empty class is 1 Byte where as Sizeof empty structure is 0 Bytes.
Structure
1. Structure is a value type that is why its object is created on Stack memory.
2. Struct should typically be used for grouping data.
3. Structure does not support the inheritance and cannot inherit another class.
4. Structure can only have the parametrized constructor. it means a structure can not have the non-
parametrized constructor,default constructor and destructor also.
5. The member variable cannot be initialized directly.
6. Structure object can be created without using the new keyword.(optional). Eg: Demo obj;
7. Structure can’t be abstract.

What is Java

Java is a programming language and a platform.

Java is a high level, robust, secured and object-oriented programming language.

Platform: Any hardware or software environment in which a program runs, is known as a platform. Since Java has its own
runtime environment (JRE) and API, it is called platform.

Where it is used

According to Sun, 3 billion devices run java. There are many devices where Java is currently used. Some of them are as
follows:

1. Desktop Applications such as acrobat reader, media player, antivirus etc.

Qasim Ali Page 2


Object Oriented Programming In Java
2. Web Applications such as irctc.co.in, javatpoint.com etc.

3. Enterprise Applications such as banking applications.

4. Mobile

5. Embedded System

6. Smart Card

7. Robotics

8. Games etc.

Types of Java Applications

There are mainly 4 types of applications that can be created using java programming:

Standalone Application

It is also known as desktop application or window-based application. An application that we need to install on every
machine such as media player, antivirus etc. AWT and Swing are used in java for creating standalone applications.

Web Application

An application that runs on the server side and creates dynamic page, is called web application. Currently, servlet, jsp,
struts, jsf etc. technologies are used for creating web applications in java.

Enterprise Application

An application that is distributed in nature, such as banking applications etc. It has the advantage of high level security,
load balancing and clustering. In java, EJB is used for creating enterprise applications.

Mobile Application

An application that is created for mobile devices. Currently Android and Java ME are used for creating mobile
applications.

Java Platforms / Editions

There are 4 platforms or editions of Java:

Java SE (Java Standard Edition)

It is a java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net, java.util,
java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O
Stream, Networking, AWT, Swing, Reflection, Collection etc.

Java EE (Java Enterprise Edition)

It is an enterprise platform which is mainly used to develop web and enterprise applications. It is built on the top of Java
SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA etc.

Java ME (Java Micro Edition)

It is a micro platform which is mainly used to develop mobile applications.

Qasim Ali Page 3


Object Oriented Programming In Java
JavaFx

It is used to develop rich internet applications. It uses light-weight user interface API.

Java Version History

There are many java versions that has been released. Current stable release of Java is Java SE 8.

1. JDK Alpha and Beta (1995)

2. JDK 1.0 (23rd Jan, 1996)

3. JDK 1.1 (19th Feb, 1997)

4. J2SE 1.2 (8th Dec, 1998)

5. J2SE 1.3 (8th May, 2000)

6. J2SE 1.4 (6th Feb, 2002)

7. J2SE 5.0 (30th Sep, 2004)

8. Java SE 6 (11th Dec, 2006)

9. Java SE 7 (28th July, 2011)

10. Java SE 8 (18th March, 2014)

Features of Java

1. Simple,Object-Oriented

2. Portable

3. Platform independent

4. Secured

5. Robust

6. Architecture neutral

7. Dynamic

8. Interpreted

9. High Performance

10. Multithreaded

11. Distributed

Platform Independent

A platform is the hardware or software environment in which a program runs.

There are two types of platforms software-based and hardware-based. Java provides software-based platform.

Qasim Ali Page 4


Object Oriented Programming In Java
The Java platform differs from most other platforms in the sense that it is a software-based platform that runs on the top of
other hardware-based platforms. It has two components:

1. Runtime Environment

2. API(Application Programming Interface)

Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java code is compiled by the
compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run on multiple
platforms i.e. Write Once and Run Anywhere(WORA).

Secured

What happens at compile time

What happens at runtime

Qasim Ali Page 5


Object Oriented Programming In Java

Note: When compiler of java which is “javac” create byte-code of source file of java then JVM takes the byte-code
and execute it by using its own java runtime environment.

JVM (Java Virtual Machine)

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java
bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

What it does

The JVM performs following operation:

o Loads code

o Verifies code

o Executes code

o Provides runtime environment

JVM provides definitions for the:

o Memory area

o Class file format

o Register set

Qasim Ali Page 6


Object Oriented Programming In Java
o Garbage-collected heap

o Fatal error reporting etc.

Classloader

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

Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for
methods.

Heap

It is the runtime data area in which objects are allocated.

Stack

Java Stack stores frames.It holds local variables and partial results, and plays a part in method invocation and return.

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

Program Counter Register

PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed.

Native Method Stack

It contains all the native methods used in the application.

Execution Engine

It contains:

1) A virtual processor

2) Interpreter: Read bytecode stream then execute the instructions.

3) Just-In-Time(JIT) compiler: It is used to improve the performance.JIT compiles parts of the byte code that have

similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term ?

compiler? refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a

specific CPU.

JRE

JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the implementation of
JVM. It physically exists. It contains set of libraries + other files that JVM uses at runtime.

Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.

Qasim Ali Page 7


Object Oriented Programming In Java
JDK

JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.

Structure of Java Program

public class Simple{  

   public static void main(String args[]){  

     System.out.println("Hello Java");  

     }  

public access specifier.

Qasim Ali Page 8


Object Oriented Programming In Java
class keyword is used to declare a class in java.

public keyword is an access modifier which represents visibility, it means it is visible to all.

static is a keyword, if we declare any method as static, it is known as static method. The core advantage of static method is

that there is no need to create object to invoke the static method. The main method is executed by the JVM, so it doesn't

require to create object to invoke the main method. So it saves memory.

void is the return type of the method, it means it doesn't return any value.

main represents startup of the program.

String[] args is used for command line argument. We will learn it later.

System.out.println() is used print statement. We will learn about the internal working of System.out.println statement

later.

Note: Main method can be overloaded in same class, if you miss the static keyword of the main method then compiler

shows you a message “class should have main method” as everything is done in main method and you can’t miss main

method.

Note: Static functions (Like main function) are also part of Class that is why all private and other members of class can

also be accessed inside the static functions.

Note: All non static members of a class can be accessed in static functions only with the help of object.

Note: All static members of class can be accessed inside the non static functions of class without use of object.

Difference between Java and C programming language

Java’s motto (so to speak) is “write once run anywhere”.


 When you compile a Java program, an intermediate bytecode is generated, which itself is interpreted by the Java Virtual
Machine. This way you write a program once, and the virtual machine translates the bytecode into instructions a specific
processor can understand.
 Execution of a Java program is by consequence a bit slow, because the intermediate bytecode has to be interpreted.
 Java uses a “Garbage Collector” which manages memory automatically so the programmer doesn’t have to handle that.
 Variables in Java can be declared anywhere in a program. (Although it is recommended to declare/define them at the
beginning of blocks).
 Reuse of code achieved by inheritance.
 By default members are private.
 During the execution of bytecode by JVM, it does not substitute the entire classes of package which are imported in the
program. It just enters the package and executes the class and returns result in to the program. Due to this less memory is
used by java program.

C Programming Language
 C uses concept of structures (not object oriented).
 In C we use the concept of pointers whereas there are no pointers used in JAVA
 In C the programmer needs to manage memory manually. “malloc()” and “free()” are the fundamental memory allocation
library calls.
 In C the declaration of variables should be on the beginning of the block.
 C supports go to statement, struct and union unlike Java
 C is compiled to the machines “native language” so it’s execution is much faster than Java’s.
 No reuse in code and by default members are public.

Qasim Ali Page 9


Object Oriented Programming In Java
 C programs will have a larger memory footprint than an equivalent program written in pure machine code, but the total
memory use of a C program is much smaller than the a Java program because C does not require the loading of an
execution interpreter like the JVM.
 The main differences between Java and C are speed, portability, and object-orientation.

Primitive data types

byte

 Byte data type is an 8-bit signed two's complement integer

 Minimum value is -128 (-2^7)

 Maximum value is 127 (inclusive)(2^7 -1)

 Default value is 0

 Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times

smaller than an integer.

 Example: byte a = 100, byte b = -50

short

 Short data type is a 16-bit signed two's complement integer

 Minimum value is -32,768 (-2^15)

 Maximum value is 32,767 (inclusive) (2^15 -1)

 Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an integer

 Default value is 0.

 Example: short s = 10000, short r = -20000

int

 Int data type is a 32-bit signed two's complement integer.

 Minimum value is - 2,147,483,648 (-2^31)

 Maximum value is 2,147,483,647(inclusive) (2^31 -1)

 Integer is generally used as the default data type for integral values unless there is a concern about memory.

 The default value is 0

 Example: int a = 100000, int b = -200000

long

 Long data type is a 64-bit signed two's complement integer

 Minimum value is -9,223,372,036,854,775,808(-2^63)

 Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)

 This type is used when a wider range than int is needed

 Default value is 0L

 Example: long a = 100000L, long b = -200000L

Qasim Ali Page 10


Object Oriented Programming In Java
float

 Float data type is a single-precision 32-bit IEEE 754 floating point

 Float is mainly used to save memory in large arrays of floating point numbers

 Default value is 0.0f

 Float data type is never used for precise values such as currency

 Example: float f1 = 234.5f

double

 double data type is a double-precision 64-bit IEEE 754 floating point

 This data type is generally used as the default data type for decimal values, generally the default choice

 Double data type should never be used for precise values such as currency

 Default value is 0.0d

 Example: double d1 = 123.4

boolean

 boolean data type represents one bit of information

 There are only two possible values: true and false

 This data type is used for simple flags that track true/false conditions

 Default value is false

 Example: boolean one = true

char

 char data type is a single 16-bit Unicode character

 Minimum value is '\u0000' (or 0)

 Maximum value is '\uffff' (or 65,535 inclusive)

 Char data type is used to store any character

 Example: char letterA = 'A'

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.
Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

Qasim Ali Page 11


Object Oriented Programming In Java

The package keyword is used to create a package in java.

How to access package from another package


There are three ways to access the package from outside the package.

1. import package.*;

2. import package.classname;

3. fully qualified name.


Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current package.
Example of package that import the packagename.*

//save by A.java  

package pack;  

public class A{  

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

  

//save by B.java  

package mypack;  

import pack.*;    

class B{  

  public static void main(String args[]){  

   A obj = new A();  

   obj.msg();  

  }  

}  

Qasim Ali Page 12


Object Oriented Programming In Java
Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname

//save by A.java  

package pack;  

public class A{  

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

}  

//save by B.java  

package mypack;  

import pack.A;  

  class B{  

  public static void main(String args[]){  

   A obj = new A();  

   obj.msg();  

  }  

}  
Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import.
But you need to use fully qualified name every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.
Example of package by import fully qualified name

//save by A.java  

package pack;  

public class A{  

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

}  

//save by B.java  

package mypack;  

class B{  

  public static void main(String args[]){  

   pack.A obj = new pack.A();//using fully qualified name  

   obj.msg();  

  }  

}  

Qasim Ali Page 13


Object Oriented Programming In Java
Class in Java
A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It
is a logical entity. It can't be physical.
A class in Java can contain:

o fields

o methods

o constructors

o blocks

o nested class and interface

Syntax to declare a class:

class <class_name>{  

    field;  

    method;  

}  

Lamp CLass
class Lamp {
boolean isOn;
void turnOn() {
isOn = true;
}
void turnOff() {
isOn = false;
}
void displayLightStatus() {
System.out.println("Light on? " + isOn);
}
}
class ClassObjectsExample {
public static void main(String[] args) {
Lamp l1 = new Lamp(), l2 = new Lamp();
l1.turnOn();
l2.turnOff();
l1.displayLightStatus();
l2.displayLightStatus();
}
}

class Book

Qasim Ali Page 14


Object Oriented Programming In Java

private int pubyear;

private String title;

String getTitle()

return title;

int getPubYear()

return pubYear;

void setTitle(String _title)

title = _title;

void setPubYear(int _pubYear)

pubYear = _pubYear;

}
}

Instance variable in Java


A variable which is created inside the class but outside the method, is known as instance variable. Instance variable doesn't
get memory at compile time. It gets memory at run time when object(instance) is created. That is why, it is known as
instance variable.

Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or
logical (tangible and intangible). The example of intangible object is banking system.
An object has three characteristics:

o state: represents data (value) of an object.

o behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.

o identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the

external user. But, it is used internally by the JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to write, so writing is
its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are created. So object is the
instance(result) of a class.

Object Definitions:

Qasim Ali Page 15


Object Oriented Programming In Java
o Object is a real world entity.

o Object is a run time entity.

o Object is an entity which has state and behavior.

o Object is an instance of a class.

new keyword in Java


The new keyword is used to allocate memory at run time. All objects get memory in Heap memory area.
Different Ways to Create Objects in Java

Using new keyword } → constructor gets called

Using newInstance() method of Class class } → constructor gets called

Using newInstance() method of Constructor class } → constructor gets called

Using clone() method } → no constructor call

Using deserialization } → no constructor call

1. Using new keywords

Employee emp1 = new Employee();


2. Using newInstance() method of Class class 

Java Class.newInstance() is the method of Class class. The Class class belongs to java.lang package. It creates a new
instance of the class represented by this Class object. It returns the newly created instance of the class. This newInstance()
method calls the no-arg constructor to create the object.
Employee emp2 = Employee.class.newInstance();
3. Using newInstance() method of Constructor class 

Constructor<Employee> constructor = Employee.class.getConstructor();


Employee emp3 = constructor.newInstance();

This is similar to the newInstance() method of a class. There is one newInstance() method in
the java.lang.reflect.Constructor class which we can use to create objects. It can also call parameterized constructor, and
private constructor by using this newInstance() method.
Both newInstance() methods are known as reflective ways to create objects. In fact newInstance() method of Class
internally uses newInstance() method of Constructor class.

4. Using clone() method: 

Whenever we call clone() on any object, the JVM actually creates a new object for us and copies all content of the previous
object into it. Creating an object using the clone method does not invoke any constructor. Java clone() method
creates a copy of an existing object. It is defined in Object class. It returns clone of this
instance. The two most important point about clone() method is:

o The Cloneable interface must be implement while using clone() method. It is defined

in java.lang package.

o The clone() method must be override with other classes.

When we use clone() method in class, the class must call super.clone() to obtain the cloned
object reference.

To use clone() method on an object we need to implement Cloneable and define the clone() method in it. 

Qasim Ali Page 16


Object Oriented Programming In Java
Employee emp4 = (Employee) emp3.clone();
Object and Class Example: main within class

In this example, we have created a Student class that have two data members id and name. We are creating the object of the
Student class by new keyword and printing the objects value.
Here, we are creating main() method inside the class.
File: Student.java

class Student{  

 int id;//field or data member or instance variable  

 String name;  

public static void main(String args[]){  

  Student s1=new Student();//creating an object of Student  

  System.out.println(s1.id);//accessing member through reference variable  

  System.out.println(s1.name);  

 }  

}  
Object and Class Example: main outside class

In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's
see a simple example, where we are having main() method in another class.
We can have multiple classes in different java files or single java file. If you define multiple classes in a single java source
file, it is a good idea to save the file name with the class name which has main() method.
File: TestStudent1.java

class Student{  

 int id;  

 String name;  

}  

class TestStudent1{  

 public static void main(String args[]){  

  Student s1=new Student();  

  System.out.println(s1.id);  

  System.out.println(s1.name);  

 }  

}  

Ways to initialize object


There are 3 ways to initialize object in java.

1. By reference variable

2. By method

3. By constructor

Qasim Ali Page 17


Object Oriented Programming In Java
Object and Class Example: Initialization through reference

Initializing object simply means storing data into object. Let's see a simple example where we are going to initialize object
through reference variable.
File: TestStudent2.java

class Student{  

 int id;  

 String name;  

}  

class TestStudent2{  

 public static void main(String args[]){  

  Student s1=new Student();  

  s1.id=101;  

  s1.name="Sonoo";  

  System.out.println(s1.id+" "+s1.name);//printing members with a white space  

 }  

}  
Object and Class Example: Initialization through method

In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the
insertRecord method. Here, we are displaying the state (data) of the objects by invoking the displayInformation() method.
File: TestStudent4.java

class Student{  

 int rollno;  

 String name;  

 void insertRecord(int r, String n){  

  rollno=r;  

  name=n;  

 }  

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

}  

class TestStudent4{  

 public static void main(String args[]){  

  Student s1=new Student();  

  Student s2=new Student();  

  s1.insertRecord(111,"Karan");  

  s2.insertRecord(222,"Aryan");  

  s1.displayInformation();  

  s2.displayInformation();  

Qasim Ali Page 18


Object Oriented Programming In Java
 }  

}  
Object and Class Example: Employee

Let's see an example where we are maintaining records of employees.


File: TestEmployee.java

class Employee{  

    int id;  

    String name;  

    float salary;  

    void insert(int i, String n, float s) {  

        id=i;  

        name=n;  

        salary=s;  

    }  

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

}  

public class TestEmployee {  

public static void main(String[] args) {  

    Employee e1=new Employee();  

    Employee e2=new Employee();  

    Employee e3=new Employee();  

    e1.insert(101,"ajeet",45000);  

    e2.insert(102,"irfan",25000);  

    e3.insert(103,"nakul",55000);  

    e1.display();  

    e2.display();  

    e3.display();  

}  

}  
Object and Class Example: Rectangle

There is given another example that maintains the records of Rectangle class.
File: TestRectangle1.java

class Rectangle{  

 int length;  

Qasim Ali Page 19


Object Oriented Programming In Java
 int width;  

 void insert(int l, int w){  

  length=l;  

  width=w;  

 }  

 void calculateArea(){System.out.println(length*width);}  

}  

class TestRectangle1{  

 public static void main(String args[]){  

  Rectangle r1=new Rectangle();  

  Rectangle r2=new Rectangle();  

  r1.insert(11,5);  

  r2.insert(3,15);  

  r1.calculateArea();  

  r2.calculateArea();  

}  

}  
Object and Class Example: Initialization through constructor

class Rectangle{  

 int length;  

 int width;  

 public Rectangle(int l, int w){  

  length=l;  

  width=w;  

 }  

 void calculateArea(){System.out.println(length*width);}  

}  

class TestRectangle1{  

 public static void main(String args[]){  

  Rectangle r1=new Rectangle(11,5);  

  Rectangle r2=new Rectangle(3,15);  

  r1.calculateArea();  

  r2.calculateArea();  

}  

Qasim Ali Page 20


Object Oriented Programming In Java
}  
Creating multiple objects by one type only

We can create multiple objects by one type only as we do in case of primitives.


Initialization of primitive variables:

1. int a=10, b=20;  
Initialization of refernce variables:

1. Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects  
Let's see the example:

class Rectangle{  

 int length;  

 int width;  

 void insert(int l,int w){  

  length=l;  

  width=w;  

 }  

 void calculateArea(){System.out.println(length*width);}  

}  

class TestRectangle2{  

 public static void main(String args[]){  

  Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects  

  r1.insert(11,5);  

  r2.insert(3,15);  

  r1.calculateArea();  

  r2.calculateArea();  

}  

}  
Java program to find area and perimeter of a circle using class

import java.util.*;
class AreaOfCircle
{
private float radius=0.0f;
private float area=0.0f;
private float perimeter=0.0f;

//function to read radius


public void readRadius()
{
//Scanner class - to read value from keyboard
Scanner sc=new Scanner(System.in);
System.out.print("Enter radius:");
radius=sc.nextFloat(); //to read float value from keyboard
}
//funtction to calculate area
//return value - will return calculated area

Qasim Ali Page 21


Object Oriented Programming In Java
public float getArea()
{
area= Math.PI *radius*radius;
return area;
}
//funtction to calculate perimeter
//return value - will return calculated perimeter
public float getPerimeter()
{
perimeter = 2* Math.PI *radius;
return perimeter;
}
}
public class circle
{
public static void main(String []s)
{
AreaOfCircle area=new AreaOfCircle();
area.readRadius();
System.out.println("Area of circle:" + area.getArea());
System.out.println("Perimeter of circle:" + area.getPerimeter());
}
}

Output:
Enter radius:15.50
Area of circle:754.385
Perimeter of circle:97.340004
Java program to read and add two distances using class

import java.util.*;
//class Distance to read, print and add distance
class Distance
{
private int feet;
private int inches;
public void getDistance()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter feet: ");
feet=sc.nextInt();
System.out.print("Enter inches: ");
inches=sc.nextInt();
}
public void showDistance()
{
System.out.println("Feet: "+ feet + "\tInches: "+ inches);
}

public void addDistance(Distance D1, Distance D2)


{
inches=D1.inches+D2.inches;
feet=D1.feet+D2.feet+(inches/12);
inches=inches%12;
}
}
public class AddTwoDistance
{
public static void main(String []s)
{
try
{

Distance D1=new Distance();


Distance D2=new Distance();
Distance D3=new Distance();
//read first distance

Qasim Ali Page 22


Object Oriented Programming In Java
System.out.println("Enter first distance: ");
D1.getDistance();
//read second distance
System.out.println("Enter second distance: ");
D2.getDistance()
//add distances
D3.addDistance(D1,D2);
//print distance
System.out.println("Total distance is:" );
D3.showDistance();
}
catch (Exception e)
{
System.out.println("Exception occurred :"+ e.toString());
}
}
}

Output

Enter first distance:


Enter feet: 20
Enter inches: 10
Enter second distance:
Enter feet: 20
Enter inches: 10
Total distance is:
Feet: 41 Inches: 8
Real World Example: Account

File: TestAccount.java

class Account{  

int acc_no;  

String name;  

float amount;  

void insert(int a,String n,float amt){  

acc_no=a;  

name=n;  

amount=amt;  

}  

void deposit(float amt){  

amount=amount+amt;  

System.out.println(amt+" deposited");  

}  

void withdraw(float amt){  

if(amount<amt){  

System.out.println("Insufficient Balance");  

}else{  

amount=amount-amt;  

Qasim Ali Page 23


Object Oriented Programming In Java
System.out.println(amt+" withdrawn");  

}  

}  

void checkBalance(){System.out.println("Balance is: "+amount);}  

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

}  

class TestAccount{  

public static void main(String[] args){  

Account a1=new Account();  

a1.insert(832345,"Ankit",1000);  

a1.display();  

a1.checkBalance();  

a1.deposit(40000);  

a1.checkBalance();  

a1.withdraw(15000);  

a1.checkBalance();  

}}   
Output:
832345 Ankit 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0

Access Modifiers in java


There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of java access modifiers:

1. private

2. default

3. protected

4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will
learn access modifiers.

private access modifier

The private access modifier is accessible only within class.


Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data member and private method. We

are accessing these private members from outside the class, so there is compile time error.

class A{  

Qasim Ali Page 24


Object Oriented Programming In Java
private int data=40;  

private void msg(){System.out.println("Hello java");}  

}  

  

public class Simple{  

 public static void main(String args[]){  

   A obj=new A();  

   System.out.println(obj.data);//Compile Time Error  

   obj.msg();//Compile Time Error  

   }  

}  
Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside the class. For example:

class A{  

private A(){}//private constructor  

void msg(){System.out.println("Hello java");}  

}  

public class Simple{  

 public static void main(String args[]){  

   A obj=new A();//Compile Time Error  

 }  

Note: A class can never be private or protected.


default access modifier

If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package.

protected access modifier


The protected access modifier is accessible within package and outside the package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.

 public access modifier

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Understanding all java access modifiers


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

Acc w w o o
ess i i u u
Mo t t t t

Qasim Ali Page 25


Object Oriented Programming In Java
difie h h s s
r i i i i
n n d d
p e e
a p p
c
c a a
l
k c c
a
a k k
s
g a a
s
e g g
e e
b
y
s
u
b
c
l
a
s
s
o
n
l
y

P Y N N N

ri

D Y Y N N

lt

P Y Y Y N

Qasim Ali Page 26


Object Oriented Programming In Java

P Y Y Y Y

li

Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is
why it is known as constructor.

Rules for creating java constructor


There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name

2. Constructor must have no explicit return type

Types of java constructors


There are two types of constructors:

1. Default constructor (no-arg constructor)

2. Parameterized constructor

Java Default Constructor

A constructor that have no parameter is known as default constructor.

Syntax of default constructor:

1. <class_name>(){}  
Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object

creation.

Qasim Ali Page 27


Object Oriented Programming In Java
class Bike1{  

Bike1(){System.out.println("Bike is created");}  

public static void main(String args[]){  

Bike1 b=new Bike1();  

}  

}  

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

What is the purpose of default constructor?


Default constructor provides the default values to the object like 0, null etc. depending on the type.
Example of default constructor that displays the default values

class Student3{  

int id;  

String name;  

  

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

public static void main(String args[]){  

Student3 s1=new Student3();  

Student3 s2=new Student3();  

s1.display();  

s2.display();  

}  

}  

Java parameterized constructor

A constructor that have parameters is known as parameterized constructor.

Why use parameterized constructor?

Parameterized constructor is used to provide different values to the distinct objects.


Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any number of

parameters in the constructor.

class Student4{  

    int id;  

    String name;  

      

Qasim Ali Page 28


Object Oriented Programming In Java
    Student4(int i,String n){  

    id = i;  

    name = n;  

    }  

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

   

    public static void main(String args[]){  

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

    Student4 s2 = new Student4(222,"Aryan");  

    s1.display();  

    s2.display();  

   }  

}  
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.
Example of Constructor Overloading

class Student5{  

    int id;  

    String name;  

    int age;  

    Student5(int i,String n){  

    id = i;  

    name = n;  

    }  

    Student5(int i,String n,int a){  

    id = i;  

    name = n;  

    age=a;  

    }  

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

    public static void main(String args[]){  

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

    Student5 s2 = new Student5(222,"Aryan",25);  

    s1.display();  

Qasim Ali Page 29


Object Oriented Programming In Java
    s2.display();  

   }  

}  
Difference between constructor and method in java

Java Constructor Java Method

Constructor is used to initialize the state of an object. Method is used to expose behaviour

of an object.

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

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if Method is not provided by compiler

you don't have any constructor. in any case.

Constructor name must be same as the class name. Method name may or may not be

same as class name.

Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit
from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).

o For Code Reusability.

Syntax of Java Inheritance

class Subclass-name extends Superclass-name  

{  

   //methods and fields  

}  
The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of
"extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called parent or super class and the new class is called child or
subclass.

Qasim Ali Page 30


Object Oriented Programming In Java
Java Inheritance Example

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

}  

}  
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces
later.

Qasim Ali Page 31


Object Oriented Programming In Java

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

Single Inheritance Example


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

}  
Multilevel Inheritance Example
File: TestInheritance2.java

class Animal{  

void eat(){System.out.println("eating...");}  

}  

class Dog extends Animal{  

void bark(){System.out.println("barking...");}  

}  

Qasim Ali Page 32


Object Oriented Programming In Java
class BabyDog extends Dog{  

void weep(){System.out.println("weeping...");}  

}  

class TestInheritance2{  

public static void main(String args[]){  

BabyDog d=new BabyDog();  

d.weep();  

d.bark();  

d.eat();  

}  
Hierarchical Inheritance Example
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  

}}  

The super keyword

The super keyword is similar to this keyword. Following are the scenarios where the super keyword is used.

 It is used to differentiate the members of superclass from the members of subclass, if they have same names.

 It is used to invoke the superclass constructor from subclass.

Qasim Ali Page 33


Object Oriented Programming In Java
Differentiating the Members

If a class is inheriting the properties of another class. And if the members of the superclass have the names same as the

sub class, to differentiate these variables we use super keyword as shown below.
super.variable
super.method();

Sample Code

This section provides you a program that demonstrates the usage of the super keyword.

In the given program, you have two classes namely Sub_class and Super_class, both have a method named display() with

different implementations, and a variable named num with different values. We are invoking display() method of both

classes and printing the value of the variable num of both classes. Here you can observe that we have used super keyword

to differentiate the members of superclass from subclass.

Copy and paste the program in a file with name Sub_class.java.

Example

class Super_class {
int num = 20;
// display method of superclass
public void display() {
System.out.println("This is the display method of superclass");
}
}
public class Sub_class extends Super_class {
int num = 10;
// display method of sub class
public void display() {
System.out.println("This is the display method of subclass");
}
public void my_method() {
// Instantiating subclass
Sub_class sub = new Sub_class();
// Invoking the display() method of sub class
sub.display();
// Invoking the display() method of superclass
super.display();
// printing the value of variable num of subclass
System.out.println("value of the variable named num in sub class:"+ sub.num);
// printing the value of variable num of superclass
System.out.println("value of the variable named num in super class:"+ super.num);
}
public static void main(String args[]) {
Sub_class obj = new Sub_class();
obj.my_method();
}
}

Qasim Ali Page 34


Object Oriented Programming In Java
Compile and execute the above code using the following syntax.
javac Super_Demo
java Super

On executing the program, you will get the following result −

Output
This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20

Invoking Superclass Constructor

If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the

superclass. But if you want to call a parameterized constructor of the superclass, you need to use the super keyword as

shown below.
super(values);

Sample Code

The program given in this section demonstrates how to use the super keyword to invoke the parametrized constructor of

the superclass. This program contains a superclass and a subclass, where the superclass contains a parameterized

constructor which accepts a string value, and we used the super keyword to invoke the parameterized constructor of the

superclass.

Copy and paste the following program in a file with the name Subclass.java

Example

class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
public void getAge() {
System.out.println("The value of the variable named age in super class is: " +age);
}
}
public class Subclass extends Superclass {
Subclass(int age) {
super(age);
}
public static void main(String argd[]) {
Subclass s = new Subclass(24);
s.getAge();
}
}

Compile and execute the above code using the following syntax.

Qasim Ali Page 35


Object Oriented Programming In Java
javac Subclass
java Subclass

On executing the program, you will get the following result −

Output
The value of the variable named age in super class is: 24

The instanceof Keyword

Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an

Animal.

Example

interface Animal{}
class Mammal implements Animal{}
public class Dog extends Mammal {
public static void main(String args[]) {
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

Bicycle Class Example with Inheritance


class Bicycle
{
    // the Bicycle class has two fields
    public int gear;
    public int speed;
    // the Bicycle class has one constructor
    public Bicycle(int gear, int speed)
    {
        this.gear = gear;
        this.speed = speed;
    }         
    // the Bicycle class has three methods
    public void applyBrake(int decrement)
    {
        speed -= decrement;
    }       
    public void speedUp(int increment)
    {
        speed += increment;
    }    
    // toString() method to print info of Bicycle
    public String toString()
    {
        return("No of gears are "+gear
                +"\n"
                + "speed of bicycle is "+speed);
    }

// derived class
class MountainBike extends Bicycle
{     
    // the MountainBike subclass adds one more field

Qasim Ali Page 36


Object Oriented Programming In Java
    public int seatHeight;
    // the MountainBike subclass has one constructor
    public MountainBike(int gear,int speed,
                        int startHeight)
    {
        // invoking base-class(Bicycle) constructor
        super(gear, speed);
        seatHeight = startHeight;
    }          
    // the MountainBike subclass adds one more method
    public void setHeight(int newValue)
    {
        seatHeight = newValue;
    }      
    // overriding toString() method
    // of Bicycle to print more info
    @Override
    public String toString()
    {
        return (super.toString()+
                "\nseat height is "+seatHeight);
    }     

// driver class
public class Test
{
    public static void main(String args[])
    {         
        MountainBike mb = new MountainBike(3, 100, 25);
        System.out.println(mb.toString());             
    }
}
Output:

No of gears are 3
speed of bicycle is 100
seat height is 25

In above program, when an object of MountainBike class is created, a copy of the all methods and fields of the superclass

acquire memory in this object. That is why, by using the object of the subclass we can also access the members of a

superclass.

Please note that during inheritance only object of subclass is created, not the superclass. For more, refer Java Object

Creation of Inherited Class.

Shape Class Inheritance Example with Setters and Getters and Constructor Overloading

Parent Class (Shape)

package javaapplication1;

/**

* @author Qasim Ali

*/

public class Shape {

private String name;

private float area;

Qasim Ali Page 37


Object Oriented Programming In Java
private float perimeter;

public Shape(String n)

name=n;

public void setName(String name)

this.name=name;

public void setArea(float area)

this.area=area;

public void setPerimeter(float perimeter)

this.perimeter=perimeter;

public String getName()

return name;

public float getArea()

return area;

public float getPerimeter()

return perimeter;

Child Class (Rectangle)

package javaapplication1;

/**

Qasim Ali Page 38


Object Oriented Programming In Java
* @author Qasim Ali

*/

public class Rectangle extends Shape {

private float length;

private float width;

public Rectangle(String n, float l)

super(n);

length=l;

public Rectangle(String n)

super(n);

public Rectangle(String n, float l, float w)

super(n);

length=l;

width=w;

public void setLength(float l)

If(l>0)

length=l;

else

System.out.println(“Length should be +ve”);

public void setWidth(float w)

If(w>0)

width=w;

else

System.out.println(“Width should be +ve”);

Qasim Ali Page 39


Object Oriented Programming In Java
}

public float getLength()

return length;

public float getWidth()

return width;

public void calculateArea()

super.setArea(getWidth()*getLength());

public void calculatePerimeter()

setPerimeter(2*(getWidth()+getLength()));

public void display()

System.out.println("Name of Shape="+getName());

System.out.println("Length of Rectangle="+getLength());

System.out.println("Width of Rectangle="+getWidth());

System.out.println("Area of Shape="+getArea());

System.out.println("Perimeter of Shape"+getPerimeter());

Demo Class (TestShape)

package javaapplication1;

/**

* @author Qasim Ali

*/

public class TestShape {

public static void main(String[] args) {

Qasim Ali Page 40


Object Oriented Programming In Java
Rectangle r=new Rectangle("Rectangle",12,12);

r.calculateArea();

r.calculatePerimeter();

r.display();

Rectangle r1=new Rectangle("Rectangle",13);

r1.setWidth(20);

r1.calculateArea();

r1.calculatePerimeter();

r1.display();

}
Problem Statement

Implement a Remote class that models the remote control unit


of Figure 12.1 . When the TV is initially switched on, the default channel is 2 and the
default volume is 5.

Java Solution
The Remote class has two attributes:
• volume , an integer in the range 0 through 20, and
• channel , an integer in the range 1 through 199.
The methods simulate the functions of the buttons in Figure 12.1 . These methods are
• channelUp() and channelDown() , which respectively increase and decrease
channel by one, and
• volumeUp() and volumeDown() , which increase or decrease volume .
The Remote class has no fancy code or complicated methods. In addition to the
methods channelUp() , channelDown() , volumeUp() , and volumeDown() , the Remote
class implements two additional methods:
• display() , which displays the current volume and channel, and
• menu() , which presents a list of options to a user.
Each time a user “presses any button,” display() shows the current channel and the
volume.
You may notice that the instance variables of the following class are declared
as protected . For the present, ignore this access modifi er. We explain its meaning in
Example 12.2.
import java.util.*;
public class Remote
{
protected int volume; // notice the protected access modifier
protected int channel;
protected final int MAXIMUM_VOLUME = 20; // highest volume setting
protected final int MAXIMUM_CHANNEL = 199; // highest channel number

protected final int DEFAULT_CHANNEL = 2; // default channel number


protected final int DEFAULT_VOLUME = 5; // default volume setting
protected final int MINIMUM_VOLUME = 0; // minimum volume, no sound
protected final int MINIMUM_CHANNEL = 1; // lowest channel number
public Remote() // default constructor
{
channel = DEFAULT_CHANNEL;
volume = DEFAULT_VOLUME;
}
public Remote(int ch, int vol ) // two argument constructor
{ // assumes valid data
channel = ch;
volume = vol;
}
public void volumeUp() // increase volume by one unit

Qasim Ali Page 41


Object Oriented Programming In Java
{
if (volume < MAXIMUM_VOLUME) // cannot exceed MAXIMUM_VOLUME
volume++;
}
public void volumeDown() // decrease volume by one unit
{
if (volume > MINIMUM_VOLUME) // cannot go lower than MINIMUM_VOLUME
volume --;
}
public void channelUp() // increase channel number by 1
{
if (channel < MAXIMUM_CHANNEL ) // cannot exceed MAXIMUM_CHANNEL
channel++;
}
public void channelDown() // decrease channel number by 1
{
if (channel > MINIMUM_CHANNEL) // cannot go lower than MINIMUM_CHANNEL
channel --;
}
public void display() // show the volume and the channel
{
System.out.println("\n----------------------");
System.out.println("Channel: " + channel);
System.out.println("Volume: " +volume);
System.out.println("----------------------\n");
}
public void menu() // presents user with the choices of Figure 12.2
{
Scanner input = new Scanner(System.in);
String choice;
System.out.println("POWER ON");
display();
do
{
System.out.println("Channel up: +");
System.out.println("Channel down: -");
System.out.println("Volume up: ++");
System.out.println("Volume down: --");
System.out.println("Power off: o");
System.out.print("Choose: ");
choice = input.next();
if (choice.equals("+"))
channelUp();
else if (choice.equals("-"))
channelDown();
else if (choice.equals("++"))
volumeUp();
else if (choice.equals("--"))
volumeDown();
display();
} while (! choice.equals("o"));
System.out.println("POWER OFF");
}
public static void main(String[] args)
{
Remote remote = new Remote();
remote.menu();
}
}

Output
POWER ON
----------------------
Channel: 2
Volume: 5
----------------------
Channel up: +
Channel down: -
Volume up: ++
Volume down: --

Qasim Ali Page 42


Object Oriented Programming In Java
Power off: o
Choose: +
----------------------
Channel: 3
Volume: 5
----------------------
Channel up: +
Channel down: -
Volume up: ++
Volume down: --
Power off: o
Choose: --
----------------------
Channel: 3
Volume: 6
----------------------
Channel up: +
Channel down: -
Volume up: ++
Volume down: --
Power off: o
Choose: o
----------------------
Channel: 3
Volume: 6
----------------------
POWER OFF

DirectRemote, a subclass of Remote

mport java.util.*;
public class DirectRemote extends Remote // Remote is the base class; DirectRemote a subclass
{
protected int lastChannel; // to reset to the previous channel
public DirectRemote() // default constructor
{
super(); // call the default constructor of remote
lastChannel = DEFAULT_CHANNEL; // DEFAULT_CHANNEL inherited from Remote
}
public DirectRemote(int ch, int vol, int last) // three-argument constructor
{
super(ch, vol); // a call to the two-argument constructor of Remote
lastChannel = last;
}
public void channelUp() // overrides the channelUp() method of Remote
{
lastChannel = channel;
super.channelUp(); // a call to the channelUp() method of Remote
}
public void channelDown () // overrides the channelDown() method of Remote
{
lastChannel = channel;
super.channelDown(); // a call to the channelDown() method of Remote
}
public void setChannel(int ch)
{
lastChannel = channel;
channel = ch;
}
public void last() // sets channel to previously viewed channel
{
int temp = channel;
channel = lastChannel;
lastChannel = temp;
}
public void menu() // the user interface
{
Scanner input = new Scanner(System.in);
String choice;

Qasim Ali Page 43


Object Oriented Programming In Java
System.out.println("POWER ON");
display(); // method inherited from Remote
do
{
System.out.println("Channel up: +");
System.out.println("Channel down: -");
System.out.println("Volume up: ++");
System.out.println("Volume down: --");
System.out.println("Last channel: << ");
System.out.println("Enter channel number: ");
System.out.println("Power off o");
System.out.print("Choose: ");
choice = input.next();
if (choice.equals("+"))
channelUp(); // overrides the Remote methode
else if (choice.equals("-"))
channelDown(); // overrides the Remote method
else if (choice.equals("++"))
volumeUp(); // inherited from Remote
else if (choice.equals("--"))
volumeDown(); // inherited from Remote
else if (choice.equals("<< "))
last(); // resets channel to previously viewed channel
else if ( !choice.equals("o")) // choice is a number or invalid
{
int ch = getChannel(choice);
if (ch >= 1 && ch <= 200) // if valid channel
setChannel(ch);
}
display();
} while (! choice.equals("o"));
System.out.println("POWER OFF");
}
private int getChannel(String ch) // a helper method
// converts a string of digits to an integer
// if a character of ch is not a digit returns 0
{
int number = 0;
for (int i = 0; i < ch.length(); i++)
{
char digit = ch.charAt(i);
if ( digit _>'9' || digit < '0')
return 0;
number = 10 * number + (digit - '0');
}
return number;
}
public static void main(String[] args)
{
DirectRemote remote _ new DirectRemote();
remote.menu();
}
}
Output
Instantiation of a DirectRemote object produces the following output:
POWER ON
----------------------
Channel: 2
Volume: 5
----------------------
Channel up: +
Channel down: -
Volume up: ++
Volume down: --
Last channel: <<
Enter channel number:
Power off o
Choose: 16
----------------------
Channel: 16

Qasim Ali Page 44


Object Oriented Programming In Java
Volume: 5
----------------------
Channel up: +
Channel down: -
Volume up: ++
Volume down: --
Last channel: <<
Enter channel number:
Power off o
Choose: 12
----------------------
Channel: 12
Volume: 5
----------------------
Channel up: +
Channel down: -
Volume up: ++
Volume down: --
Last channel: <<
Enter channel number:
Power off o
Choose: <<
----------------------
Channel: 16
Volume: 5
----------------------
Channel up: +
Channel down: -
Volume up: ++
Volume down: --
Last channel: <<
Enter channel number:
Power off o
Choose: ++
----------------------
Channel: 16
Volume: 6
----------------------
Channel up: +
Channel down: -
Volume up: ++
Volume down: --
Last channel: <<
Enter channel number:
Power off o
Choose: o
----------------------
Channel: 16
Volume: 6
----------------------
POWER OFF

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it
shows only important things to the user and hides the internal details for example sending sms, you just type the text and
send the message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction


There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)

2. Interface (100%)

Qasim Ali Page 45


Object Oriented Programming In Java
Abstract class in Java
A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It
cannot be instantiated.

Example abstract class

1. abstract class A{} 
abstract method

A method that is declared as abstract and does not have implementation is known as abstract method.

Example abstract method

1. abstract void printStatus();//no body and abstract  
Example of abstract class that has abstract method
In this example, Bike the abstract class that contains only one abstract method run. It implementation is provided by the
Honda class.

Public abstract class Bike{  

 Public  abstract void run();  

}  

class Honda4 extends Bike{  

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

public static void main(String args[]){  

 Bike obj = new Honda4();  

 obj.run();  

}  

}  

Parent Class Shape with two abstract methods

1. calculateArea

2. calculatePerimeter

package javaapplication1;

/**

* @author Qasim Ali

*/

public abstract class Shape {

private String name;

private double area;

private double perimeter;

public Shape(String n)

Qasim Ali Page 46


Object Oriented Programming In Java
name=n;

public void setName(String name)

this.name=name;

public void setArea(double area)

this.area=area;

public void setPerimeter(double perimeter)

this.perimeter=perimeter;

public String getName()

return name;

public double getArea()

return area;

public double getPerimeter()

return perimeter;

public abstract void calculateArea();

public abstract void calculatePerimeter();

Child Class Rectangle

package javaapplication1;

/**

* @author Qasim Ali

Qasim Ali Page 47


Object Oriented Programming In Java
*/

public class Rectangle extends Shape {

private float length;

private float width;

public Rectangle(String n, float l)

super(n);

length=l;

public Rectangle(String n)

super(n);

public Rectangle(String n, float l, float w)

super(n);

length=l;

width=w;

public void setLength(float l)

if(l>0)

length=l;

else

System.out.println("Length should be +ve");

public void setWidth(float w)

if(w>0)

width=w;

else

System.out.println("Width should be +ve");

public float getLength()

Qasim Ali Page 48


Object Oriented Programming In Java
{

return length;

public float getWidth()

return width;

public void calculateArea()

super.setArea(getWidth()*getLength());

public void calculatePerimeter()

setPerimeter(2*(getWidth()+getLength()));

public void display()

System.out.println("Name of Shape="+getName());

System.out.println("Length of Rectangle="+getLength());

System.out.println("Width of Rectangle="+getWidth());

System.out.println("Area of Shape="+getArea());

System.out.println("Perimeter of Shape"+getPerimeter());

Child Class Circle

package javaapplication1;

import java.util.*;

/**

* @author Qasim Ali

*/

public class Circle extends Shape {

private double radius;

public Circle(String n, double r)

Qasim Ali Page 49


Object Oriented Programming In Java
{

super(n);

radius=r;

public Circle(String n)

super(n);

public void setRadius(double r)

if(r>0)

radius=r;

else

System.out.println("Area should be +ve");

public double getRadius()

return radius;

public void calculateArea()

setArea(3.145*getRadius()*getRadius());

public void calculatePerimeter()

setPerimeter(2*3.15*getRadius());

public void display()

System.out.println("Name of Shape="+getName());

System.out.println("Radius of Circle="+getRadius());

System.out.println("Area of Circle="+getArea());

System.out.println("Perimeter of Circle"+getPerimeter());

Qasim Ali Page 50


Object Oriented Programming In Java
}

Demo Class TestShape

package javaapplication1;

/**

* @author Qasim Ali

*/

public class TestShape {

public static void main(String[] args) {

Rectangle r=new Rectangle("Rectangle",12,12);

r.calculateArea();

r.calculatePerimeter();

r.display();

Circle c = new Circle("Circle", 12.4);

c.calculateArea();

c.calculatePerimeter();

c.display();

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

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. We will have detailed learning of these. Let's first learn the basics of final
keyword.

Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be constant).

class Bike9{  

 final int speedlimit=90;//final variable  

 void run(){  

  speedlimit=400;  

 }  

 public static void main(String args[]){  

Qasim Ali Page 51


Object Oriented Programming In Java
 Bike9 obj=new  Bike9();  

 obj.run();  

 }  

}//end of class  

Java final method


If you make any method as final, you cannot override it.

class Bike{  

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

}  

class Honda extends Bike{  

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

   public static void main(String args[]){  

   Honda honda= new Honda();  

   honda.run();  

   }  

}  

Java final class


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

final class Bike{}    

class Honda1 extends Bike{  

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

  public static void main(String args[]){  

  Honda1 honda= new Honda();  

  honda.run();  

  }  

}  
Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For Example:

class Bike{  

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

}  

class Honda2 extends Bike{  

   public static void main(String args[]){  

    new Honda2().run();  

Qasim Ali Page 52


Object Oriented Programming In Java
   }  

What is blank or uninitialized final variable?


A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is
useful. For example PAN CARD number of an employee.
It can be initialized only in constructor.
Example of blank final variable

class Student{  

int id;  

String name;  

final String PAN_CARD_NUMBER;  

...  

}  

Can we initialize blank final variable?


Yes, but only in constructor. For example:

class Bike10{  

  final int speedlimit;//blank final variable  

    

  Bike10(){  

  speedlimit=70;  

  System.out.println(speedlimit);  

  }    

  public static void main(String args[]){  

    new Bike10();  

 }  

}  

Mammal Interface
public interface Mammal {
    public void eat();
 
    public void move();
 
    public void sleep();
}

Animal Class (Abstract)

public abstract class Animal implements Mammal {


    public void eat() {
        System.out.println("Eating...");
    }
 

Qasim Ali Page 53


Object Oriented Programming In Java
    public void move() {
        System.out.println("Moving...");
    }
 
    public void sleep() {
        System.out.println("Sleeping...");
    }
 
}
Dog Class (Concrete)
public class Dog extends Animal {
    public void bark() {
        System.out.println("Gow gow!");
    }
    public void eat() {
        System.out.println("Dog is eating...");
    }
}
 Cat Class (Concrete)
public class Cat extends Animal {
    public void meow() {
        System.out.println("Meow Meow!");
    }
}

What is Upcasting?
Upcasting is casting a subtype to a supertype, upward to the inheritance tree. Let’s see an example:
1 Dog dog = new Dog();
2 Animal anim = (Animal) dog; //upcasting
3 anim.eat();
Here, we cast the Dog type to the Animal type. Because Animal is the supertype of Dog, this casting is called upcasting.
Note that the actual object type does not change because of casting. The Dog object is still a Dog object. Only the reference
type gets changed. Hence the above code produces the following output:
1 Dog is eating…
 
Upcasting is always safe, as we treat a type to a more general one. In the above example, an Animal has all behaviors of
a Dog.
This is also another example of upcasting:
1 Mammal mam = new Cat();
2 Animal anim = new Dog();

Why is Upcasting?

Generally, upcasting is not necessary. However, we need upcasting when we want to write general code that deals with only the

supertype. 

What is Downcasting?
Downcasting is casting to a subtype, downward to the inheritance tree. Let’s see an example:
1
Animal anim = new Cat(); // upcasting
2
Cat cat = (Cat) anim;
Here, we cast the Animal type to the Cat type. As Cat is subclass of Animal, this casting is called downcasting.
Unlike upcasting, downcasting can fail if the actual object type is not the target object type. For example:
1 Animal anim = new Cat();
2 Dog dog = (Dog) anim;

Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.
Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more
object named address, which contains its own informations such as city, state, country, zipcode etc. as given below.

Qasim Ali Page 54


Object Oriented Programming In Java
1. class Employee{  

2. int id;  

3. String name;  

4. Address address;//Address is a class  

5. ...  

6. }  
In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.

Why use Aggregation?

o For Code Reusability.


Simple Example of Aggregation

In this example, we have created the reference of Operation class in the Circle class.

class Operation{  

 int square(int n){  

  return n*n;  

 }  

class Circle{  

 Operation op;//aggregation  

 double pi=3.14;      

 double area(int radius){ 

op=new Operation();  

   int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).  

   return pi*rsquare;  

 }  

 public static void main(String args[]){  

   Circle c=new Circle();  

   double result=c.area(5);  

   System.out.println(result);  

Qasim Ali Page 55


Object Oriented Programming In Java
 }  

}  
When use Aggregation?

o Code reuse is also best achieved by aggregation when there is no is-a relationship.

o Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects

involved; otherwise, aggregation is the best choice.


Understanding meaningful example of Aggregation

In this example, Employee has an object of Address, address object contains its own informations such as city, state,
country etc. In such case relationship is Employee HAS-A address.
Address.java

public class Address {  

String city,state,country;  

public Address(String city, String state, String country) {  

    this.city = city;  

    this.state = state;  

    this.country = country;  

}  

}  
Emp.java

public class Emp {  

int id;  

String name;  

Address address;  

public Emp(int id, String name,Address address) {  

    this.id = id;  

    this.name = name;  

    this.address=address;  

}  

void display(){  

System.out.println(id+" "+name);  

System.out.println(address.city+" "+address.state+" "+address.country);  

}  

public static void main(String[] args) {  

Address address1=new Address("gzb","UP","india");  

Address address2=new Address("gno","UP","india");  

Qasim Ali Page 56


Object Oriented Programming In Java
Emp e=new Emp(111,"varun",address1);  

Emp e2=new Emp(112,"arun",address2);  

e.display();  

e2.display();  

      

}  

}  

Car has Engine Relationship


import java.io.*;
 
// Engine class which will
// be used by car. so 'Car'
// class will have a field
// of Engine type.
class Engine
{
    // starting an engine.
    public void work()
    {
         
        System.out.println("Engine of car has been started ");
         
    }
     
}
 
// Engine class
class Car
{
     
    // For a car to move,
    // it need to have a engine.
    private Engine engine; // Composition
    //private Engine engine;     // Aggregation
     
    Car(Engine engine)
    {
        this.engine = engine;
    }
     
    // car start moving by starting engine
    public void move()
    {
         
        //if(engine != null)
        {
            engine.work();
            System.out.println("Car is moving ");
        }
    }
}
 
class GFG
{
    public static void main (String[] args)
    {
         
        // making an engine by creating
        // an instance of Engine class.
        Engine engine = new Engine();

Qasim Ali Page 57


Object Oriented Programming In Java
         
        // Making a car with engine.
        // so we are passing a engine
        // instance as an argument while
        // creating instace of Car.
        Car car = new Car(engine);
        car.move();
         
    }
}
Aggregation
It is a special form of Association where:
 It represents Has-A relationship.
 It is a unidirectional association i.e. a one way relationship. For example, department can have students but vice
versa is not possible and thus unidirectional in nature.
 In Aggregation, both the entries can survive individually which means ending one entity will not effect the
other entity
// Java program to illustrate
//the concept of Aggregation.
import java.io.*;
import java.util.*;
 
// student class

class Student
{
    String name;
    int id ;
    String dept;
     
    Student(String name, int id, String dept)
    {
         
        this.name = name;
        this.id = id;
        this.dept = dept;
         
    }
}
 
/* Department class contains list of student
Objects. It is associated with student
class through its Object(s). */
class Department
{
    String name;
    private List<Student> students;
    Department(String name, List<Student> students)
    {
        this.name = name;
        this.students = students;       
    }
    public List<Student> getStudents()
    {
        return students;
    }
}
 
/* Institute class contains list of Department
Objects. It is asoociated with Department
class through its Object(s).*/
class Institute
{
    String instituteName;

Qasim Ali Page 58


Object Oriented Programming In Java
    private List<Department> departments;   
    Institute(String instituteName, List<Department> departments)
    {
        this.instituteName = instituteName;
        this.departments = departments;
    }
    // count total students of all departments
    // in a given institute
    public int getTotalStudentsInInstitute()
    {
        int noOfStudents = 0;
        List<Student> students;
        for(Department dept : departments)
        {
            students = dept.getStudents();
            for(Student s : students)
            {
                noOfStudents++;
            }
        }
        return noOfStudents;
    }
}
 
// main method
class GFG
{
    public static void main (String[] args)
    {
        Student s1 = new Student("Mia", 1, "CSE");
        Student s2 = new Student("Priya", 2, "CSE");
        Student s3 = new Student("John", 1, "EE");
        Student s4 = new Student("Rahul", 2, "EE");
     
        // making a List of
        // CSE Students.
        List <Student> cse_students = new ArrayList<Student>();
        cse_students.add(s1);
        cse_students.add(s2);
         
        // making a List of
        // EE Students
        List <Student> ee_students = new ArrayList<Student>();
        ee_students.add(s3);
        ee_students.add(s4);
         
        Department CSE = new Department("CSE", cse_students);
        Department EE = new Department("EE", ee_students);
         
        List <Department> departments = new ArrayList<Department>();
        departments.add(CSE);
        departments.add(EE);
         
        // creating an instance of Institute.
        Institute institute = new Institute("BITS", departments);
         
        System.out.print("Total students in institute: ");
        System.out.print(institute.getTotalStudentsInInstitute());
    }
}

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.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.

Qasim Ali Page 59


Object Oriented Programming In Java
Why use Java interface?
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.

The java compiler adds public and abstract keywords before the interface method. More, it adds public, static and
final keywords before data members.

Java Interface Example: Bank


Let's see another example of java interface which provides the implementation of Bank interface.

interface Bank{  

float rateOfInterest();  

}  

class SBI implements Bank{  

public float rateOfInterest(){return 9.15f;}  

}  

class PNB implements Bank{  

public float rateOfInterest(){return 9.7f;}  

}  

Qasim Ali Page 60


Object Oriented Programming In Java
File: TestInterface2.java

class TestInterface2{  

public static void main(String[] args){  

Bank b=new SBI();  

System.out.println("ROI: "+b.rateOfInterest());  

}}  
Problem Statement
Define Circle, Square and Triangle classes each of which implements the Geometry interface.
Java Solution Because the following classes implement Geometry, each class is
required to implement the area() and perimeter() methods. For simplicity, the usual
getter and setter methods are not included.

Public interface Geometry


{
Public abstract double perimeter();
Public abstract double area();
}
public class Circle implements Geometry
{
private double radius;
public Circle()
{
radius = 0.0;
}
public Circle (double r)
{
radius = r;
}
public double perimeter()
{
return 2 * PI * radius;
}
public double area()
{
return PI * radius * radius;
}
}
public class Square implements Geometry
{
private double side;
public Square()
{
side = 0.0;
}
public Square (double s)
{
side = s;
}
public double perimeter()
{
return 4 * side;
}
public double area()
{
return side * side;
}
}
class Triangle implements Geometry
{
private double a, b, c;
public Triangle()
{
a = b = c = 0.0;

Qasim Ali Page 61


Object Oriented Programming In Java
}
public Triangle (double a1, double b1, double c1)
{
a = a1;
b = b1;
c = c1;
}
public double perimeter()
{
return a + b + c;
}
public double area()
{
double s = (a + b + c)/2.0;
return
Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
}
A real world example:
Let’s consider the example of vehicles like bicycle, car, bike………,they have common functionalities. So we make an
interface and put all these common functionalities. And lets Bicylce, Bike, car ….etc implement all these functionalities in
their own class in their on way.

import java.io.*; 
interface Vehicle {
    // all are the abstract methods.
    void changeGear(int a);
    void speedUp(int a);
    void applyBrakes(int a);
}
 
class Bicycle implements Vehicle{
     
    int speed;
    int gear;
     
     // to change gear
    @Override
    public void changeGear(int newGear){
         
        gear = newGear;
    }
     
    // to increase speed
    @Override
    public void speedUp(int increment){
         
        speed = speed + increment;
    }
     
    // to decrease speed
    @Override
    public void applyBrakes(int decrement){
         
        speed = speed - decrement;
    }
     
    public void printStates() {
         System.out.println("speed: " + speed
              + " gear: " + gear);
    }
}
class Bike implements Vehicle {
     
    int speed;
    int gear;
     
    // to change gear
    @Override
    public void changeGear(int newGear){

Qasim Ali Page 62


Object Oriented Programming In Java
         
        gear = newGear;
    }
     
    // to increase speed
    @Override
    public void speedUp(int increment){
         
        speed = speed + increment;
    }
     
    // to decrease speed
    @Override
    public void applyBrakes(int decrement){
         
        speed = speed - decrement;
    }
     
    public void printStates() {
         System.out.println("speed: " + speed
             + " gear: " + gear);
    }
     
}
class GFG {
     
    public static void main (String[] args) {
     
        // creating an inatance of Bicycle
        // doing some operations
        Bicycle bicycle = new Bicycle();
        bicycle.changeGear(2);
        bicycle.speedUp(3);
        bicycle.applyBrakes(1);
         
        System.out.println("Bicycle present state :");
        bicycle.printStates();
         
        // creating instance of bike.
        Bike bike = new Bike();
        bike.changeGear(1);
        bike.speedUp(4);
        bike.applyBrakes(3);
         
        System.out.println("Bike present state :");
        bike.printStates();
    }
}
Abstract class vs Interface
1. Type of methods: Interface can have only abstract methods. Abstract class can have abstract and non-abstract
methods. From Java 8, it can have default and static methods also.
2. Final Variables: Variables declared in a Java interface are by default final. An abstract class may contain non-
final variables.
3. Type of variables: Abstract class can have final, non-final, static and non-static variables. Interface has only
static and final variables.
4. Implementation: Abstract class can provide the implementation of interface. Interface can’t provide the
implementation of abstract class.
5. Inheritance vs Abstraction: A Java interface can be implemented using keyword “implements” and abstract
class can be extended using keyword “extends”.
6. Multiple implementation: An interface can extend another Java interface only, an abstract class can extend
another Java class and implement multiple Java interfaces.
7. Accessibility of Data Members: Members of a Java interface are public by default. A Java abstract class can
have class members like private, protected, etc.

Qasim Ali Page 63


Object Oriented Programming In Java

// Java program to illustrate the


// concept of abstract class
 
import java.io.*;
 
// abstract class
abstract class Shape
{
    // declare fields
    String objectName = " ";
    public abstract double area();
    Shape(String name)
    {
        this.objectName = name;
    }
     
    // declare non-abstract methods
    // it has default implementation
    public void moveTo(int x, int y)
    {
        System.out.println(this.objectName + " " + "has been moved to"
                                   + " x = " + x + " and y = " + y);
    }
     
    // abstract methods which will be
    // implemented by its subclass(es)
    abstract public double area();
    abstract public void draw();
}
 
class Rectangle extends Shape
{
     
    int length, width;
     
    // constructor
    Rectangle(int length, int width, String name)
    {
         
        super(name);
        this.length = length;
        this.width = width;
    }
     
    @Override
    public void draw()
    {
        System.out.println("Rectangle has been drawn ");
    }
     

Qasim Ali Page 64


Object Oriented Programming In Java
    @Override
    public double area()
    {
        return (double)(length*width);
    }
}
 
class Circle extends Shape
{
     
    double pi = 3.14;
    int radius;
     
    //constructor
    Circle(int radius, String name)
    {
         
        super(name);
        this.radius = radius;
    }
     
    @Override
    public void draw()
    {
         
        System.out.println("Circle has been drawn ");
    }
     
    @Override
    public double area()
    {
        return (double)((pi*radius*radius)/2);
    }
}
 
class GFG
{
    public static void main (String[] args)
    {
     
        // creating the Object of Rectangle class
        // and using shape class reference.
        Shape rect = new Rectangle(2,3, "Rectangle");
        System.out.println("Area of rectangle: " + rect.area());
        rect.moveTo(1,2);
         
        System.out.println(" ");
         
        // creating the Objects of circle class
        Shape circle = new Circle(2, "Cicle");
        System.out.println("Area of circle: " + circle.area());
        circle.moveTo(2,4);
     
    }
}
In you don’t have any common code between rectangle and circle then go with interface.
See this…..
// Java program to illustrate the
// concept of interface
import java.io.*;
 
interface Shape
{
    // abstract method
    void draw();
    double area();
}
 

Qasim Ali Page 65


Object Oriented Programming In Java
class Rectangle implements Shape
{
    int length, width;
     
    // constructor
    Rectangle(int length, int width)
    {
        this.length = length;
        this.width = width;
    }
     
    @Override
    public void draw()
    {
        System.out.println("Rectangle has been drawn ");
    }
     
    @Override
    public double area()
    {
        return (double)(length*width);
    }
}
 
class Circle implements Shape
{
     
    double pi = 3.14;
    int radius;
     
    //constructor
    Circle(int radius)
    {
         
        this.radius = radius;
    }
     
    @Override
    public void draw()
    {
        System.out.println("Circle has been drawn ");
    }
     
    @Override
    public double area()
    {
         
        return (double)((pi*radius*radius)/2);
    }
     
}
 
class GFG
{
    public static void main (String[] args)
    {
     
        // creating the Object of Rectangle class
        // and using shape interface reference.
        Shape rect = new Rectangle(2,3);
        System.out.println("Area of rectangle: " + rect.area());
 
        // creating the Objects of circle class
        Shape circle = new Circle(2);
        System.out.println("Area of circle: " + circle.area());
    }
}

When to use what?

Qasim Ali Page 66


Object Oriented Programming In Java
Consider using abstract classes if any of these statements apply to your situation:
 In java application, there are some related classes that need to share some lines of code then you can put these
lines of code within abstract class and this abstract class should be extended by all these related classes.
 You can define non-static or non-final field(s) in abstract class, so that via a method you can access and modify
the state of Object to which they belong.
 You can expect that the classes that extend an abstract class have many common methods or fields, or require
access modifiers other than public (such as protected and private).
Consider using interfaces if any of these statements apply to your situation:
 It is total abstraction, All methods declared within an interface must be implemented by the class(es) that
implements this interface.
 A class can implement more than one interface. It is called multiple inheritance.
 You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.

Polymorphism in Java
Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived
from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means
many forms.

Prerequisite: Overriding in java, Inheritance
 When an overridden method is called through a superclass reference, Java determines which
version(superclass/subclasses) of that method is to be executed based upon the type of the object
being referred to at the time the call occurs. Thus, this determination is made at run time.
 At run-time, it depends on the type of the object being referred to (not the type of the reference
variable) that determines which version of an overridden method will be executed
 A superclass reference variable can refer to a subclass object. This is also known as upcasting. Java
uses this fact to resolve calls to overridden methods at run time.
There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform
polymorphism in java by method overloading and method overriding.
If you overload static method in java, it is the example of compile time polymorphism. Here, we will focus on runtime
polymorphism in java.

Runtime Polymorphism in Java


Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved
at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The determination of the
method to be called is based on the object being referred to by the reference variable.
Let's first understand the upcasting before Runtime Polymorphism.

Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:

1. class A{}  

2. class B extends A{}  

1. A a=new B();//upcasting  
Example of Java Runtime Polymorphism

In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike class and overrides its run()
method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and
subclass method overrides the Parent class method, subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.

Qasim Ali Page 67


Object Oriented Programming In Java
class Bike{  

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

}  

class Splender extends Bike{  

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

public static void main(String args[]){  

Bike b = new Splender();//upcasting  

b.run();  

}  

}  

Java Runtime Polymorphism Example: Shape

class Shape{  

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

}  

class Rectangle extends Shape{  

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

}  

class Circle extends Shape{  

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

}  

class Triangle extends Shape{  

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

}  

class TestPolymorphism2{  

public static void main(String args[]){  

Shape s;  

s=new Rectangle();  

s.draw();  

s=new Circle();  

s.draw();  

s=new Triangle();  

s.draw();  

}  

Qasim Ali Page 68


Object Oriented Programming In Java
}  

Example
class Animal {
public void name() {
System.out.println("This is Animal");
}
public void parentMethod() {
System.out.println("This is method in Animal class.");
}
}
interface Running {
public void run();
}

class Horse extends Animal implements Running {


@Override
public void run() {
System.out.println("Horse is running.");
}

@Override
public void name() {
System.out.println("This is Horse.");
}
}
class TestInvocation {
public void invoke() {
Horse horse = new Horse(); // since it is Horse itself.
Animal animal = new Horse(); // since Horse extends Animal.
Running running = new Horse(); // since Horse implements Running.
Object obj = new Horse(); // All java class is subclass of Object.

// Invoking name() method.


horse.name();
animal.name();

// Invoking run() method.


horse.run();
running.run();

// Invoking parentMethod()
horse.parentMethod();
animal.parentMethod();
}
}

Java Runtime Polymorphism with Data Member

Qasim Ali Page 69


Object Oriented Programming In Java
Method is overridden not the datamembers, so runtime polymorphism can't be achieved by data members.

In the example given below, both the classes have a datamember speedlimit, we are accessing the datamember by the

reference variable of Parent class which refers to the subclass object. Since we are accessing the datamember which is

not overridden, hence it will access the datamember of Parent class always.

Rule: Runtime polymorphism can't be achieved by data members.

class Bike{  

 int speedlimit=90;  

}  

class Honda3 extends Bike{  

 int speedlimit=150;  

  

 public static void main(String args[]){  

  Bike obj=new Honda3();  

  System.out.println(obj.speedlimit);//90  

}  

static binding

When type of the object is determined at compiled time(by the compiler), it is known as static binding.

If there is any private, final or static method in a class, there is static binding.

Example of static binding

class Dog{  

 private void eat(){System.out.println("dog is eating...");}  

 public static void main(String args[]){  

  Dog d1=new Dog();  

  d1.eat();  

 }  

}  

Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding

class Animal{  

 void eat(){System.out.println("animal is eating...");}  

}  

  

Qasim Ali Page 70


Object Oriented Programming In Java
class Dog extends Animal{  

 void eat(){System.out.println("dog is eating...");}  

  

 public static void main(String args[]){  

  Animal a=new Dog();  

  a.eat();  

 }  

}  

Polymorphism Example

package polymorphism;

public abstract class Shape {

private String name;

private double area;

private double peri;

public Shape(String name)

this.name=name;

public void setName(String n)

name=n;

public String getName()

return name;

public void setArea(double a)

if(a>0)

area=a;

else

System.out.println("Invalid area");

public double getarea()

Qasim Ali Page 71


Object Oriented Programming In Java
{

return area;

}public void setPeri(double p)

if(p>0)

peri=p;

else

System.out.println("Invalid perimeter");

public double getPeri()

return peri;

public abstract void calculatePeri();

public abstract void calculateArea();

public abstract void show();

Circle Class (Child)

package polymorphism;

public class Circle extends Shape{

private double radius;

public Circle(String n, double r)

super(n);

radius=r;

public void setRadius(double r)

if(r>0)

radius=r;

else

System.err.println("Invalid Radius");

public double getRadius()

Qasim Ali Page 72


Object Oriented Programming In Java
{

return radius;

public void calculateArea()

setArea(3.145*getRadius()*getRadius());

public void calculatePeri()

setPeri(2*3.145*getRadius());

public void show()

System.out.println("Radius of Circle="+getRadius());

System.out.println("Area of Circle="+getArea());

System.out.println("Perimeter of Circle="+getPeri());

Square Class (Child)

package polymorphism;

public class Square extends Shape {

private int side;

public Square(String n, int s)

super(n);

side=s;

public void setSide(int s)

if(s>0)

side=s;

else

System.err.println("Invalid Side Value");

Qasim Ali Page 73


Object Oriented Programming In Java
public double getSide()

return side;

public void calculateArea()

setArea(getSide()*getSide());

public void calculatePeri()

setPeri(4*getSide());

public void show()

System.out.println("Radius of Square="+getSide());

System.out.println("Area of Square="+getArea());

System.out.println("Perimeter of Square="+getPeri());

Test Shape Class (Class with Main Function)

package polymorphism;

public class TestShape {

public static void main(String[] args) {

Shape sh;

Square s=new Square("Square",10);

Circle c=new Circle("Circle",4.5);

sh=s;

sh.calculateArea();

sh.calculatePeri();

sh.show();

sh=c;

sh.calculateArea();

sh.calculatePeri();

sh.show();

Qasim Ali Page 74


Object Oriented Programming In Java
}

Output:

Radius of Square=10.0

Area of Square=100.0

Perimeter of Square=40.0

Radius of Circle=4.5

Area of Circle=63.68625

Perimeter of Circle=28.305
Wrapper Classes in Java

A Wrapper class is a class whose object wraps or contains a primitive data types. When we create an object to a wrapper
class, it contains a field and in this field, we can store a primitive data types. In other words, we can wrap a primitive value
into a wrapper class object.
Need of Wrapper Classes
1. They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into
a method (because primitive types are passed by value).
2. The classes in java.util package handles only objects and hence wrapper classes help in this case also.
3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types)
and not primitive types.
4. An object is needed to support synchronization in multithreading.

Primitive Data types and their Corresponding Wrapper class

Autoboxing and Unboxing


Autoboxing: Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as
autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc.
Example:
// Java program to demonstrate Autoboxing
 
import java.util.ArrayList;
class Autoboxing

Qasim Ali Page 75


Object Oriented Programming In Java
{
    public static void main(String[] args)
    {
        char ch = 'a';;
 
        // Autoboxing- primitive to Character object conversion
        Character a = ch;
 
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
 
        // Autoboxing because ArrayList stores only objects
        arrayList.add(25);
 
        // printing the values from object
        System.out.println(arrayList.get(0));
    }
}

Unboxing: It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its
corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to
double etc.
Implementation
// Java program to demonstrate Wrapping and UnWrapping
// in Java Classes
class WrappingUnwrapping
{
    public static void main(String args[])
    {
        //  byte data type
        byte a = 1;
 
        // wrapping around Byte object
        Byte byteobj = new Byte(a);
 
        // int data type
        int b = 10;
 
        //wrapping around Integer object
        Integer intobj = new Integer(b);
 
        // float data type
        float c = 18.6f;
 
        // wrapping around Float object
        Float floatobj = new Float(c);
 
        // double data type
        double d = 250.5;
 
        // Wrapping around Double object
        Double doubleobj = new Double(d);
 
        // char data type
        char e='a';
 
        // wrapping around Character object
        Character charobj=e;
 
        //  printing the values from objects
        System.out.println("Values of Wrapper objects (printing as objects)");
        System.out.println("Byte object byteobj:  " + byteobj);
        System.out.println("Integer object intobj:  " + intobj);
        System.out.println("Float object floatobj:  " + floatobj);
        System.out.println("Double object doubleobj:  " + doubleobj);
        System.out.println("Character object charobj:  " + charobj);
 
        // objects to data types (retrieving data types from objects)
        // unwrapping objects to primitive data types
        byte bv = byteobj;
        int iv = intobj;

Qasim Ali Page 76


Object Oriented Programming In Java
        float fv = floatobj;
        double dv = doubleobj;
        char cv = charobj;
 
        // printing the values from data types
        System.out.println("Unwrapped values (printing as data types)");
        System.out.println("byte value, bv: " + bv);
        System.out.println("int value, iv: " + iv);
        System.out.println("float value, fv: " + fv);
        System.out.println("double value, dv: " + dv);
        System.out.println("char value, cv: " + cv);
    }
}

What is exception
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
What is exception handling
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.

Advantage of Exception Handling


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. Let's take a scenario:

1. statement 1;  

2. statement 2;  

3. statement 3;  

4. statement 4;  

5. statement 5;//exception occurs  

6. statement 6;  

7. statement 7;  

8. statement 8;  

9. statement 9;  

10. statement 10;  
Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of the code will not be
executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest of the statement will be executed. That
is why we use exception handling in java.

Qasim Ali Page 77


Object Oriented Programming In Java

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
Difference between checked and unchecked exceptions

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.

Qasim Ali Page 78


Object Oriented Programming In Java
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.

Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios where exceptions may occur


There are given some scenarios where unchecked exceptions can occur. They are as follows:

Scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException  

Scenario where NullPointerException occurs


If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.

1. String s=null;  

2. System.out.println(s.length());//NullPointerException  

Scenario where NumberFormatException occurs


The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have
characters, converting this variable into digit will occur NumberFormatException.

1. String s="abc";  

2. int i=Integer.parseInt(s);//NumberFormatException  

Scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:

1. int a[]=new int[5];  

2. a[10]=50; //ArrayIndexOutOfBoundsException  

Java Exception Handling Keywords


There are 5 keywords used in java exception handling.

1. try

2. catch

3. finally

4. throw

5. throws

Java try block


Java try block is used to enclose the code that might throw an exception. It must be used within the method.
Java try block must be followed by either catch or finally block.
Syntax of java try-catch

try{  

//code that may throw exception  

Qasim Ali Page 79


Object Oriented Programming In Java
}catch(Exception_class_Name ref){}  
Syntax of try-finally block

try{  

//code that may throw exception  

}finally{}  

Java catch block

Java catch block is used to handle the Exception. It must be used after the try block only. You can use multiple catch block with

a single try. Problem without exception handling. Let's try to understand the problem if we don't use try-catch block.

public class Testtrycatch1{  

  public static void main(String args[]){  

      int data=50/0;//may throw exception  

      System.out.println("rest of the code...");  

}  

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

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.
Solution by exception handling
Let's see the solution of above problem by java try-catch block.

public class Testtrycatch2{  

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

}  

}  

Qasim Ali Page 80


Object Oriented Programming In Java

Java Multi catch block

public class TestMultipleCatchBlock{  

  public static void main(String args[]){  

   try{  

    int a[]=new int[5];  

    a[5]=30/0;  

   }  

   catch(ArithmeticException e){System.out.println("task1 is completed");}  

   catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}  

   catch(Exception e){System.out.println("common task completed");}  

  

   System.out.println("rest of the code...");  

 }  

Qasim Ali Page 81


Object Oriented Programming In Java

Rule: At a time only one Exception is occured and at a time only one catch block is executed.
Rule: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must
come before catch for Exception .

Java Exception propagation

An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous

method,If not caught there, the exception again drops down to the previous method, and so on until they are caught or

until they reach the very bottom of the call stack.This is called exception propagation.

Rule: By default Unchecked Exceptions are forwarded in calling chain (propagated).

Program of Exception Propagation

class TestExceptionPropagation1{  

  void m(){  

    int data=50/0;  

  }  

  void n(){  

    m();  

  }  

  void p(){  

   try{  

    n();  

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

  }  

  public static void main(String args[]){  

   TestExceptionPropagation1 obj=new TestExceptionPropagation1();  

   obj.p();  

   System.out.println("normal flow...");  

  }  

}  
Output:exception handled
normal flow...

Qasim Ali Page 82


Object Oriented Programming In Java

In the above example exception occurs in m() method where it is not handled,so it is propagated to previous n() method
where it is not handled, again it is propagated to p() method where exception is handled.
Exception can be handled in any method in call stack either in main() method,p() method,n() method or m() method.

Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).

class TestExceptionPropagation2{  

  void m(){  

    throw new java.io.IOException("device error");//checked exception  

  }  

  void n(){  

    m();  

  }  

  void p(){  

   try{  

    n();  

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

  }  

  public static void main(String args[]){  

   TestExceptionPropagation2 obj=new TestExceptionPropagation2();  

   obj.p();  

   System.out.println("normal flow");  

  }  

}  
1. Output:Compile Time Error

  Java finally block 

Qasim Ali Page 83


Object Oriented Programming In Java
It is a block that is used to execute important code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.

Note: If you don't handle exception, before terminating the program, JVM executes finally block(if any).

Why use java finally

o Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.

Usage of Java finally


Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.

class TestFinallyBlock{  

  public static void main(String args[]){  

  try{  

   int data=25/5;  

   System.out.println(data);  

  }  

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

  finally{System.out.println("finally block is always executed");}  

  System.out.println("rest of the code...");  

  }  

}  
Output:5
finally block is always executed
rest of the code...

Case 2
Let's see the java finally example where exception occurs and not handled.

class TestFinallyBlock1{  

Qasim Ali Page 84


Object Oriented Programming In Java
  public static void main(String args[]){  

  try{  

   int data=25/0;  

   System.out.println(data);  

  }  

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

  finally{System.out.println("finally block is always executed");}  

  System.out.println("rest of the code...");  

  }  

}  

Output:finally block is always executed


Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let's see the java finally example where exception occurs and handled.

public class TestFinallyBlock2{  

  public static void main(String args[]){  

  try{  

   int data=25/0;  

   System.out.println(data);  

  }  

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

  finally{System.out.println("finally block is always executed");}  

  System.out.println("rest of the code...");  

  }  

}  

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...

Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal
error that causes the process to abort).

Java throw keyword


The Java throw keyword is used to explicitly throw an exception.
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.
The syntax of java throw keyword is given below.

Qasim Ali Page 85


Object Oriented Programming In Java
1. throw exception;  
Let's see the example of throw IOException.

1. throw new IOException("sorry device error”);  

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.

public class TestThrow1{  

   static void validate(int age){  

     if(age<18)  

      throw new ArithmeticException("not valid");  

     else  

      System.out.println("welcome to vote");  

   }  

   public static void main(String args[]){  

      validate(13);  

      System.out.println("rest of the code...");  

  }  

}  

Output:
Exception in thread main java.lang.ArithmeticException:not valid

Java throws keyword


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.

Syntax of java throws

1. return_type method_name() throws exception_class_name{  

2. //method code  

3. }  

Which exception should be declared


Ans) checked exception only, because:

o unchecked Exception: under your control so correct your code.

o error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError or

StackOverflowError.

Advantage of Java throws keyword


Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.

Qasim Ali Page 86


Object Oriented Programming In Java
Java throws example
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  

  }  

  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
normal flow...

Rule: If you are calling a method that declares an exception, you must either caught or declare the exception.

There are two cases:

1. Case1:You caught the exception i.e. handle the exception using try/catch.

2. Case2:You declare the exception i.e. specifying throws with the method.

Case1: You handle the exception

o In case you handle the exception, the code will be executed fine whether exception occurs during the program

or not.

import java.io.*;  

class M{  

 void method()throws IOException{  

Qasim Ali Page 87


Object Oriented Programming In Java
  throw new IOException("device error");  

 }  

}  

public class Testthrows2{  

   public static void main(String args[]){  

    try{  

     M m=new M();  

     m.method();  

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

    System.out.println("normal flow...");  

  }  

}  
Output:exception handled
normal flow...

Case2: You declare the exception

o A)In case you declare the exception, if exception does not occur, the code will be executed fine.

o B)In case you declare the exception if exception occures, an exception will be thrown at runtime because throws

does not handle the exception.


A)Program if exception does not occur

import java.io.*;  

class M{  

 void method()throws IOException{  

  System.out.println("device operation performed");  

 }  

}  

class Testthrows3{  

   public static void main(String args[])throws IOException{//declare exception  

     M m=new M();  

     m.method();  

  

    System.out.println("normal flow...");  

  }  

}  
1. Output:device operation performed
2. normal flow...
B)Program if exception occurs

Qasim Ali Page 88


Object Oriented Programming In Java
import java.io.*;  

class M{  

 void method()throws IOException{  

  throw new IOException("device error");  

 }  

}  

class Testthrows4{  

   public static void main(String args[])throws IOException{//declare exception  

     M m=new M();  

     m.method();  

  

    System.out.println("normal flow...");  

  }  

}  
Output:Runtime Exception
Que) Can we rethrow an exception?
Yes, by throwing same exception in catch block.

No. Throw throws

1 Java throw keyword is used Java throws keyword is used to

) to explicitly throw an declare an exception.

exception.

2 Checked exception cannot Checked exception can be propagated

) be propagated using throw with throws.

only.

3 Throw is followed by an Throws is followed by class.

) instance.

4 Throw is used within the Throws is used with the method

) method. signature.

5 You cannot throw multiple You can declare multiple exceptions

) exceptions. e.g.

public void method()throws

Qasim Ali Page 89


Object Oriented Programming In Java

IOException,SQLException.

ExceptionHandling with MethodOverriding in Java

There are many rules if we talk about methodoverriding with exception handling. The Rules are as follows:

o If the superclass method does not declare an exception

o If the superclass method does not declare an exception, subclass overridden method cannot

declare the checked exception but it can declare unchecked exception.

o If the superclass method declares an exception

o If the superclass method declares an exception, subclass overridden method can declare same,

subclass exception or no exception but cannot declare parent exception.

If the superclass method does not declare an exception

1) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare the
checked exception.

import java.io.*;  

class Parent{  

  void msg(){System.out.println("parent");}  

}  

  

class TestExceptionChild extends Parent{  

  void msg()throws IOException{  

    System.out.println("TestExceptionChild");  

  }  

  public static void main(String args[]){  

   Parent p=new TestExceptionChild();  

   p.msg();  

  }  

}  
Output:Compile Time Error

2) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare the
checked exception but can declare unchecked exception.

import java.io.*;  

class Parent{  

  void msg(){System.out.println("parent");}  

Qasim Ali Page 90


Object Oriented Programming In Java
}  

  class TestExceptionChild1 extends Parent{  

  void msg()throws ArithmeticException{  

    System.out.println("child");  

  }  

  public static void main(String args[]){  

   Parent p=new TestExceptionChild1();  

   p.msg();  

  }  

}  
Output:child

If the superclass method declares an exception

1) Rule: If the superclass method declares an exception, subclass overridden method can declare same, subclass
exception or no exception but cannot declare parent exception.

Example in case subclass overridden method declares parent exception

import java.io.*;  

class Parent{  

  void msg()throws ArithmeticException{System.out.println("parent");}  

}    

class TestExceptionChild2 extends Parent{  

  void msg()throws Exception{System.out.println("child");}  

  public static void main(String args[]){  

   Parent p=new TestExceptionChild2();  

   try{  

   p.msg();  

   }catch(Exception e){}  

  }  

}  
Output:Compile Time Error

Example in case subclass overridden method declares same exception

import java.io.*;  

class Parent{  

  void msg()throws Exception{System.out.println("parent");}  

}  

  class TestExceptionChild3 extends Parent{  

Qasim Ali Page 91


Object Oriented Programming In Java
  void msg()throws Exception{System.out.println("child");}  

  public static void main(String args[]){  

   Parent p=new TestExceptionChild3();  

   try{  

   p.msg();  

   }catch(Exception e){}  

  }  

}  
Output:child

Example in case subclass overridden method declares subclass exception

import java.io.*;  

class Parent{  

  void msg()throws Exception{System.out.println("parent");}  

}  

class TestExceptionChild4 extends Parent{  

  void msg()throws ArithmeticException{System.out.println("child");}  

  

  public static void main(String args[]){  

   Parent p=new TestExceptionChild4();  

   try{  

   p.msg();  

   }catch(Exception e){}  

  }  

}  
Output:child

Example in case subclass overridden method declares no exception

import java.io.*;  

class Parent{  

  void msg()throws Exception{System.out.println("parent");}  

}  

  class TestExceptionChild5 extends Parent{  

  void msg(){System.out.println("child");}  

  public static void main(String args[]){  

   Parent p=new TestExceptionChild5();  

   try{  

Qasim Ali Page 92


Object Oriented Programming In Java
   p.msg();  

   }catch(Exception e){}  

  }  

}  
Output:child

Java I/O Tutorial


Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes required for input
and output operations.
We can perform file handling in java by Java I/O API.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it is like a stream of
water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and error message to the console.

1. System.out.println("simple message");  

2. System.err.println("error message");  
Let's see the code to get input from console.

1. int i=System.in.read();//returns ASCII code of 1st character  

2. System.out.println((char)i);//will print the character  
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:

OutputStream
Java application uses an output stream to write data to a destination, it may be a file, an array, peripheral device or socket.

InputStream
Java application uses an input stream to read data from a source, it may be a file, an array, peripheral device or socket.
Let's understand working of Java OutputStream and InputStream by the figure given below.

OutputStream class

Qasim Ali Page 93


Object Oriented Programming In Java
OutputStream class is an abstract class. It is the super class of all classes representing an output stream of bytes. An output
stream accepts output bytes and sends them to some sink.
Useful methods of OutputStream

Method Description

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

IOException

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

IOException stream.

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

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

OutputStream Hierarchy

InputStream class
InputStream class is an abstract class. It is the super class of all classes representing an input stream of bytes.
Useful methods of InputStream

Method Description

1) public abstract int read()throws reads the next byte of data from the input stream. It

IOException returns -1 at the end of file.

Qasim Ali Page 94


Object Oriented Programming In Java

2) public int available()throws returns an estimate of the number of bytes that can

IOException be read from the current input stream.

3) public void close()throws IOException is used to close the current input stream.

InputStream Hierarchy

Java FileOutputStream Class


Java FileOutputStream is an output stream used for writing data to a file.
If you have to write primitive values into a file, use FileOutputStream class. You can write byte-oriented as well as
character-oriented data through FileOutputStream class. But, for character-oriented data, it is preferred to use FileWriter
than FileOutputStream.
FileOutputStream class declaration

Let's see the declaration for Java.io.FileOutputStream class:

1. public class FileOutputStream extends OutputStream  
FileOutputStream class methods

Method Description

protected void finalize() It is sued to clean up the connection with the file output stream.

void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file

output stream.

void write(byte[] ary, int off, It is used to write len bytes from the byte array starting at

int len) offset off to the file output stream.

void write(int b) It is used to write the specified byte to the file output stream.

Qasim Ali Page 95


Object Oriented Programming In Java

FileChannel getChannel() It is used to return the file channel object associated with the file

output stream.

FileDescriptor getFD() It is used to return the file descriptor associated with the stream.

void close() It is used to closes the file output stream.

Java FileOutputStream Example 1: write byte

import java.io.FileOutputStream;  

public class FileOutputStreamExample {  

    public static void main(String args[]){    

           try{    

             FileOutputStream fout=new FileOutputStream("D:\\testout.txt");    

             fout.write(65);    

             fout.close();    

             System.out.println("success...");    

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

      }    

}  
Output:
Success...
The content of a text file testout.txt is set with the data A.
testout.txt
A
Java FileOutputStream example 2: write string

import java.io.FileOutputStream;  

public class FileOutputStreamExample {  

    public static void main(String args[]){    

           try{    

             FileOutputStream fout=new FileOutputStream("D:\\testout.txt");    

             String s="Welcome to javaTpoint.";    

             byte b[]=s.getBytes();//converting string into byte array    

             fout.write(b);    

             fout.close();    

             System.out.println("success...");    

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

      }    

Qasim Ali Page 96


Object Oriented Programming In Java
}  
Output:
Success...
The content of a text file testout.txt is set with the data Welcome to javaTpoint.
testout.txt
Welcome to javaTpoint.

Java FileInputStream Class


Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes)
such as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is
recommended to use FileReader class.
Java FileInputStream class declaration
Let's see the declaration for java.io.FileInputStream class:

1. public class FileInputStream extends InputStream  
Java FileInputStream class methods

Method Description

int available() It is used to return the estimated number of bytes that can be read from

the input stream.

int read() It is used to read the byte of data from the input stream.

int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.

int read(byte[] b, int off, It is used to read up to len bytes of data from the input stream.

int len)

long skip(long x) It is used to skip over and discards x bytes of data from the input

stream.

FileChannel It is used to return the unique FileChannel object associated with the

getChannel() file input stream.

FileDescriptor getFD() It is used to return the FileDescriptor object.

protected void finalize() It is used to ensure that the close method is call when there is no more

reference to the file input stream.

void close() It is used to closes the stream.

Java FileInputStream example 1: read single character

import java.io.FileInputStream;  

Qasim Ali Page 97


Object Oriented Programming In Java
public class DataStreamExample {  

     public static void main(String args[]){    

          try{    

            FileInputStream fin=new FileInputStream("D:\\testout.txt");    

            int i=fin.read();  

            System.out.print((char)i);    

  

            fin.close();    

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

         }    

        }  
Note: Before running the code, a text file named as "testout.txt" is required to be created. In this file, we are having
following content:
Welcome to javatpoint.
After executing the above program, you will get a single character from the file which is 87 (in byte form). To see the text,
you need to convert it into character.
Output:
W

Java FileInputStream example 2: read all characters

package com.javatpoint;  

  

import java.io.FileInputStream;  

public class DataStreamExample {  

     public static void main(String args[]){    

          try{    

            FileInputStream fin=new FileInputStream("D:\\testout.txt");    

            int i=0;    

            while((i=fin.read())!=-1){    

             System.out.print((char)i);    

            }    

            fin.close();    

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

         }    

        }  
Output:
Welcome to javaTpoint

Counting Total Characters of File


import java.io.*;
public class Test {

Qasim Ali Page 98


Object Oriented Programming In Java
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("xyz.txt");
int i=0;
int count=0;
while((i=fin.read())!=-1)
{
System.out.print((char)i);
count++;
}
System.out.println();
System.out.println("Total No of Characters in File:"+count);

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

Character Matching From File’s Characters


import java.io.*;
public class Test {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("xyz.txt");
int i=0;
char ch='t';
int j=0;
while((i=fin.read())!=-1)
{
if(ch==((char)i))
{
break;
}
j++;
}
if(i==-1)
System.out.println("Character No Matched");
else
System.out.println(ch+" "
+ "Matched at index No:"+j);

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

}
Copy Characters from one file to another file
import java.io.*;
public class Test {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("xyz.txt");
FileOutputStream fout=new FileOutputStream("abc.txt");
int i=0;
while((i=fin.read())!=-1)
{
System.out.print((char)i);
fout.write(i);
}
}catch(Exception e){System.out.println(e);}
}

Qasim Ali Page 99


Object Oriented Programming In Java
}

Java BufferedOutputStream Class


Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to store data. It adds more
efficiency than to write data directly into a stream. So, it makes the performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the syntax for adding the buffer in
an OutputStream:

1. OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\testout.txt"));  
Java BufferedOutputStream class declaration
Let's see the declaration for Java.io.BufferedOutputStream class:

1. public class BufferedOutputStream extends FilterOutputStream  
Java BufferedOutputStream class constructors

Constructor Description

BufferedOutputStream(OutputStream os) It creates the new buffered output stream which is

used for writing the data to the specified output

stream.

BufferedOutputStream(OutputStream os, It creates the new buffered output stream which is

int size) used for writing the data to the specified output

stream with a specified buffer size.

Java BufferedOutputStream class methods

Method Description

void write(int b) It writes the specified byte to the buffered output stream.

void write(byte[] b, int It write the bytes from the specified byte-input stream into a specified

off, int len) byte array, starting with the given offset

void flush() It flushes the buffered output stream.

Example of BufferedOutputStream class:


In this example, we are writing the textual information in the BufferedOutputStream object which is connected to the
FileOutputStream object. The flush() flushes the data of one stream and send it into another. It is required if you have
connected the one stream with another.

package com.javatpoint;  

import java.io.*;  

public class BufferedOutputStreamExample{    

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

     FileOutputStream fout=new FileOutputStream("D:\\testout.txt");    

Qasim Ali Page 100


Object Oriented Programming In Java
     BufferedOutputStream bout=new BufferedOutputStream(fout);    

     String s="Welcome to javaTpoint.";    

     byte b[]=s.getBytes();    

     bout.write(b);    

     bout.flush();    

     bout.close();    

     fout.close();    

     System.out.println("success");    

}    

}  
Output:
Success
testout.txt
Welcome to javaTpoint.

Java BufferedInputStream Class


Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the
performance fast.
The important points about BufferedInputStream are:

o When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the

contained input stream, many bytes at a time.

o When a BufferedInputStream is created, an internal buffer array is created.

Java BufferedInputStream class declaration


Let's see the declaration for Java.io.BufferedInputStream class:

1. public class BufferedInputStream extends FilterInputStream  
Java BufferedInputStream class constructors

Constructor Description

BufferedInputStream(InputStream IS) It creates the BufferedInputStream and saves it

argument, the input stream IS, for later use.

BufferedInputStream(InputStream IS, It creates the BufferedInputStream with a specified

int size) buffer size and saves it argument, the input stream IS,

for later use.

Java BufferedInputStream class methods

Method Description

int available() It returns an estimate number of bytes that can be read from the input stream

without blocking by the next invocation method for the input stream.

Qasim Ali Page 101


Object Oriented Programming In Java

int read() It read the next byte of data from the input stream.

int read(byte[] b, int It read the bytes from the specified byte-input stream into a specified byte

off, int ln) array, starting with the given offset.

void close() It closes the input stream and releases any of the system resources associated

with the stream.

void reset() It repositions the stream at a position the mark method was last called on

this input stream.

void mark(int It sees the general contract of the mark method for the input stream.

readlimit)

long skip(long x) It skips over and discards x bytes of data from the input stream.

boolean It tests for the input stream to support the mark and reset methods.

markSupported()

Example of Java BufferedInputStream


Let's see the simple example to read data of file using BufferedInputStream:

package com.javatpoint;  

import java.io.*;  

public class BufferedInputStreamExample{    

 public static void main(String args[]){    

  try{    

    FileInputStream fin=new FileInputStream("D:\\testout.txt");    

    BufferedInputStream bin=new BufferedInputStream(fin);    

    int i;    

    while((i=bin.read())!=-1){    

     System.out.print((char)i);    

    }    

    bin.close();    

    fin.close();    

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

 }    

Qasim Ali Page 102


Object Oriented Programming In Java
}  
Here, we are assuming that you have following data in "testout.txt" file:
javaTpoint
Output:
javaTpoint

Java SequenceInputStream Class


Java SequenceInputStream class is used to read data from multiple streams. It reads data sequentially (one by one).
Java SequenceInputStream Class declaration
Let's see the declaration for Java.io.SequenceInputStream class:

1. public class SequenceInputStream extends InputStream  
Constructors of SequenceInputStream class

Constructor Description

SequenceInputStream(InputStream s1, creates a new input stream by reading the data of

InputStream s2) two input stream in order, first s1 and then s2.

SequenceInputStream(Enumeration e) creates a new input stream by reading the data of

an enumeration whose type is InputStream.

Methods of SequenceInputStream class

Method Description

int read() It is used to read the next byte of data from the input stream.

int read(byte[] ary, int off, It is used to read len bytes of data from the input stream into the

int len) array of bytes.

int available() It is used to return the maximum number of byte that can be read

from an input stream.

void close() It is used to close the input stream.

Java SequenceInputStream Example


In this example, we are printing the data of two files testin.txt and testout.txt.

package com.javatpoint;  

import java.io.*;  

class InputStreamExample {    

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

   FileInputStream input1=new FileInputStream("D:\\testin.txt");    

   FileInputStream input2=new FileInputStream("D:\\testout.txt");    

Qasim Ali Page 103


Object Oriented Programming In Java
   SequenceInputStream inst=new SequenceInputStream(input1, input2);    

   int j;    

   while((j=inst.read())!=-1){    

    System.out.print((char)j);    

   }    

   inst.close();    

   input1.close();    

   input2.close();    

  }    

}    
Here, we are assuming that you have two files: testin.txt and testout.txt which have following information:
testin.txt:
Welcome to Java IO Programming.
testout.txt:
It is the example of Java SequenceInputStream class.
After executing the program, you will get following output:
Output:
Welcome to Java IO Programming. It is the example of Java SequenceInputStream class.
Example that reads the data from two files and writes into another file
In this example, we are writing the data of two files testin1.txt and testin2.txt into another file named testout.txt.

package com.javatpoint;  

import java.io.*;    

class Input1{    

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

   FileInputStream fin1=new FileInputStream("D:\\testin1.txt");    

   FileInputStream fin2=new FileInputStream("D:\\testin2.txt");    

   FileOutputStream fout=new FileOutputStream("D:\\testout.txt");      

   SequenceInputStream sis=new SequenceInputStream(fin1,fin2);    

   int i;    

   while((i=sis.read())!=-1)    

   {    

     fout.write(i);        

   }    

   sis.close();    

   fout.close();      

   fin1.close();      

   fin2.close();       

   System.out.println("Success..");  

  }    

Qasim Ali Page 104


Object Oriented Programming In Java
}    
Output:
Succeess...
testout.txt:
Welcome to Java IO Programming. It is the example of Java SequenceInputStream class.  
SequenceInputStream example that reads data using enumeration
If we need to read the data from more than two files, we need to use Enumeration. Enumeration object can be obtained by
calling elements() method of the Vector class. Let's see the simple example where we are reading the data from 4 files:
a.txt, b.txt, c.txt and d.txt.

package com.javatpoint;  

import java.io.*;    

import java.util.*;    

class Input2{    

public static void main(String args[])throws IOException{    

//creating the FileInputStream objects for all the files    

FileInputStream fin=new FileInputStream("D:\\a.txt");    

FileInputStream fin2=new FileInputStream("D:\\b.txt");    

FileInputStream fin3=new FileInputStream("D:\\c.txt");    

FileInputStream fin4=new FileInputStream("D:\\d.txt");    

//creating Vector object to all the stream    

Vector v=new Vector();    

v.add(fin);    

v.add(fin2);    

v.add(fin3);    

v.add(fin4);              

//creating enumeration object by calling the elements method    

Enumeration e=v.elements();      

//passing the enumeration object in the constructor    

SequenceInputStream bin=new SequenceInputStream(e);    

int i=0;      

while((i=bin.read())!=-1){    

System.out.print((char)i);    

}     

bin.close();    

fin.close();    

fin2.close();    

}    

}    

Qasim Ali Page 105


Object Oriented Programming In Java
The a.txt, b.txt, c.txt and d.txt have following information:
a.txt:
Welcome
b.txt:
to
c.txt:
java
d.txt:
programming
Output:
Welcometojavaprogramming

Java FileWriter Class


Java FileWriter class is used to write character-oriented data to a file. It is character-oriented class which is used for file
handling in java.
Unlike FileOutputStream class, you don't need to convert string into byte array because it provides method to write string
directly.
Java FileWriter class declaration
Let's see the declaration for Java.io.FileWriter class:

1. public class FileWriter extends OutputStreamWriter  
Constructors of FileWriter class

Constructor Description

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

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

Methods of FileWriter class

Method Description

void write(String text) It is used to write the string into FileWriter.

void write(char c) It is used to write the char into FileWriter.

void write(char[] c) It is used to write char array into FileWriter.

void flush() It is used to flushes the data of FileWriter.

void close() It is used to close the FileWriter.

Java FileWriter Example


In this example, we are writing the data in the file testout.txt using Java FileWriter class.

package com.javatpoint;  

import java.io.FileWriter;  

public class FileWriterExample {  

    public static void main(String args[]){    

         try{    

Qasim Ali Page 106


Object Oriented Programming In Java
           FileWriter fw=new FileWriter("D:\\testout.txt");    

           fw.write("Welcome to javaTpoint.");    

           fw.close();    

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

          System.out.println("Success...");    

     }    

}  
Output:
Success...
testout.txt:
Welcome to javaTpoint.
Java FileReader Class
Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.
It is character-oriented class which is used for file handling in java.
Java FileReader class declaration
Let's see the declaration for Java.io.FileReader class:

1. public class FileReader extends InputStreamReader  
Constructors of FileReader class

Constructor Description

FileReader(String It gets filename in string. It opens the given file in read mode. If file

file) doesn't exist, it throws FileNotFoundException.

FileReader(File It gets filename in file instance. It opens the given file in read mode. If

file) file doesn't exist, it throws FileNotFoundException.

Methods of FileReader class

Method Description

int read() It is used to return a character in ASCII form. It returns -1 at the end of file.

void close() It is used to close the FileReader class.

Java FileReader Example


In this example, we are reading the data from the text file testout.txt using Java FileReader class.

package com.javatpoint;  

import java.io.FileReader;  

public class FileReaderExample {  

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

          FileReader fr=new FileReader("D:\\testout.txt");    

          int i;    

Qasim Ali Page 107


Object Oriented Programming In Java
          while((i=fr.read())!=-1)    

          System.out.print((char)i);    

          fr.close();    

    }    

}    
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to javaTpoint.
Output:
Welcome to javaTpoint.

Java BufferedWriter Class


Java BufferedWriter class is used to provide buffering for Writer instances. It makes the performance fast. It inherits Writer
class. The buffering characters are used for providing the efficient writing of single arrays, characters, and strings.
Class declaration
Let's see the declaration for Java.io.BufferedWriter class:

1. public class BufferedWriter extends Writer  
Class constructors

Constructor Description

BufferedWriter(Writer wrt) It is used to create a buffered character output stream that uses

the default size for an output buffer.

BufferedWriter(Writer wrt, int It is used to create a buffered character output stream that uses

size) the specified size for an output buffer.

Class methods

Method Description

void newLine() It is used to add a new line by writing a line separator.

void write(int c) It is used to write a single character.

void write(char[] It is used to write a portion of an array of characters.

cbuf, int off, int len)

void write(String s, It is used to write a portion of a string.

int off, int len)

void flush() It is used to flushes the input stream.

void close() It is used to closes the input stream

Qasim Ali Page 108


Object Oriented Programming In Java
Example of Java BufferedWriter
Let's see the simple example of writing the data to a text file testout.txt using Java BufferedWriter.

package com.javatpoint;  

import java.io.*;  

public class BufferedWriterExample {  

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

    FileWriter writer = new FileWriter("D:\\testout.txt");  

    BufferedWriter buffer = new BufferedWriter(writer);  

    buffer.write("Welcome to javaTpoint.");  

    buffer.close();  

    System.out.println("Success");  

    }  

}  
Output:
success
testout.txt:
Welcome to javaTpoint.

Java BufferedReader Class


Java BufferedReader class is used to read the text from a character-based input stream. It can be used to read data line by
line by readLine() method. It makes the performance fast. It inherits Reader class.
Java BufferedReader class declaration
Let's see the declaration for Java.io.BufferedReader class:

1. public class BufferedReader extends Reader  
Java BufferedReader class constructors

Constructor Description

BufferedReader(Reader rd) It is used to create a buffered character input stream that uses

the default size for an input buffer.

BufferedReader(Reader rd, int It is used to create a buffered character input stream that uses

size) the specified size for an input buffer.

Java BufferedReader class methods

Method Description

int read() It is used for reading a single character.

int read(char[] cbuf, int off, It is used for reading characters into a portion of an array.

int len)

Qasim Ali Page 109


Object Oriented Programming In Java

boolean markSupported() It is used to test the input stream support for the mark and reset

method.

String readLine() It is used for reading a line of text.

boolean ready() It is used to test whether the input stream is ready to be read.

long skip(long n) It is used for skipping the characters.

void reset() It repositions the stream at a position the mark method was last called

on this input stream.

void mark(int It is used for marking the present position in a stream.

readAheadLimit)

void close() It closes the input stream and releases any of the system resources

associated with the stream.

Java BufferedReader Example


In this example, we are reading the data from the text file testout.txt using Java BufferedReader class.

package com.javatpoint;  

import java.io.*;  

public class BufferedReaderExample {  

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

          FileReader fr=new FileReader("D:\\testout.txt");    

          BufferedReader br=new BufferedReader(fr);    

   int i;    

          while((i=br.read())!=-1){  

          System.out.print((char)i);  

          }  

          br.close();    

          fr.close();    

    }    

}    
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to javaTpoint.
Output:
Welcome to javaTpoint.
Reading data from console by InputStreamReader and BufferedReader

Qasim Ali Page 110


Object Oriented Programming In Java
In this example, we are connecting the BufferedReader stream with the InputStreamReader stream for reading the line by
line data from the keyboard.

package com.javatpoint;  

import java.io.*;  

public class BufferedReaderExample{    

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

    InputStreamReader r=new InputStreamReader(System.in);    

    BufferedReader br=new BufferedReader(r);            

    System.out.println("Enter your name");    

    String name=br.readLine();    

    System.out.println("Welcome "+name);    

}    

}  
Output:
Enter your name
Nakul Jain
Welcome Nakul Jain

Another example of reading data from console until user writes stop
In this example, we are reading and printing the data until the user prints stop.

package com.javatpoint;  

import java.io.*;  

public class BufferedReaderExample{    

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

     InputStreamReader r=new InputStreamReader(System.in);    

     BufferedReader br=new BufferedReader(r);           

     String name="";    

     while(!name.equals("stop")){    

      System.out.println("Enter data: ");    

Qasim Ali Page 111


Object Oriented Programming In Java
      name=br.readLine();    

      System.out.println("data is: "+name);    

     }              

    br.close();    

    r.close();    

    }    

    }  
Output:
Enter data: Nakul
data is: Nakul
Enter data: 12
data is: 12
Enter data: stop
data is: stop
Java DataOutputStream Class
Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-
independent way.
Java application generally uses the data output stream to write data that can later be read by a data input stream.
Java DataOutputStream class declaration
Let's see the declaration for java.io.DataOutputStream class:
1. public class DataOutputStream extends FilterOutputStream implements DataOutput  
Java DataOutputStream class methods

Method Description

int size() It is used to return the number of bytes written to the data

output stream.

void write(int b) It is used to write the specified byte to the underlying output

stream.

void write(byte[] b, int off, int It is used to write len bytes of data to the output stream.

len)

void writeBoolean(boolean v) It is used to write Boolean to the output stream as a 1-byte

value.

void writeChar(int v) It is used to write char to the output stream as a 2-byte value.

void writeChars(String s) It is used to write string to the output stream as a sequence of

characters.

void writeByte(int v) It is used to write a byte to the output stream as a 1-byte value.

Qasim Ali Page 112


Object Oriented Programming In Java

void writeBytes(String s) It is used to write string to the output stream as a sequence of

bytes.

void writeInt(int v) It is used to write an int to the output stream

void writeShort(int v) It is used to write a short to the output stream.

void writeShort(int v) It is used to write a short to the output stream.

void writeLong(long v) It is used to write a long to the output stream.

void writeUTF(String str) It is used to write a string to the output stream using UTF-8

encoding in portable manner.

void flush() It is used to flushes the data output stream.

Example of DataOutputStream class


In this example, we are writing the data to a text file testout.txt using DataOutputStream class.
1. package com.javatpoint;  
2.   
3. import java.io.*;  
4. public class OutputExample {  
5.     public static void main(String[] args) throws IOException {  
6.         FileOutputStream file = new FileOutputStream(D:\\testout.txt);  
7.         DataOutputStream data = new DataOutputStream(file);  
8.         data.writeInt(65);  
9.         data.flush();  
10.         data.close();  
11.         System.out.println("Succcess...");  
12.     }  
13. }  
Java DataInputStream Class
Java DataInputStream class allows an application to read primitive data from the input stream in a machine-independent
way.
Java application generally uses the data output stream to write data that can later be read by a data input stream.
Java DataInputStream class declaration
Let's see the declaration for java.io.DataInputStream class:
1. public class DataInputStream extends FilterInputStream implements DataInput  
Java DataInputStream class Methods

Method Description

int read(byte[] b) It is used to read the number of bytes from the input stream.

Qasim Ali Page 113


Object Oriented Programming In Java

int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream.

int readInt() It is used to read input bytes and return an int value.

byte readByte() It is used to read and return the one input byte.

char readChar() It is used to read two input bytes and returns a char value.

double readDouble() It is used to read eight input bytes and returns a double value.

boolean readBoolean() It is used to read one input byte and return true if byte is non

zero, false if byte is zero.

int skipBytes(int x) It is used to skip over x bytes of data from the input stream.

String readUTF() It is used to read a string that has been encoded using the UTF-8

format.

void readFully(byte[] b) It is used to read bytes from the input stream and store them into

the buffer array.

void readFully(byte[] b, int off, It is used to read len bytes from the input stream.

int len)

Example of DataInputStream class


In this example, we are reading the data from the file testout.txt file.
1. package com.javatpoint;  
2. import java.io.*;    
3. public class DataStreamExample {  
4.   public static void main(String[] args) throws IOException {  
5.     InputStream input = new FileInputStream("D:\\testout.txt");  
6.     DataInputStream inst = new DataInputStream(input);  
7.     int count = input.available();  
8.     byte[] ary = new byte[count];  
9.     inst.read(ary);  
10.     for (byte bt : ary) {  
11.       char k = (char) bt;  
12.       System.out.print(k+"-");  
13.     }  
14.   }  
15. }  

Qasim Ali Page 114


Object Oriented Programming In Java

Java PrintStream Class


The PrintStream class provides methods to write data to another stream. The PrintStream class automatically flushes the
data so there is no need to call flush() method. Moreover, its methods don't throw IOException.
Class declaration
Let's see the declaration for Java.io.PrintStream class:

1. public class PrintStream extends FilterOutputStream implements Closeable. Appendable   
Methods of PrintStream class

Method Description

void print(boolean b) It prints the specified boolean value.

void print(char c) It prints the specified char value.

void print(char[] c) It prints the specified character array values.

void print(int i) It prints the specified int value.

void print(long l) It prints the specified long value.

void print(float f) It prints the specified float value.

void print(double d) It prints the specified double value.

void print(String s) It prints the specified string value.

void print(Object obj) It prints the specified object value.

void println(boolean b) It prints the specified boolean value and terminates

the line.

void println(char c) It prints the specified char value and terminates the

line.

void println(char[] c) It prints the specified character array values and

terminates the line.

void println(int i) It prints the specified int value and terminates the

line.

Qasim Ali Page 115


Object Oriented Programming In Java

void println(long l) It prints the specified long value and terminates the

line.

void println(float f) It prints the specified float value and terminates the

line.

void println(double d) It prints the specified double value and terminates the

line.

void println(String s) It prints the specified string value and terminates the

line.

void println(Object obj) It prints the specified object value and terminates the

line.

void println() It terminates the line only.

void printf(Object format, Object... It writes the formatted string to the current stream.

args)

void printf(Locale l, Object format, It writes the formatted string to the current stream.

Object... args)

void format(Object format, Object... It writes the formatted string to the current stream

args) using specified format.

void format(Locale l, Object format, It writes the formatted string to the current stream

Object... args) using specified format.

Example of java PrintStream class


In this example, we are simply printing integer and string value.

package com.javatpoint;  

import java.io.FileOutputStream;  

import java.io.PrintStream;  

public class PrintStreamTest{    

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

   FileOutputStream fout=new FileOutputStream("D:\\testout.txt ");    

   PrintStream pout=new PrintStream(fout);    

Qasim Ali Page 116


Object Oriented Programming In Java
   pout.println(2016);    

   pout.println("Hello Java");    

   pout.println("Welcome to Java");    

   pout.close();    

   fout.close();    

  System.out.println("Success?");    

 }    

}    
Output
Success...
The content of a text file testout.txt is set with the below data
2016
Hello Java
Welcome to Java

Java program to read a file line by line

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class ReadLineByLine


{
public static void main(String[] args)
{
// create object of scanner class.
Scanner Sc=new Scanner(System.in);

// enter file name.


System.out.print("Enter the file name:");
String sfilename=Sc.next();
Scanner Sc1= null;
FileInputStream fis=null;
try
{
FileInputStream FI=new FileInputStream(sfilename);
Sc1=new Scanner(FI);

// this will read data till the end of data.


while(Sc1.hasNext())
{
String data=Sc1.nextLine();

// print the data.


System.out.print("The file data is : " +data);
}
}
catch(IOException e)
{
System.out.println(e);
}
}

Output

Enter the file name: E:/B.txt


This is line 1
This is line 2

Qasim Ali Page 117


Object Oriented Programming In Java
This is line 3
This is line 4

Java program to read content from one file and write it into another file

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class CopyFile {

public static void main(String[] args) {


try
{
boolean create=true;
Scanner KB=new Scanner(System.in);

System.out.print("Enter Source File Name:");


String sfilename=KB.next();
File srcfile=new File(sfilename);
if(!srcfile.exists())
{
System.out.println("File Not Found..");
}
else
{
FileInputStream FI=new FileInputStream(sfilename);
System.out.print("Enter Target File Name:");
String tfilename=KB.next();
File tfile=new File(tfilename);
if(tfile.exists())
{
System.out.print("File Already Exist OverWrite
it..Yes/No?:");
String confirm=KB.next();
if(confirm.equalsIgnoreCase("yes"))
{
create=true;
}
else
{
create=false;
}
}
if(create)
{
FileOutputStream FO=new
FileOutputStream(tfilename);
int b;
//read content and write in another file
while((b=FI.read())!=-1)
{
FO.write(b);
}
System.out.println("\nFile Copied...");
}
FI.close();
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}

Qasim Ali Page 118


Object Oriented Programming In Java
Output

File Copied...
Java program to append text/string in a file

Example:

File’s content: "This is sample text."


Text to append: "Text to be appended."
File’s content after appending: "This is sample text.Text to be appended."

Consider the program

import java.io.*;

public class AppendFile


{
public static void main(String[] args)
{
//file name with path
String strFilePath = "E:/JAVA/IncludeHelp.txt";
try
{
//file output stream to open and write data
FileOutputStream fos = new FileOutputStream(strFilePath, true);
//string to be appended
String strContent = "Text to be appended.";

//appending text/string
fos.write(strContent.getBytes());
//closing the file
fos.close();
System.out.println("Content Successfully Append into File...");
}
catch(FileNotFoundException ex)
{
System.out.println("FileNotFoundException : " + ex.toString());
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe.toString());
}
catch (Exception e)
{
System.out.println("Exception: " + e.toString());
}
}
}

Output

Content Successfully Append into File...

Java program to determine number of bytes written to file using DataOutputStream

import java.io.*;

public class ExToDetermineWrittenDataSize


{
//Java program to determine number of bytes written to file using DataOutputStream
public static void main(String[] args){
try

Qasim Ali Page 119


Object Oriented Programming In Java
{
FileOutputStream objFOS = new FileOutputStream("E:/includehelp.txt");
DataOutputStream objDOS = new DataOutputStream(objFOS);

objDOS.writeBytes("IncludeHelp is for computer science students.");


int bytesWritten = objDOS.size();
System.out.println("Total " + bytesWritten + " bytes are written to stream.");
objDOS.close();
}
catch(Exception ex)
{
System.out.println("Exception: " + ex.toString());
}

}
}

Output

Total 45 bytes are written to stream.

Serialization in Java

Serialization in java is a mechanism of writing the state of an object into a byte stream.

It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization.


Advantage of Java Serialization

It is mainly used to travel object's state on the network (known as marshaling).

java.io.Serializable interface

Serializable is a marker interface (has no data member and method). It is used to "mark" java classes so that objects of

Qasim Ali Page 120


Object Oriented Programming In Java

these classes may get certain capability. The Cloneable and Remote are also marker interfaces.

It must be implemented by the class whose object you want to persist.

The String class and all the wrapper classes implements java.io.Serializable interface by default.

Let's see the example given below:

import java.io.Serializable;  

public class Student implements Serializable{  

 int id;  

 String name;  

 public Student(int id, String name) {  

  this.id = id;  

  this.name = name;  

 }  

}  

In the above example, Student class implements Serializable interface. Now its objects can be converted into stream.

ObjectOutputStream class

The ObjectOutputStream class is used to write primitive data types and Java objects to an OutputStream. Only objects

that support the java.io.Serializable interface can be written to streams.


Constructor

1) public ObjectOutputStream(OutputStream out) throws IOException {}creates an ObjectOutputStream that

writes to the specified OutputStream.

Important Methods

Method Description

1) public final void writes the specified object to

writeObject(Object obj) throws the ObjectOutputStream.

IOException {}

2) public void flush() throws flushes the current output

IOException {} stream.

3) public void close() throws closes the current output

IOException {} stream.

Example of Java Serialization

Qasim Ali Page 121


Object Oriented Programming In Java

In this example, we are going to serialize the object of Student class. The writeObject() method of ObjectOutputStream

class provides the functionality to serialize the object. We are saving the state of the object in the file named f.txt.

import java.io.*;  

class Persist{  

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

  Student s1 =new Student(211,"ravi");  

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

  ObjectOutputStream out=new ObjectOutputStream(fout);  

  out.writeObject(s1);  

  out.flush();  

  System.out.println("success");  

 }  

}  

success

Deserialization in java

Deserialization is the process of reconstructing the object from the serialized state.It is the reverse operation of

serialization.
ObjectInputStream class

An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.


Constructor

1) public creates an

ObjectInputStream(InputStream ObjectInputStream

in) throws IOException {} that reads from the

specified InputStream.

Important Methods

Method Description

1) public final Object readObject() reads an object from

throws IOException, the input stream.

ClassNotFoundException{}

2) public void close() throws closes

IOException {} ObjectInputStream.

Example of Java Deserialization

Qasim Ali Page 122


Object Oriented Programming In Java

import java.io.*;  

class Depersist{  

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

 ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));  

  Student s=(Student)in.readObject();  

  System.out.println(s.id+" "+s.name);  

  

  in.close();  

 }  

}  

211 ravi

Java Serialization with Inheritance (IS-A Relationship)

If a class implements serializable then all its sub classes will also be serializable. Let's see the example given below:

import java.io.Serializable;  

class Person implements Serializable{  

 int id;  

 String name;  

 Person(int id, String name) {  

  this.id = id;  

  this.name = name;  

 }  

}  

class Student extends Person{  

 String course;  

 int fee;  

 public Student(int id, String name, String course, int fee) {  

  super(id,name);  

  this.course=course;  

  this.fee=fee;  

 }  

}  

Now you can serialize the Student class object that extends the Person class which is Serializable.Parent class

properties are inherited to subclasses so if parent class is Serializable, subclass would also be.

Qasim Ali Page 123


Object Oriented Programming In Java

Java Serialization with Aggregation (HAS-A Relationship)

If a class has a reference of another class, all the references must be Serializable otherwise serialization process will

not be performed. In such case, NotSerializableException is thrown at runtime.

class Address{  

 String addressLine,city,state;  

 public Address(String addressLine, String city, String state) {  

  this.addressLine=addressLine;  

  this.city=city;  

  this.state=state;  

 }  

}  

import java.io.Serializable;  

public class Student implements Serializable{  

 int id;  

 String name;  

 Address address;//HAS-A  

 public Student(int id, String name) {  

  this.id = id;  

  this.name = name;  

 }  

}  

Since Address is not Serializable, you can not serialize the instance of Student class.

Note: All the objects within an object must be Serializable.

Java Serialization with static data member

If there is any static data member in a class, it will not be serialized because static is the part of class not object.

class Employee implements Serializable{  

 int id;  

 String name;  

 static String company="SSS IT Pvt Ltd";//it won't be serialized  

 public Student(int id, String name) {  

  this.id = id;  

  this.name = name;  

Qasim Ali Page 124


Object Oriented Programming In Java
 }  

}  
Java Serialization with array or collection

Rule: In case of array or collection, all the objects of array or collection must be serializable. If any object is not

serialiizable, serialization will be failed.


Externalizable in java

The Externalizable interface provides the facility of writing the state of an object into a byte stream in compress

format. It is not a marker interface.

The Externalizable interface provides two methods:

o public void writeExternal(ObjectOutput out) throws IOException

o public void readExternal(ObjectInput in) throws IOException

Collections 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).
What is Collection in java

Collection represents a single unit of objects i.e. a group.


What is framework in java

o provides readymade architecture.

o represents set of classes and interface.

o is optional.
What is Collection framework

Collection framework represents a unified architecture for storing and manipulating group of objects. It has:

1. Interfaces and its implementations i.e. classes

2. Algorithm

Do You Know ?

o What are the two ways to iterate the elements of a collection ?

o What is the difference between ArrayList and LinkedList classes in collection framework?

o What is the difference between ArrayList and Vector classes in collection framework?

o What is the difference between HashSet and HashMap classes in collection framework?

o What is the difference between HashMap and Hashtable class?

o What is the difference between Iterator and Enumeration interface in collection framework?

o How can we sort the elements of an object. What is the difference between Comparable and Comparator

interfaces?

o What does the hashcode() method ?

o What is the difference between java collection and java collections ?

Qasim Ali Page 125


Object Oriented Programming In Java
Hierarchy of Collection Framework
Let us see the hierarchy of collection framework.The java.util package contains all the classes and interfaces for
Collection framework.

Methods of Collection interface


There are many methods declared in the Collection interface. They are as follows:

No. Method Description

1 public boolean add(Object is used to insert an element in

element) this collection.

2 public boolean is used to insert the specified

addAll(Collection c) collection elements in the

invoking collection.

3 public boolean is used to delete an element from

remove(Object element) this collection.

4 public boolean is used to delete all the elements

removeAll(Collection c) of specified collection from the

invoking collection.

5 public boolean is used to delete all the elements

retainAll(Collection c) of invoking collection except the

Qasim Ali Page 126


Object Oriented Programming In Java

specified collection.

6 public int size() return the total number of

elements in the collection.

7 public void clear() removes the total no of element

from the collection.

8 public boolean is used to search an element.

contains(Object element)

9 public boolean is used to search the specified

containsAll(Collection c) collection in this collection.

1 public Iterator iterator() returns an iterator.

1 public Object[] toArray() converts collection into array.

1 public boolean isEmpty() checks if collection is empty.

1 public boolean matches two collection.

3 equals(Object element)

1 public int hashCode() returns the hashcode number for

4 collection.

Iterator interface

Iterator interface provides the facility of iterating the elements in forward direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:

No. Method Description

1 public boolean It returns true if iterator has more elements.

hasNext()

Qasim Ali Page 127


Object Oriented Programming In Java

2 public Object It returns the element and moves the cursor

next() pointer to the next element.

3 public void It removes the last elements returned by the

remove() iterator. It is rarely used.

Collection Interface

The Collection interface is the interface which is implemented by all the classes in the collection framework. It declares the
methods that every collection will have. In other words, we can say that the Collection interface builds the foundation on
which the collection framework depends.

Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll ( Collection c), void clear(),
etc. which are implemented by all the subclasses of Collection interface.

List Interface

List interface is the child interface of Collection interface. It inhibits a list type data structure in which we can store the
ordered collection of objects. It can have the duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();  

2. List <data-type> list2 = new LinkedList();  

3. List <data-type> list3 = new Vector();  

4. List <data-type> list4 = new Stack();  

ArrayList

The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate element of different data
types. The ArrayList class maintains the insertion order and is non-synchronized. The elements stored in ArrayList class
can be randomly accessed. Consider the following example.

1. import java.util.*;  

2. class TestJavaCollection1{  

3. public static void main(String args[]){  

4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist  

5. list.add("Ravi");//Adding object in arraylist  

6. list.add("Vijay");  

7. list.add("Ravi");  

8. list.add("Ajay");  

9. //Traversing list through Iterator  

Qasim Ali Page 128


Object Oriented Programming In Java
10. Iterator itr=list.iterator();  

11. while(itr.hasNext()){  

12. System.out.println(itr.next());  

13. }  

14. }  

15. }  

LinkedList

LinkedList implements the Collection interface. It uses a doubly linked list internally to store the elements. It can store the
duplicate elements. It maintains the insertion order and is not synchronized. In LinkedList, the manipulation is fast because
no shifting is required.

Consider the following example.

1. import java.util.*;  

2. public class TestJavaCollection2{  

3. public static void main(String args[]){  

4. LinkedList<String> al=new LinkedList<String>();  

5. al.add("Ravi");  

6. al.add("Vijay");  

7. al.add("Ravi");  

8. al.add("Ajay");  

9. Iterator<String> itr=al.iterator();  

10. while(itr.hasNext()){  

11. System.out.println(itr.next());  

12. }  

13. }  

14. }  

Vector

Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is synchronized and contains
many methods that are not the part of Collection framework.

Consider the following example.

1. import java.util.*;  

2. public class TestJavaCollection3{  

3. public static void main(String args[]){  

4. Vector<String> v=new Vector<String>();  

5. v.add("Ayush");  

Qasim Ali Page 129


Object Oriented Programming In Java
6. v.add("Amit");  

7. v.add("Ashish");  

8. v.add("Garima");  

9. Iterator<String> itr=v.iterator();  

10. while(itr.hasNext()){  

11. System.out.println(itr.next());  

12. }  

13. }  

14. }  

Stack

The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The stack contains all of
the methods of Vector class and also provides its own methods like boolean push(), boolean peek(), boolean push(object
o), which defines its properties.

Consider the following example.

1. import java.util.*;  

2. public class TestJavaCollection4{  

3. public static void main(String args[]){  

4. Stack<String> stack = new Stack<String>();  

5. stack.push("Ayush");  

6. stack.push("Garvit");  

7. stack.push("Amit");  

8. stack.push("Ashish");  

9. stack.push("Garima");  

10. stack.pop();  

11. Iterator<String> itr=stack.iterator();  

12. while(itr.hasNext()){  

13. System.out.println(itr.next());  

14. }  

15. }  

16. }  

Queue Interface

Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used to hold the elements
which are about to be processed. There are various classes like PriorityQueue, Deque, ArrayDeque, etc. which implements
the Queue interface.

Queue interface can be instantiated as:

Qasim Ali Page 130


Object Oriented Programming In Java
1. Queue<String> q1 = new PriorityQueue();  

2. Queue<String> q2 = new ArrayDeque();  

PriorityQueue

The PriorityQueue class implements the Queue interface. It holds the elements or objects which are to be processed by
their priorities. PriorityQueue doesn't allow null values to be stored in the queue.

Consider the following example.

1. import java.util.*;  

2. public class TestJavaCollection5{  

3. public static void main(String args[]){  

4. PriorityQueue<String> queue=new PriorityQueue<String>();  

5. queue.add("Amit Sharma");  

6. queue.add("Vijay Raj");  

7. queue.add("JaiShankar");  

8. queue.add("Raj");  

9. System.out.println("head:"+queue.element());  

10. System.out.println("head:"+queue.peek());  

11. System.out.println("iterating the queue elements:");  

12. Iterator itr=queue.iterator();  

13. while(itr.hasNext()){  

14. System.out.println(itr.next());  

15. }  

16. queue.remove();  

17. queue.poll();  

18. System.out.println("after removing two elements:");  

19. Iterator<String> itr2=queue.iterator();  

20. while(itr2.hasNext()){  

21. System.out.println(itr2.next());  

22. }  

23. }  

24. }  

Output:

head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj

Qasim Ali Page 131


Object Oriented Programming In Java
after removing two elements:
Raj
Vijay Raj

Deque Interface

Deque interface extends the Queue interface. In Deque, we can remove and add the elements from both the side. Deque
stands for a double-ended queue which enables us to perform the operations at both the ends.

Deque can be instantiated as:

1. Deque d = new ArrayDeque();  

ArrayDeque

ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we can add or delete
the elements from both the ends.

ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

Consider the following example.

1. import java.util.*;  

2. public class TestJavaCollection6{  

3. public static void main(String[] args) {  

4. //Creating Deque and adding elements  

5. Deque<String> deque = new ArrayDeque<String>();  

6. deque.add("Gautam");  

7. deque.add("Karan");  

8. deque.add("Ajay");  

9. //Traversing elements  

10. for (String str : deque) {  

11. System.out.println(str);  

12. }  

13. }  

14. }  

Output:

Gautam
Karan
Ajay

Set Interface

Qasim Ali Page 132


Object Oriented Programming In Java
Set Interface in Java is present in java.util package. It extends the Collection interface. It represents the unordered set of
elements which doesn't allow us to store the duplicate items. We can store at most one null value in Set. Set is implemented
by HashSet, LinkedHashSet, and TreeSet.

Set can be instantiated as:

1. Set<data-type> s1 = new HashSet<data-type>();  

2. Set<data-type> s2 = new LinkedHashSet<data-type>();  

3. Set<data-type> s3 = new TreeSet<data-type>();  

HashSet

HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing is used to
store the elements in the HashSet. It contains the unique items.

Consider the following example.

1. import java.util.*;  

2. public class TestJavaCollection7{  

3. public static void main(String args[]){  

4. //Creating HashSet and adding elements  

5. HashSet<String> set=new HashSet<String>();  

6. set.add("Ravi");  

7. set.add("Vijay");  

8. set.add("Ravi");  

9. set.add("Ajay");  

10. //Traversing elements  

11. Iterator<String> itr=set.iterator();  

12. while(itr.hasNext()){  

13. System.out.println(itr.next());  

14. }  

15. }  

16. }  

Output:

Vijay
Ravi
Ajay

LinkedHashSet

LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the HashSet class and
implements Set interface. Like HashSet, It also contains unique elements. It maintains the insertion order and permits null
elements.

Consider the following example.

Qasim Ali Page 133


Object Oriented Programming In Java
1. import java.util.*;  

2. public class TestJavaCollection8{  

3. public static void main(String args[]){  

4. LinkedHashSet<String> set=new LinkedHashSet<String>();  

5. set.add("Ravi");  

6. set.add("Vijay");  

7. set.add("Ravi");  

8. set.add("Ajay");  

9. Iterator<String> itr=set.iterator();  

10. while(itr.hasNext()){  

11. System.out.println(itr.next());  

12. }  

13. }  

14. }  

SortedSet Interface

SortedSet is the alternate of Set interface that provides a total ordering on its elements. The elements of the SortedSet are
arranged in the increasing (ascending) order. The SortedSet provides the additional methods that inhibit the natural
ordering of the elements.

The SortedSet can be instantiated as:

1. SortedSet<data-type> set = new TreeSet();  

TreeSet

Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also contains the unique
elements However, the access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.

Consider the following example:

1. import java.util.*;  

2. public class TestJavaCollection9{  

3. public static void main(String args[]){  

4. //Creating and adding elements  

5. TreeSet<String> set=new TreeSet<String>();  

6. set.add("Ravi");  

7. set.add("Vijay");  

8. set.add("Ravi");  

9. set.add("Ajay");  

10. //traversing elements  

Qasim Ali Page 134


Object Oriented Programming In Java
11. Iterator<String> itr=set.iterator();  

12. while(itr.hasNext()){  

13. System.out.println(itr.next());  

14. }  

15. }  

16. }  

Java Map Interface

A map contains values on the basis of key i.e. key and value pair. Each key and value pair is known as an entry. Map
contains only unique keys.

Map is useful if you have to search, update or delete elements on the basis of key.

Java Map Hierarchy

There are two interfaces for implementing Map in java: Map and SortedMap, and three classes: HashMap,
LinkedHashMap and TreeMap. The hierarchy of Java Map is given below:

Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and LinkedHashMap allows null keys and
values but TreeMap doesn't allow any null key or value.

Map can't be traversed so you need to convert it into Set using keySet() or entrySet() method.

Class Description

HashMap HashMap is the implementation of Map but it doesn't maintain any order.

Qasim Ali Page 135


Object Oriented Programming In Java

LinkedHashMa LinkedHashMap is the implementation of Map, it inherits HashMap class. It

p maintains insertion order.

TreeMap TreeMap is the implementation of Map and SortedMap, it maintains ascending order.

Useful methods of Map interface

Method Description

Object put(Object key, Object It is used to insert an entry in this map.

value)

void putAll(Map map) It is used to insert the specified map in this map.

Object remove(Object key) It is used to delete an entry for the specified key.

Object get(Object key) It is used to return the value for the specified key.

boolean containsKey(Object key) It is used to search the specified key from this map.

Set keySet() It is used to return the Set view containing all the keys.

Set entrySet() It is used to return the Set view containing all the keys and

values.

Map.Entry Interface

Entry is the sub interface of Map. So we will be accessed it by Map.Entry name. It provides methods to get key and value.

Methods of Map.Entry interface

Method Description

Qasim Ali Page 136


Object Oriented Programming In Java

Object getKey() It is used to obtain key.

Object getValue() It is used to obtain value.

Java Map Example: Generic (New Style)

1. import java.util.*;  

2. class MapInterfaceExample{  

3.  public static void main(String args[]){  

4.   Map<Integer,String> map=new HashMap<Integer,String>();  

5.   map.put(100,"Amit");  

6.   map.put(101,"Vijay");  

7.   map.put(102,"Rahul");  

8.   for(Map.Entry m : map.entrySet()){  

9.    System.out.println(m.getKey()+" "+m.getValue());  

10.   }  

11.  }  

12. }  

Output:

102 Rahul
100 Amit
101 Vijay

Java Map Example: Non-Generic (Old Style)

1. //Non-generic  

2. import java.util.*;  

3. public class MapExample1 {  

4. public static void main(String[] args) {  

5.     Map map=new HashMap();  

6.     //Adding elements to map  

7.     map.put(1,"Amit");  

8.     map.put(5,"Rahul");  

9.     map.put(2,"Jai");  

10.     map.put(6,"Amit");  

11.     //Traversing Map  

Qasim Ali Page 137


Object Oriented Programming In Java
12.     Set set=map.entrySet();//Converting to Set so that we can traverse  

13.     Iterator itr=set.iterator();  

14.     while(itr.hasNext()){  

15.         //Converting to Map.Entry so that we can get key and value separately  

16.         Map.Entry entry=(Map.Entry)itr.next();  

17.         System.out.println(entry.getKey()+" "+entry.getValue());  

18.     }  

19. }  

20. }  

Output:

1 Amit
2 Jai
5 Rahul
6 Amit

What we are going to learn in Java Collections Framework

1. ArrayList class

2. LinkedList class

3. List interface

4. HashSet class

5. LinkedHashSet class

6. TreeSet class

7. PriorityQueue class

8. Map interface

9. HashMap class

10. LinkedHashMap class

11. TreeMap class

12. Hashtable class

13. Sorting

14. Comparable interface

15. Comparator interface

16. Properties class in Java

For-each loop (Advanced or Enhanced For loop):


The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each
loop is that it eliminates the possibility of bugs and makes the code more readable.
Advantage of for-each loop:

o It makes the code more readable.

o It eliminates the possibility of programming errors.

Qasim Ali Page 138


Object Oriented Programming In Java
Syntax of for-each loop:

1. for(data_type variable : array | collection){}  
Simple Example of for-each loop for traversing the array elements:

class ForEachExample1{  

  public static void main(String args[]){  

   int arr[]={12,13,14,44};  

   for(int i:arr){  

     System.out.println(i);  

   }  }   }        
Output:
12
13
14
44
Simple Example of for-each loop for traversing the collection elements:

import java.util.*;  

class ForEachExample2{  

  public static void main(String args[]){  

   ArrayList<String> list=new ArrayList<String>();  

   list.add("vimal");  

   list.add("sonoo");  

   list.add("ratan");  

   for(String s:list){  

     System.out.println(s);  

   }  }   }        
Output:vimal
sonoo
ratan

Java AWT Tutorial


Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java.
Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system.
AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox, Choice,
List etc.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below.

Qasim Ali Page 139


Object Oriented Programming In Java

Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes
that extends Container class are known as container such as Frame, Dialog and Panel.

Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another window for
creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield
etc.

Frame
The Frame is the container that contain title bar and can have menu bars. It can have other components like button,
textfield etc.
Useful Methods of Component class

Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int height) sets the size (width and height) of the component.

public void setLayout(LayoutManager defines the layout manager for the component.

m)

public void setVisible(boolean status) changes the visibility of the component, by default

false.

Qasim Ali Page 140


Object Oriented Programming In Java
Java AWT Example
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.

o By extending Frame class (inheritance)

o By creating the object of Frame class (association)

AWT Example by Inheritance


Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button component on the
Frame.

import java.awt.*;  

class First extends Frame{  

First(){  

Button b=new Button("click me");  

b.setBounds(30,100,80,30);// setting button position  

add(b);//adding button into frame  

setSize(300,300);//frame size 300 width and 300 height  

setLayout(null);//no layout manager  

setVisible(true);//now frame will be visible, by default not visible  

}  

public static void main(String args[]){  

First f=new First();  

}}  
download this example
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that sets the position of the
awt button.

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are showing Button
component on the Frame.

import java.awt.*;  

class First2{  

First2(){  

Qasim Ali Page 141


Object Oriented Programming In Java
Frame f=new Frame();  

Button b=new Button("click me");  

b.setBounds(30,50,80,30);  

f.add(b);  

f.setSize(300,300);  

f.setLayout(null);  

f.setVisible(true);  

}  

public static void main(String args[]){  

First2 f=new First2();  

}}  

Event and Listener (Java Event Handling)

Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The

java.awt.event package provides many event classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

Qasim Ali Page 142


Object Oriented Programming In Java

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling


Following steps are required to perform event handling:

1. Attach Relevant Listener to your class(Either by Inheritence / Outer Class / by Anonymous Class)

2. Bind the listener with your component like button.

3. Pass event which will occur to the relevant method which will be called on generating an event.
Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For example:

o Button

o public void addActionListener(ActionListener a){}

o MenuItem

o public void addActionListener(ActionListener a){}

o TextField

o public void addActionListener(ActionListener a){}

o public void addTextListener(TextListener a){}

o TextArea

o public void addTextListener(TextListener a){}

o Checkbox

o public void addItemListener(ItemListener a){}

o Choice

o public void addItemListener(ItemListener a){}

o List

o public void addActionListener(ActionListener a){}

o public void addItemListener(ItemListener a){}

Java Event Handling Code


We can put the event handling code into one of the following places:

1. Within class

2. Other class

3. Anonymous class
Java event handling by implementing ActionListener

import java.awt.*;  

import java.awt.event.*;  

class AEvent extends Frame implements ActionListener{  

Qasim Ali Page 143


Object Oriented Programming In Java
TextField tf;  

AEvent(){  

//create components  

tf=new TextField();  

tf.setBounds(60,50,170,20);  

Button b=new Button("click me");  

b.setBounds(100,120,80,30);  

//register listener  

b.addActionListener(this);//passing current instance  

//add components and set size, layout and visibility  

add(b);

add(tf);  

setSize(300,300);  

setLayout(null);  

setVisible(true);  

}  

public void actionPerformed(ActionEvent e){  

tf.setText("Welcome");  

}  

public static void main(String args[]){  

new AEvent();  

}  

}  
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that sets the
position of the component it may be button, textfield etc.

Java event handling by outer class

import java.awt.*;  

Qasim Ali Page 144


Object Oriented Programming In Java
import java.awt.event.*;  

class AEvent2 extends Frame{  

TextField tf;  

AEvent2(){  

//create components  

tf=new TextField();  

tf.setBounds(60,50,170,20);  

Button b=new Button("click me");  

b.setBounds(100,120,80,30);  

//register listener  

Outer o=new Outer(this);  

b.addActionListener(o);//passing outer class instance  

//add components and set size, layout and visibility  

add(b);add(tf);  

setSize(300,300);  

setLayout(null);  

setVisible(true);  

}  

public static void main(String args[]){  

new AEvent2();  

}  

}  

import java.awt.event.*;  

class Outer implements ActionListener{  

AEvent2 obj;  

Outer(AEvent2 obj){  

this.obj=obj;  

}  

public void actionPerformed(ActionEvent e){  

obj.tf.setText("welcome");  

}  

}  

Java event handling by anonymous class

import java.awt.*;  

Qasim Ali Page 145


Object Oriented Programming In Java
import java.awt.event.*;  

class AEvent3 extends Frame{  

TextField tf;  

AEvent3(){  

tf=new TextField();  

tf.setBounds(60,50,170,20);  

Button b=new Button("click me");  

b.setBounds(50,120,80,30);  

b.addActionListener(new ActionListener(){  

public void actionPerformed(){  

tf.setText("hello");  

}  

});  

add(b);add(tf);  

setSize(300,300);  

setLayout(null);  

setVisible(true);  

}  

public static void main(String args[]){  

new AEvent3();  

}  


Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is
implemented by all the classes of layout managers. There are following classes that represents the layout managers:

1. java.awt.BorderLayout

2. java.awt.FlowLayout

3. java.awt.GridLayout

4. java.awt.CardLayout

5. java.awt.GridBagLayout

6. javax.swing.BoxLayout

7. javax.swing.GroupLayout

8. javax.swing.ScrollPaneLayout

9. javax.swing.SpringLayout etc.

Qasim Ali Page 146


Object Oriented Programming In Java
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region (area)
may contain one component only. It is the default layout of frame or window. The BorderLayout provides five constants
for each region:

1. public static final int NORTH

2. public static final int SOUTH

3. public static final int EAST

4. public static final int WEST

5. public static final int CENTER


Constructors of BorderLayout class:

o BorderLayout(): creates a border layout but with no gaps between the components.

o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps

between the components.


Example of BorderLayout class:

import java.awt.*;  

import javax.swing.*;  

public class Border {  

JFrame f;  

Border(){  

    f=new JFrame();  

    JButton b1=new JButton("NORTH");;  

    JButton b2=new JButton("SOUTH");;  

    JButton b3=new JButton("EAST");;  

    JButton b4=new JButton("WEST");;  

    JButton b5=new JButton("CENTER");;  

    f.add(b1,BorderLayout.NORTH);  

    f.add(b2,BorderLayout.SOUTH);  

    f.add(b3,BorderLayout.EAST);  

Qasim Ali Page 147


Object Oriented Programming In Java
    f.add(b4,BorderLayout.WEST);  

    f.add(b5,BorderLayout.CENTER);  

      

    f.setSize(300,300);  

    f.setVisible(true);  

}  

public static void main(String[] args) {  

    new Border();  

}  

}  
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.
Constructors of GridLayout class

1. GridLayout(): creates a grid layout with one column per component in a row.

2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps

between the components.

3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns

alongwith given horizontal and vertical gaps.


Example of GridLayout class

import java.awt.*;  

import javax.swing.*;  

public class MyGridLayout{  

JFrame f;  

MyGridLayout(){  

    f=new JFrame();  

    JButton b1=new JButton("1");  

    JButton b2=new JButton("2");  

    JButton b3=new JButton("3");  

    JButton b4=new JButton("4");  

Qasim Ali Page 148


Object Oriented Programming In Java
    JButton b5=new JButton("5");  

        JButton b6=new JButton("6");  

        JButton b7=new JButton("7");  

    JButton b8=new JButton("8");  

        JButton b9=new JButton("9");  

    f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);  

    f.add(b6);f.add(b7);f.add(b8);f.add(b9);  

    f.setLayout(new GridLayout(3,3));  

    //setting grid layout of 3 rows and 3 columns  

    f.setSize(300,300);  

    f.setVisible(true);  

}  

public static void main(String[] args) {  

    new MyGridLayout();  

}  

}  
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet
or panel.
Fields of FlowLayout class

1. public static final int LEFT

2. public static final int RIGHT

3. public static final int CENTER

4. public static final int LEADING

5. public static final int TRAILING


Constructors of FlowLayout class

1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.

2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and

vertical gap.

3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given

horizontal and vertical gap.

Qasim Ali Page 149


Object Oriented Programming In Java
Example of FlowLayout class

import java.awt.*;  

import javax.swing.*;   

public class MyFlowLayout{  

JFrame f;  

MyFlowLayout(){  

    f=new JFrame();

    JButton b1=new JButton("1");  

    JButton b2=new JButton("2");  

    JButton b3=new JButton("3");  

    JButton b4=new JButton("4");  

    JButton b5=new JButton("5");

    f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);  

    f.setLayout(new FlowLayout(FlowLayout.RIGHT));  

    //setting flow layout of right alignment  

    f.setSize(300,300);  

    f.setVisible(true);  

}  

public static void main(String[] args) {  

    new MyFlowLayout();  

}  

}  
Java BoxLayout
The BoxLayout is used to arrange the components either vertically or horizontally. For this purpose, BoxLayout provides
four constants. They are as follows:

Note: BoxLayout class is found in javax.swing package.

Fields of BoxLayout class

1. public static final int X_AXIS

Qasim Ali Page 150


Object Oriented Programming In Java
2. public static final int Y_AXIS

3. public static final int LINE_AXIS

4. public static final int PAGE_AXIS


Constructor of BoxLayout class

1. BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given axis.
Example of BoxLayout class with Y-AXIS:

import java.awt.*;  

import javax.swing.*;  

public class BoxLayoutExample1 extends Frame {  

 Button buttons[];    

 public BoxLayoutExample1 () {  

   buttons = new Button [5];    

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

      buttons[i] = new Button ("Button " + (i + 1));  

      add (buttons[i]);  

    }  

setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));  

setSize(400,400);  

setVisible(true);  

}  

public static void main(String args[]){  

BoxLayoutExample1 b=new BoxLayoutExample1();  

}  

}  

Qasim Ali Page 151


Object Oriented Programming In Java
Example of BoxLayout class with X-AXIS

import java.awt.*;  

import javax.swing.*;   

public class BoxLayoutExample2 extends Frame {  

 Button buttons[];  

 public BoxLayoutExample2() {  

   buttons = new Button [5];  

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

      buttons[i] = new Button ("Button " + (i + 1));  

      add (buttons[i]);  

    }  

setLayout (new BoxLayout(this, BoxLayout.X_AXIS));  

setSize(400,400);  

setVisible(true);  

}  

public static void main(String args[]){  

BoxLayoutExample2 b=new BoxLayoutExample2();  

}  

}  
Java CardLayout
The CardLayout class manages the components in such a manner that only one component is visible at a time. It treats each
component as a card that is why it is known as CardLayout.
Constructors of CardLayout class

1. CardLayout(): creates a card layout with zero horizontal and vertical gap.

2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.
Commonly used methods of CardLayout class

o public void next(Container parent): is used to flip to the next card of the given container.

o public void previous(Container parent): is used to flip to the previous card of the given container.

Qasim Ali Page 152


Object Oriented Programming In Java
o public void first(Container parent): is used to flip to the first card of the given container.

o public void last(Container parent): is used to flip to the last card of the given container.

o public void show(Container parent, String name): is used to flip to the specified card with the given name.

Example of CardLayout class

import java.awt.*;  

import java.awt.event.*;  

import javax.swing.*;  

public class CardLayoutExample extends JFrame implements ActionListener{  

CardLayout card;  

JButton b1,b2,b3;  

Container c;  

    CardLayoutExample(){  

        c=getContentPane();  

        card=new CardLayout(40,30);  

//create CardLayout object with 40 hor space and 30 ver space  

        c.setLayout(card);  

        b1=new JButton("Apple");  

        b2=new JButton("Boy");  

        b3=new JButton("Cat");  

        b1.addActionListener(this);  

        b2.addActionListener(this);  

        b3.addActionListener(this);  

        c.add("a",b1);c.add("b",b2);c.add("c",b3);  

    }  

    public void actionPerformed(ActionEvent e) {  

    card.next(c);  

    }  

Qasim Ali Page 153


Object Oriented Programming In Java
    public static void main(String[] args) {  

        CardLayoutExample cl=new CardLayoutExample();  

        cl.setSize(400,400);  

        cl.setVisible(true);  

        cl.setDefaultCloseOperation(EXIT_ON_CLOSE);  

    }  

}  
Java AWT Button
The button class is used to create a labeled button that has platform independent implementation. The application result in
some action when the button is pushed.

AWT Button Class declaration

Java AWT Button Example with ActionListener

import java.awt.*;  

import java.awt.event.*;  

public class ButtonExample {  

public static void main(String[] args) {  

    Frame f=new Frame("Button Example");  

    final TextField tf=new TextField();  

    tf.setBounds(50,50, 150,20);  

    Button b=new Button("Click Here");  

    b.setBounds(50,100,60,30);  

    b.addActionListener(new ActionListener(){  

    public void actionPerformed(ActionEvent e){  

            tf.setText("Welcome to Javatpoint.");  

        }  

    });  

    f.add(b);f.add(tf);  

    f.setSize(400,400);  

    f.setLayout(null);  

    f.setVisible(true);   

}  

}  
Output:

Qasim Ali Page 154


Object Oriented Programming In Java

Java AWT Label


The object of Label class is a component for placing text in a container. It is used to display a single line of read only text.
The text can be changed by an application but a user cannot edit it directly.

AWT Label Class Declaration


Java AWT Label Example with ActionListener

import java.awt.*;  

import java.awt.event.*;  

public class LabelExample extends Frame implements ActionListener{  

    TextField tf; Label l; Button b;  

    LabelExample(){  

        tf=new TextField();  

        tf.setBounds(50,50, 150,20);  

        l=new Label();  

        l.setBounds(50,100, 250,20);      

        b=new Button("Find IP");  

        b.setBounds(50,150,60,30);  

        b.addActionListener(this);    

        add(b);add(tf);add(l);    

        setSize(400,400);  

        setLayout(null);  

        setVisible(true);  

    }  

    public void actionPerformed(ActionEvent e) {  

        try{  

        String host=tf.getText();  

        String ip=java.net.InetAddress.getByName(host).getHostAddress();  

Qasim Ali Page 155


Object Oriented Programming In Java
        l.setText("IP of "+host+" is: "+ip);  

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

    }  

    public static void main(String[] args) {  

        new LabelExample();  

    }  

}  
Output:

Java AWT TextField


The object of a TextField class is a text component that allows the editing of a single line text. It inherits TextComponent
class.

AWT TextField Class Declaration

1. public class TextField extends TextComponent  
Java AWT TextField Example

import java.awt.*;  

class TextFieldExample{  

public static void main(String args[]){  

    Frame f= new Frame("TextField Example");  

    TextField t1,t2;  

    t1=new TextField("Welcome to Javatpoint.");  

    t1.setBounds(50,100, 200,30);  

    t2=new TextField("AWT Tutorial");  

    t2.setBounds(50,150, 200,30);  

    f.add(t1); f.add(t2);  

    f.setSize(400,400);  

    f.setLayout(null);  

    f.setVisible(true);  

}  }  

Qasim Ali Page 156


Object Oriented Programming In Java
Output:

Java AWT TextField Example with ActionListener

import java.awt.*;  

import java.awt.event.*;  

public class TextFieldExample extends Frame implements ActionListener{  

    TextField tf1,tf2,tf3;  

    Button b1,b2;  

    TextFieldExample(){  

        tf1=new TextField();  

        tf1.setBounds(50,50,150,20);  

        tf2=new TextField();  

        tf2.setBounds(50,100,150,20);  

        tf3=new TextField();  

        tf3.setBounds(50,150,150,20);  

        tf3.setEditable(false);   

        b1=new Button("+");  

        b1.setBounds(50,200,50,50);  

        b2=new Button("-");  

        b2.setBounds(120,200,50,50);  

        b1.addActionListener(this);  

        b2.addActionListener(this);  

        add(tf1);add(tf2);add(tf3);add(b1);add(b2);  

        setSize(300,300);  

        setLayout(null);  

        setVisible(true);      }         

    public void actionPerformed(ActionEvent e) {  

        String s1=tf1.getText();  

        String s2=tf2.getText();  

Qasim Ali Page 157


Object Oriented Programming In Java
        int a=Integer.parseInt(s1);  

        int b=Integer.parseInt(s2);  

        int c=0;  

        if(e.getSource()==b1){  

            c=a+b;   }

else if(e.getSource()==b2){  

            c=a-b;  }  

        String result=String.valueOf(c);  

        tf3.setText(result);  

    }  

public static void main(String[] args) {  

    new TextFieldExample();  

}  

}  
Output:

Java AWT TextArea


The object of a TextArea class is a multi line region that displays text. It allows the editing of multiple line text. It inherits
TextComponent class.

AWT TextArea Class Declaration

Java AWT TextArea Example


Java AWT TextArea Example with ActionListener

import java.awt.*;  

import java.awt.event.*;  

public class TextAreaExample extends Frame implements ActionListener{  

Label l1,l2;  

TextArea area;  

Button b;  

TextAreaExample(){  

    l1=new Label();  

    l1.setBounds(50,50,100,30);  

    l2=new Label();  

Qasim Ali Page 158


Object Oriented Programming In Java
    l2.setBounds(160,50,100,30);  

    area=new TextArea();  

    area.setBounds(20,100,300,300);  

    b=new Button("Count Words");  

    b.setBounds(100,400,100,30);  

    b.addActionListener(this);  

    add(l1);add(l2);add(area);add(b);  

    setSize(400,450);  

    setLayout(null);  

    setVisible(true);  }  

public void actionPerformed(ActionEvent e){  

    String text=area.getText();  

    String words[]=text.split("\\s");  

    l1.setText("Words: "+words.length);  

    l2.setText("Characters: "+text.length());  }  

public static void main(String[] args) {  

    new TextAreaExample();  

}  }  
Output:

Java AWT CheckboxGroup


The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only one check box button is
allowed to be in "on" state and remaining check box button in "off" state. It inherits the object class.

Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special control for creating radio
buttons in AWT.

AWT CheckboxGroup Class Declaration

Qasim Ali Page 159


Object Oriented Programming In Java
Java AWT CheckboxGroup Example with ItemListener

import java.awt.*;    

import java.awt.event.*;  

public class CheckboxGroupExample    

{    

     CheckboxGroupExample(){    

       Frame f= new Frame("CheckboxGroup Example");    

       final Label label = new Label();          

       label.setAlignment(Label.CENTER);  

       label.setSize(400,100);  

        CheckboxGroup cbg = new CheckboxGroup();  

        Checkbox checkBox1 = new Checkbox("C++", cbg, false);    

        checkBox1.setBounds(100,100, 50,50);    

        Checkbox checkBox2 = new Checkbox("Java", cbg, false);    

        checkBox2.setBounds(100,150, 50,50);    

        f.add(checkBox1); f.add(checkBox2); f.add(label);    

        f.setSize(400,400);    

        f.setLayout(null);    

        f.setVisible(true);    

        checkBox1.addItemListener(new ItemListener() {  

            public void itemStateChanged(ItemEvent e) {               

               label.setText("C++ checkbox: Checked");  

            }  

         });  

        checkBox2.addItemListener(new ItemListener() {  

            public void itemStateChanged(ItemEvent e) {               

               label.setText("Java checkbox: Checked");  

            }  

         });  

     }    

public static void main(String args[])    

{    

    new CheckboxGroupExample();    

}    }  
Output:

Qasim Ali Page 160


Object Oriented Programming In Java

Java AWT Choice


The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on the top of a menu.
It inherits Component class.

AWT Choice Class Declaration


Java AWT Choice Example with ActionListener

import java.awt.*;  

import java.awt.event.*;  

public class ChoiceExample  

{  

        ChoiceExample(){  

        Frame f= new Frame();  

        final Label label = new Label();          

        label.setAlignment(Label.CENTER);  

        label.setSize(400,100);  

        Button b=new Button("Show");  

        b.setBounds(200,100,50,20);  

        final Choice c=new Choice();  

        c.setBounds(100,100, 75,75);  

        c.add("C");  

        c.add("C++");  

        c.add("Java");  

        c.add("PHP");  

        c.add("Android");  

        f.add(c);f.add(label); f.add(b);  

        f.setSize(400,400);  

        f.setLayout(null);  

        f.setVisible(true);  

        b.addActionListener(new ActionListener() {  

Qasim Ali Page 161


Object Oriented Programming In Java
            public void actionPerformed(ActionEvent e) {       

         String data = "Programming language Selected: "+ c.getItem(c.getSelectedIndex());  

         label.setText(data);  

        }  

        });           

        }  

public static void main(String args[])  

{  

   new ChoiceExample();  

}  

}  
Output:

Java AWT List


The object of List class represents a list of text items. By the help of list, user can choose either one item or multiple items.
It inherits Component class.

AWT List class Declaration

Java AWT List Example with ActionListener

import java.awt.*;  

import java.awt.event.*;  

public class ListExample  

{  

     ListExample(){  

        Frame f= new Frame();  

        final Label label = new Label();          

        label.setAlignment(Label.CENTER);  

        label.setSize(500,100);  

        Button b=new Button("Show");  

        b.setBounds(200,150,80,30);  

        final List l1=new List(4, false);  

Qasim Ali Page 162


Object Oriented Programming In Java
        l1.setBounds(100,100, 70,70);  

        l1.add("C");  

        l1.add("C++");  

        l1.add("Java");  

        l1.add("PHP");  

        final List l2=new List(4, true);  

        l2.setBounds(100,200, 70,70);  

        l2.add("Turbo C++");  

        l2.add("Spring");  

        l2.add("Hibernate");  

        l2.add("CodeIgniter");  

        f.add(l1); f.add(l2); f.add(label); f.add(b);  

        f.setSize(450,450);  

        f.setLayout(null);  

        f.setVisible(true);  

        b.addActionListener(new ActionListener() {  

         public void actionPerformed(ActionEvent e) {       

          String data = "Programming language Selected: "+l1.getItem(l1.getSelectedIndex());  

          data += ", Framework Selected:";  

          for(String frame:l2.getSelectedItems()){  

                   data += frame + " ";  

          }  

          label.setText(data);  

          }  

         });          }  

public static void main(String args[])  

{  

   new ListExample();  

}  }  
Output:

Qasim Ali Page 163


Object Oriented Programming In Java

Java AWT Scrollbar


The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a GUI component allows us to see
invisible number of rows and columns.
AWT Scrollbar class declaration

Java AWT Scrollbar Example with AdjustmentListener

import java.awt.*;  

import java.awt.event.*;  

class ScrollbarExample{  

     ScrollbarExample(){  

            Frame f= new Frame("Scrollbar Example");  

            final Label label = new Label();          

            label.setAlignment(Label.CENTER);  

            label.setSize(400,100);  

            final Scrollbar s=new Scrollbar();  

            s.setBounds(100,100, 50,100);  

            f.add(s);f.add(label);   

            f.setSize(400,400);  

            f.setLayout(null);  

            f.setVisible(true);  

            s.addAdjustmentListener(new AdjustmentListener() {  

                public void adjustmentValueChanged(AdjustmentEvent e) {  

                   label.setText("Vertical Scrollbar value is:"+ s.getValue());  

                }  

            });  

         }  

public static void main(String args[]){  

new ScrollbarExample();  

Qasim Ali Page 164


Object Oriented Programming In Java
}  

}  
Output:

Java AWT MenuItem and Menu


The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu must belong to the
MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the menu bar. It inherits the MenuItem
class.

AWT MenuItem class declaration

1. public class MenuItem extends MenuComponent implements Accessible  
AWT Menu class declaration

1. public class Menu extends MenuItem implements MenuContainer, Accessible  
Java AWT MenuItem and Menu Example

import java.awt.*;  

class MenuExample  

{  

     MenuExample(){  

         Frame f= new Frame("Menu and MenuItem Example");  

         MenuBar mb=new MenuBar();  

         Menu menu=new Menu("Menu");  

         Menu submenu=new Menu("Sub Menu");  

         MenuItem i1=new MenuItem("Item 1");  

         MenuItem i2=new MenuItem("Item 2");  

         MenuItem i3=new MenuItem("Item 3");  

         MenuItem i4=new MenuItem("Item 4");  

         MenuItem i5=new MenuItem("Item 5");  

         menu.add(i1);  

         menu.add(i2);  

         menu.add(i3);  

Qasim Ali Page 165


Object Oriented Programming In Java
         submenu.add(i4);  

         submenu.add(i5);  

         menu.add(submenu);  

         mb.add(menu);  

         f.setMenuBar(mb);  

         f.setSize(400,400);  

         f.setLayout(null);  

         f.setVisible(true);  

}  

public static void main(String args[])  

{  

new MenuExample();  

}  

}  
Output:

Java AWT PopupMenu


PopupMenu can be dynamically popped up at specific position within a component. It inherits the Menu class.

AWT PopupMenu class declaration

1. public class PopupMenu extends Menu implements MenuContainer, Accessible  
Java AWT PopupMenu Example

import java.awt.*;  

import java.awt.event.*;  

class PopupMenuExample  

{  

     PopupMenuExample(){  

         final Frame f= new Frame("PopupMenu Example");  

         final PopupMenu popupmenu = new PopupMenu("Edit");   

         MenuItem cut = new MenuItem("Cut");  

Qasim Ali Page 166


Object Oriented Programming In Java
         cut.setActionCommand("Cut");  

         MenuItem copy = new MenuItem("Copy");  

         copy.setActionCommand("Copy");  

         MenuItem paste = new MenuItem("Paste");  

         paste.setActionCommand("Paste");      

         popupmenu.add(cut);  

         popupmenu.add(copy);  

         popupmenu.add(paste);        

         f.addMouseListener(new MouseAdapter() {  

            public void mouseClicked(MouseEvent e) {              

                popupmenu.show(f , e.getX(), e.getY());  

            }                 

         });  

         f.add(popupmenu);   

         f.setSize(400,400);  

         f.setLayout(null);  

         f.setVisible(true);  

     }  

public static void main(String args[])  

{  

        new PopupMenuExample();  

}  }  
Output:

Java AWT Panel


The Panel is a simplest container class. It provides space in which an application can attach any other component. It
inherits the Container class.

Qasim Ali Page 167


Object Oriented Programming In Java
It doesn't have title bar.
AWT Panel class declaration

1. public class Panel extends Container implements Accessible  
Java AWT Panel Example

import java.awt.*;  

public class PanelExample {  

     PanelExample()  

        {  

        Frame f= new Frame("Panel Example");    

        Panel panel=new Panel();  

        panel.setBounds(40,80,200,200);    

        panel.setBackground(Color.gray);  

        Button b1=new Button("Button 1");     

        b1.setBounds(50,100,80,30);    

        b1.setBackground(Color.yellow);   

        Button b2=new Button("Button 2");   

        b2.setBounds(100,100,80,30);    

        b2.setBackground(Color.green);   

        panel.add(b1); panel.add(b2);  

        f.add(panel);  

        f.setSize(400,400);    

        f.setLayout(null);    

        f.setVisible(true);    

        }  

        public static void main(String args[])  

        {  

        new PanelExample();  

        }  

}  
Output:

Qasim Ali Page 168


Object Oriented Programming In Java

Java AWT Dialog


The Dialog control represents a top level window with a border and a title used to take some form of input from the user. It
inherits the Window class.
Unlike Frame, it doesn't have maximize and minimize buttons.

Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but Dialog doesn't have.
AWT Dialog class declaration

1. public class Dialog extends Window  
Java AWT Dialog Example

import java.awt.*;  

import java.awt.event.*;  

public class DialogExample {  

    private static Dialog d;  

    DialogExample() {  

        Frame f= new Frame();  

        d = new Dialog(f , "Dialog Example", true);  

        d.setLayout( new FlowLayout() );  

        Button b = new Button ("OK");  

        b.addActionListener ( new ActionListener()  

        {  

            public void actionPerformed( ActionEvent e )  

            {  

                DialogExample.d.setVisible(false);  

            }  

        });  

        d.add( new Label ("Click button to continue."));  

        d.add(b);   

Qasim Ali Page 169


Object Oriented Programming In Java
        d.setSize(300,300);    

        d.setVisible(true);  

    }  

    public static void main(String args[])  

    {  

        new DialogExample();  

    }  

}  
Output:

Java ActionListener Interface


The Java ActionListener is notified whenever you click on the button or menu item. It is notified against ActionEvent. The
ActionListener interface is found in java.awt.event package. It has only one method: actionPerformed().

actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the registered component.

1. public abstract void actionPerformed(ActionEvent e);  
Java ActionListener Example: On Button click

import java.awt.*;  

import java.awt.event.*;  

public class ActionListenerExample {  

public static void main(String[] args) {  

    Frame f=new Frame("ActionListener Example");  

    final TextField tf=new TextField();  

    tf.setBounds(50,50, 150,20);  

    Button b=new Button("Click Here");  

    b.setBounds(50,100,60,30);  

  

    b.addActionListener(new ActionListener(){  

    public void actionPerformed(ActionEvent e){  

            tf.setText("Welcome to Javatpoint.");  

    }  

Qasim Ali Page 170


Object Oriented Programming In Java
    });  

    f.add(b);f.add(tf);  

    f.setSize(400,400);  

    f.setLayout(null);  

    f.setVisible(true);   

}  }  
Output:

Java MouseListener Interface


The Java MouseListener is notified whenever you change the state of mouse. It is notified against MouseEvent. The
MouseListener interface is found in java.awt.event package. It has five methods.

Methods of MouseListener interface

1. public abstract void mouseClicked(MouseEvent e);  

2. public abstract void mouseEntered(MouseEvent e);  

3. public abstract void mouseExited(MouseEvent e);  

4. public abstract void mousePressed(MouseEvent e);  

5. public abstract void mouseReleased(MouseEvent e);  
Java MouseListener Example

import java.awt.*;  

import java.awt.event.*;  

public class MouseListenerExample extends Frame implements MouseListener{  

    Label l;  

    MouseListenerExample(){  

        addMouseListener(this);  

          

        l=new Label();  

        l.setBounds(20,50,100,20);  

        add(l);  

        setSize(300,300);  

Qasim Ali Page 171


Object Oriented Programming In Java
        setLayout(null);  

        setVisible(true);  

    }  

    public void mouseClicked(MouseEvent e) {  

        l.setText("Mouse Clicked");  

    }  

    public void mouseEntered(MouseEvent e) {  

        l.setText("Mouse Entered");  

    }  

    public void mouseExited(MouseEvent e) {  

        l.setText("Mouse Exited");  

    }  

    public void mousePressed(MouseEvent e) {  

        l.setText("Mouse Pressed");  

    }  

    public void mouseReleased(MouseEvent e) {  

        l.setText("Mouse Released");  

    }  

public static void main(String[] args) {  

    new MouseListenerExample();  

}  

}  
Output:

Java MouseListener Example 2

import java.awt.*;  

import java.awt.event.*;  

public class MouseListenerExample2 extends Frame implements MouseListener{  

    MouseListenerExample2(){  

        addMouseListener(this);  

Qasim Ali Page 172


Object Oriented Programming In Java
        setSize(300,300);  

        setLayout(null);  

        setVisible(true);  

    }  

    public void mouseClicked(MouseEvent e) {  

        Graphics g=getGraphics();  

        g.setColor(Color.BLUE);  

        g.fillOval(e.getX(),e.getY(),30,30);  

    }  

    public void mouseEntered(MouseEvent e) {}  

    public void mouseExited(MouseEvent e) {}  

    public void mousePressed(MouseEvent e) {}  

    public void mouseReleased(MouseEvent e) {}  

public static void main(String[] args) {  

    new MouseListenerExample2();  

}  

}  
Output:

Java ItemListener Interface


The Java ItemListener is notified whenever you click on the checkbox. It is notified against ItemEvent. The ItemListener
interface is found in java.awt.event package. It has only one method: itemStateChanged().

itemStateChanged() method
The itemStateChanged() method is invoked automatically whenever you click or unclick on the registered checkbox
component.

1. public abstract void itemStateChanged(ItemEvent e);  
Java ItemListener Example

import java.awt.*;    

import java.awt.event.*;    

public class ItemListenerExample implements ItemListener{    

    Checkbox checkBox1,checkBox2;  

Qasim Ali Page 173


Object Oriented Programming In Java
    Label label;  

    ItemListenerExample(){    

        Frame f= new Frame("CheckBox Example");    

        label = new Label();            

        label.setAlignment(Label.CENTER);    

        label.setSize(400,100);    

        checkBox1 = new Checkbox("C++");    

        checkBox1.setBounds(100,100, 50,50);    

        checkBox2 = new Checkbox("Java");    

        checkBox2.setBounds(100,150, 50,50);    

        f.add(checkBox1); f.add(checkBox2); f.add(label);    

        checkBox1.addItemListener(this);    

        checkBox2.addItemListener(this);    

        f.setSize(400,400);    

        f.setLayout(null);    

        f.setVisible(true);    

     }    

    public void itemStateChanged(ItemEvent e) {      

        if(e.getSource()==checkBox1)  

            label.setText("C++ Checkbox: "     

            + (e.getStateChange()==1?"checked":"unchecked"));   

        if(e.getSource()==checkBox2)  

        label.setText("Java Checkbox: "     

        + (e.getStateChange()==1?"checked":"unchecked"));    

     }  

public static void main(String args[])    

{    

    new ItemListenerExample();    

}    

}    
Output:

Qasim Ali Page 174


Object Oriented Programming In Java

Java KeyListener Interface


The Java KeyListener is notified whenever you change the state of key. It is notified against KeyEvent. The KeyListener
interface is found in java.awt.event package. It has three methods.

Methods of KeyListener interface


The signature of 3 methods found in KeyListener interface are given below:

1. public abstract void keyPressed(KeyEvent e);  

2. public abstract void keyReleased(KeyEvent e);  

3. public abstract void keyTyped(KeyEvent e);  

Java KeyListener Example

import java.awt.*;  

import java.awt.event.*;  

public class KeyListenerExample extends Frame implements KeyListener{  

    Label l;  

    TextArea area;  

    KeyListenerExample(){  

        l=new Label();  

        l.setBounds(20,50,100,20);  

        area=new TextArea();  

        area.setBounds(20,80,300, 300);  

        area.addKeyListener(this);  

        add(l);add(area);  

        setSize(400,400);  

        setLayout(null);  

        setVisible(true);  

    }  

    public void keyPressed(KeyEvent e) {  

Qasim Ali Page 175


Object Oriented Programming In Java
        l.setText("Key Pressed");  

    }  

    public void keyReleased(KeyEvent e) {  

        l.setText("Key Released");  

    }  

    public void keyTyped(KeyEvent e) {  

        l.setText("Key Typed");  

    }  

    public static void main(String[] args) {  

        new KeyListenerExample();  

    }  

}  
Output:

Java KeyListener Example 2: Count Words & Characters

import java.awt.*;  

import java.awt.event.*;  

public class KeyListenerExample extends Frame implements KeyListener{  

    Label l;  

    TextArea area;  

    KeyListenerExample(){  

        l=new Label();  

        l.setBounds(20,50,200,20);  

        area=new TextArea();  

        area.setBounds(20,80,300, 300);  

        area.addKeyListener(this);  

        add(l);add(area);  

Qasim Ali Page 176


Object Oriented Programming In Java
        setSize(400,400);  

        setLayout(null);  

        setVisible(true);  

    }  

    public void keyPressed(KeyEvent e) {}  

    public void keyReleased(KeyEvent e) {  

        String text=area.getText();  

        String words[]=text.split("\\s");  

        l.setText("Words: "+words.length+" Characters:"+text.length());  

    }  

    public void keyTyped(KeyEvent e) {}  

    public static void main(String[] args) {  

        new KeyListenerExample();  

    }  

}  
Output:

Java WindowListener Interface


The Java WindowListener is notified whenever you change the state of window. It is notified against WindowEvent. The
WindowListener interface is found in java.awt.event package. It has three methods.

Methods of WindowListener interface


The signature of 7 methods found in WindowListener interface are given below:

1. public abstract void windowActivated(WindowEvent e);  

2. public abstract void windowClosed(WindowEvent e);  

3. public abstract void windowClosing(WindowEvent e);  

4. public abstract void windowDeactivated(WindowEvent e);  

5. public abstract void windowDeiconified(WindowEvent e);  

6. public abstract void windowIconified(WindowEvent e);  

Qasim Ali Page 177


Object Oriented Programming In Java
7. public abstract void windowOpened(WindowEvent e);  
Java WindowListener Example

import java.awt.*;  

import java.awt.event.WindowEvent;  

import java.awt.event.WindowListener;  

public class WindowExample extends Frame implements WindowListener{  

    WindowExample(){  

        addWindowListener(this);  

        setSize(400,400);  

        setLayout(null);  

        setVisible(true);  

    }  

public static void main(String[] args) {  

    new WindowExample();  

}  

public void windowActivated(WindowEvent arg0) {  

    System.out.println("activated");  

}  

public void windowClosed(WindowEvent arg0) {  

    System.out.println("closed");  

}  

public void windowClosing(WindowEvent arg0) {  

    System.out.println("closing");  

    dispose();  

}  

public void windowDeactivated(WindowEvent arg0) {  

    System.out.println("deactivated");  

}  

public void windowDeiconified(WindowEvent arg0) {  

    System.out.println("deiconified");  

}  

public void windowIconified(WindowEvent arg0) {  

    System.out.println("iconified");  

}  

public void windowOpened(WindowEvent arg0) {  

Qasim Ali Page 178


Object Oriented Programming In Java
    System.out.println("opened");  

}  

}  
Output:
 

How to close AWT Window in Java


We can close the AWT Window or Frame by calling dispose() or System.exit() inside windowClosing() method. The
windowClosing() method is found in WindowListener interface and WindowAdapter class.
The WindowAdapter class implements WindowListener interfaces. It provides the default implementation of all the 7
methods of WindowListener interface. To override the windowClosing() method, you can either use WindowAdapter class
or WindowListener interface.
If you implement the WindowListener interface, you will be forced to override all the 7 methods of WindowListener
interface. So it is better to use WindowAdapter class.
Different ways to override windowClosing() method
There are many ways to override windowClosing() method:

o By anonymous class

o By inheriting WindowAdapter class

o By implementing WindowListener interface

Close AWT Window Example 1: Anonymous class

import java.awt.*;  

import java.awt.event.WindowEvent;  

import java.awt.event.WindowListener;  

public class WindowExample extends Frame{  

    WindowExample(){  

        addWindowListener(new WindowAdapter(){  

            public void windowClosing(WindowEvent e) {  

                dispose();  

            }  

        });  

        setSize(400,400);  

        setLayout(null);  

        setVisible(true);  

    }  

Qasim Ali Page 179


Object Oriented Programming In Java
public static void main(String[] args) {  

    new WindowExample();  

}  
Output:

Close AWT Window Example 2: extending WindowAdapter

import java.awt.*;  

import java.awt.event.*;  

public class AdapterExample extends WindowAdapter{  

    Frame f;  

    AdapterExample(){  

        f=new Frame();  

        f.addWindowListener(this);  

          

        f.setSize(400,400);  

        f.setLayout(null);  

        f.setVisible(true);  

    }  

public void windowClosing(WindowEvent e) {  

    f.dispose();  

}  

public static void main(String[] args) {  

    new AdapterExample();  

}  

}  
Close AWT Window Example 3: implementing WindowListener

import java.awt.*;  

import java.awt.event.WindowEvent;  

import java.awt.event.WindowListener;  

public class WindowExample extends Frame implements WindowListener{  

    WindowExample(){  

Qasim Ali Page 180


Object Oriented Programming In Java
        addWindowListener(this);  

        setSize(400,400);  

        setLayout(null);  

        setVisible(true);  

    }    

public static void main(String[] args) {  

    new WindowExample();  

}  

public void windowActivated(WindowEvent e) {}  

public void windowClosed(WindowEvent e) {}  

public void windowClosing(WindowEvent e) {  

    dispose();  

}  

public void windowDeactivated(WindowEvent e) {}  

public void windowDeiconified(WindowEvent e) {}  

public void windowIconified(WindowEvent e) {}  

public void windowOpened(WindowEvent arg0) {}  

}  
Java Swing Tutorial
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built
on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton,
JCheckbox, JMenu, JColorChooser etc.
Difference between AWT and Swing
There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1 AWT components are platform- Java swing components

) dependent. are platform-

independent.

2 AWT components Swing components

) are heavyweight. are lightweight.

3 AWT doesn't support Swing supports pluggable

) pluggable look and feel. look and feel.

Qasim Ali Page 181


Object Oriented Programming In Java

4 AWT provides less Swing provides more

) components than Swing. powerful

components such as

tables, lists, scrollpanes,

colorchooser, tabbedpane

etc.

5 AWT doesn't follows Swing follows MVC.

) MVC(Model View Controller)

where model represents data,

view represents presentation and

controller acts as an interface

between model and view.

What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications.
Do You Know

o How to create runnable jar file in java?

o How to display image on a button in swing?

o How to change the component color by choosing a color from ColorChooser ?

o How to display the digital watch in swing tutorial ?

o How to create a notepad in swing?

o How to create puzzle game and pic puzzle game in swing ?

o How to create tic tac toe game in swing ?

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.

Qasim Ali Page 182


Object Oriented Programming In Java

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int sets size of the component.

height)

public void setLayout(LayoutManager sets the layout manager for the component.

m)

public void setVisible(boolean b) sets the visibility of the component. It is by

default false.

Java Swing Examples


There are two ways to create a frame:

o By creating the object of Frame class (association)

o By extending Frame class (inheritance)


We can write the code of swing inside the main(), constructor or any other method.
Simple Java Swing Example
Let's see a simple swing example where we are creating one button and adding it on the JFrame object inside the main()
method.
File: FirstSwingExample.java

import javax.swing.*;  

Qasim Ali Page 183


Object Oriented Programming In Java
public class FirstSwingExample {  

public static void main(String[] args) {  

JFrame f=new JFrame();//creating instance of JFrame  

JButton b=new JButton("click");//creating instance of JButton  

b.setBounds(130,100,100, 40);//x axis, y axis, width, height            

f.add(b);//adding button in JFrame  

f.setSize(400,500);//400 width and 500 height  

f.setLayout(null);//using no layout managers  

f.setVisible(true);//making the frame visible  

}  

}  

Example of Swing by Association inside constructor


We can also write all the codes of creating JFrame, JButton and method call inside the java constructor.
File: Simple.java

import javax.swing.*;  

public class Simple {  

JFrame f;  

Simple(){  

f=new JFrame();//creating instance of JFrame         

JButton b=new JButton("click");//creating instance of JButton  

b.setBounds(130,100,100, 40);  

f.add(b);//adding button in JFrame  

f.setSize(400,500);//400 width and 500 height  

f.setLayout(null);//using no layout managers  

f.setVisible(true);//making the frame visible  

}  

public static void main(String[] args) {  

new Simple();  

}  

}  
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the position of the button.

Qasim Ali Page 184


Object Oriented Programming In Java
Simple example of Swing by inheritance
We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.
File: Simple2.java

import javax.swing.*;  

public class Simple2 extends JFrame{//inheriting JFrame  

JFrame f;  

Simple2(){  

JButton b=new JButton("click");//create button  

b.setBounds(130,100,100, 40);       

add(b);//adding button on frame  

setSize(400,500);  

setLayout(null);  

setVisible(true);  

}  

public static void main(String[] args) {  

new Simple2();  

}}  
Java JTable
The JTable class is used to display data in tabular form. It is composed of rows and columns.
JTable class declaration
Let's see the declaration for javax.swing.JTable class.
Commonly used Constructors:

Constructor Description

JTable() Creates a table with empty cells.

JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

Java JTable Example

import javax.swing.*;    

public class TableExample {    

    JFrame f;    

    TableExample(){    

    f=new JFrame();    

    String data[][]={ {"101","Amit","670000"},    

                          {"102","Jai","780000"},    

                          {"101","Sachin","700000"}};    

Qasim Ali Page 185


Object Oriented Programming In Java
    String column[]={"ID","NAME","SALARY"};         

    JTable jt=new JTable(data,column);    

    jt.setBounds(30,40,200,300);          

    JScrollPane sp=new JScrollPane(jt);    

    f.add(sp);          

    f.setSize(300,400);    

    f.setVisible(true);    

}     

public static void main(String[] args) {    

    new TableExample();    

}    

}  
Output:

Java JTable Example with ListSelectionListener

import javax.swing.*;    

import javax.swing.event.*;  

public class TableExample {    

      public static void main(String[] a) {  

            JFrame f = new JFrame("Table Example");  

            String data[][]={ {"101","Amit","670000"},    

                                                                       {"102","Jai","780000"},    

                                                                       {"101","Sachin","700000"}};    

                            String column[]={"ID","NAME","SALARY"};         

                            final JTable jt=new JTable(data,column);    

            jt.setCellSelectionEnabled(true);  

            ListSelectionModel select= jt.getSelectionModel();  

            select.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  

            select.addListSelectionListener(new ListSelectionListener() {  

              public void valueChanged(ListSelectionEvent e) {  

Qasim Ali Page 186


Object Oriented Programming In Java
                String Data = null;  

                int[] row = jt.getSelectedRows();  

                int[] columns = jt.getSelectedColumns();  

                for (int i = 0; i < row.length; i++) {  

                  for (int j = 0; j < columns.length; j++) {  

                    Data = (String) jt.getValueAt(row[i], columns[j]);  

                  } }  

                System.out.println("Table element selected is: " + Data);    

              }       

            });  

            JScrollPane sp=new JScrollPane(jt);    

            f.add(sp);  

            f.setSize(300, 200);  

            f.setVisible(true);  

          }  

        }  
Output:

If you select an element in column NAME, name of the element will be displayed on the console:

1. Table element selected is: Sachin  

Java JOptionPane

The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm dialog box and input
dialog box. These dialog boxes are used to display information or get input from the user. The JOptionPane class inherits
JComponent class.

JOptionPane class declaration

1. public class JOptionPane extends JComponent implements Accessible  

Common Constructors of JOptionPane class

Constructor Description

Qasim Ali Page 187


Object Oriented Programming In Java

JOptionPane() It is used to create a JOptionPane with a test message.

JOptionPane(Object message) It is used to create an instance of JOptionPane to display a

message.

JOptionPane(Object message, int It is used to create an instance of JOptionPane to display a

messageType message with specified message type and default options.

Common Methods of JOptionPane class

Methods Description

JDialog createDialog(String title) It is used to create and return a new

parentless JDialog with the specified title.

static void showMessageDialog(Component It is used to create an information-message

parentComponent, Object message) dialog titled "Message".

static void showMessageDialog(Component It is used to create a message dialog with

parentComponent, Object message, String title, int given title and messageType.

messageType)

static int showConfirmDialog(Component It is used to create a dialog with the options

parentComponent, Object message) Yes, No and Cancel; with the title, Select

an Option.

static String showInputDialog(Component It is used to show a question-message

parentComponent, Object message) dialog requesting input from the user

parented to parentComponent.

void setInputValue(Object newValue) It is used to set the input value that was

Qasim Ali Page 188


Object Oriented Programming In Java

selected or input by the user.

Java JOptionPane Example: showMessageDialog()

import javax.swing.*;  

public class OptionPaneExample {  

JFrame f;  

OptionPaneExample(){  

    f=new JFrame();  

    JOptionPane.showMessageDialog(f,"Hello, Welcome to Javatpoint.");  

}  

public static void main(String[] args) {  

    new OptionPaneExample();  

}  

}  

Output:

Java JOptionPane Example: showMessageDialog()

import javax.swing.*;  

public class OptionPaneExample {  

JFrame f;  

OptionPaneExample(){  

    f=new JFrame();  

    JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPane.WARNING_MESSAGE);     

}  

public static void main(String[] args) {  

    new OptionPaneExample();  

}  

}  Output:

Qasim Ali Page 189


Object Oriented Programming In Java

Java JOptionPane Example: showInputDialog()

import javax.swing.*;  

public class OptionPaneExample {  

JFrame f;  

OptionPaneExample(){  

    f=new JFrame();   

    String name=JOptionPane.showInputDialog(f,"Enter Name");      

}  

public static void main(String[] args) {  

    new OptionPaneExample();  

}  }  

Output:

Java JOptionPane Example: showConfirmDialog()

import javax.swing.*;  

import java.awt.event.*;  

public class OptionPaneExample extends WindowAdapter{  

JFrame f;  

OptionPaneExample(){  

    f=new JFrame();   

    f.addWindowListener(this);  

    f.setSize(300, 300);  

    f.setLayout(null);  

    f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);  

Qasim Ali Page 190


Object Oriented Programming In Java
    f.setVisible(true);  

}  

public void windowClosing(WindowEvent e) {  

    int a=JOptionPane.showConfirmDialog(f,"Are you sure?");  

if(a==JOptionPane.YES_OPTION){  

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  

}  

}  

public static void main(String[] args) {  

    new  OptionPaneExample();  

}     }  

Output:

Java JMenuBar, JMenu and JMenuItem


The JMenuBar class is used to display menubar on the window or frame. It may have several menus.
The object of JMenu class is a pull down menu component which is displayed from the menu bar. It inherits the
JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must belong to the JMenuItem
or any of its subclass.
JMenuBar class declaration

1. public class JMenuBar extends JComponent implements MenuElement, Accessible  
JMenu class declaration

1. public class JMenu extends JMenuItem implements MenuElement, Accessible  
JMenuItem class declaration

1. public class JMenuItem extends AbstractButton implements Accessible, MenuElement  
Example of creating Edit menu for Notepad:

import javax.swing.*;    

import java.awt.event.*;    

public class MenuExample implements ActionListener{    

JFrame f;    

JMenuBar mb;    

Qasim Ali Page 191


Object Oriented Programming In Java
JMenu file,edit,help;    

JMenuItem cut,copy,paste,selectAll;    

JTextArea ta;    

MenuExample(){    

f=new JFrame();    

cut=new JMenuItem("cut");    

copy=new JMenuItem("copy");    

paste=new JMenuItem("paste");    

selectAll=new JMenuItem("selectAll");    

cut.addActionListener(this);    

copy.addActionListener(this);    

paste.addActionListener(this);    

selectAll.addActionListener(this);    

mb=new JMenuBar();    

file=new JMenu("File");    

edit=new JMenu("Edit");    

help=new JMenu("Help");     

edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);    

mb.add(file);mb.add(edit);mb.add(help);    

ta=new JTextArea();    

ta.setBounds(5,5,360,320);    

f.add(mb);f.add(ta);    

f.setJMenuBar(mb);  

f.setLayout(null);    

f.setSize(400,400);    

f.setVisible(true);    

}     

public void actionPerformed(ActionEvent e) {    

if(e.getSource()==cut)    

ta.cut();    

if(e.getSource()==paste)    

ta.paste();    

if(e.getSource()==copy)    

ta.copy();    

Qasim Ali Page 192


Object Oriented Programming In Java
if(e.getSource()==selectAll)    

ta.selectAll();    

}     

public static void main(String[] args) {    

    new MenuExample();    

}    

}    
Output:

Java JPopupMenu
PopupMenu can be dynamically popped up at specific position within a component. It inherits the JComponent class.
JPopupMenu class declaration
Let's see the declaration for javax.swing.JPopupMenu class.

1. public class JPopupMenu extends JComponent implements Accessible, MenuElement  
Commonly used Constructors:

Constructor Description

JPopupMenu() Constructs a JPopupMenu without an "invoker".

JPopupMenu(String label) Constructs a JPopupMenu with the specified title.

Java JPopupMenu Example with MouseListener and ActionListener

import javax.swing.*;  

import java.awt.event.*;  

class PopupMenuExample   

{  

     PopupMenuExample(){  

         final JFrame f= new JFrame("PopupMenu Example");  

         final JLabel label = new JLabel();          

         label.setHorizontalAlignment(JLabel.CENTER);  

Qasim Ali Page 193


Object Oriented Programming In Java
         label.setSize(400,100);  

         final JPopupMenu popupmenu = new JPopupMenu("Edit");   

         JMenuItem cut = new JMenuItem("Cut");  

         JMenuItem copy = new JMenuItem("Copy");  

         JMenuItem paste = new JMenuItem("Paste");  

         popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste);        

         f.addMouseListener(new MouseAdapter() {  

            public void mouseClicked(MouseEvent e) {              

                popupmenu.show(f , e.getX(), e.getY());  

            }                 

         });  

        cut.addActionListener(new ActionListener(){  

         public void actionPerformed(ActionEvent e) {              

             label.setText("cut MenuItem clicked.");  

         }  

        });  

        copy.addActionListener(new ActionListener(){  

            public void actionPerformed(ActionEvent e) {              

                label.setText("copy MenuItem clicked.");  

            }  

           });  

        paste.addActionListener(new ActionListener(){  

            public void actionPerformed(ActionEvent e) {              

                label.setText("paste MenuItem clicked.");  

            }  

           });  

         f.add(label); f.add(popupmenu);   

         f.setSize(400,400);  

         f.setLayout(null);  

         f.setVisible(true);  

     }  

public static void main(String args[])  

{  

        new PopupMenuExample();  

Qasim Ali Page 194


Object Oriented Programming In Java
}  

}  
Output:

Java JProgressBar
The JProgressBar class is used to display the progress of the task. It inherits JComponent class.
JProgressBar class declaration
Let's see the declaration for javax.swing.JProgressBar class.

1. public class JProgressBar extends JComponent implements SwingConstants, Accessible  
Commonly used Constructors:

Constructor Description

JProgressBar() It is used to create a horizontal progress bar but no string text.

JProgressBar(int min, It is used to create a horizontal progress bar with the specified minimum

int max) and maximum value.

JProgressBar(int It is used to create a progress bar with the specified orientation, it can be

orient) either Vertical or Horizontal by using SwingConstants.VERTICAL and

SwingConstants.HORIZONTAL constants.

JProgressBar(int It is used to create a progress bar with the specified orientation, minimum

orient, int min, int and maximum value.

max)

Commonly used Methods:

Method Description

void It is used to determine whether string should be displayed.

setStringPainted(boolean b)

void setString(String s) It is used to set value to the progress string.

Qasim Ali Page 195


Object Oriented Programming In Java

void setOrientation(int It is used to set the orientation, it may be either vertical or horizontal

orientation) by using SwingConstants.VERTICAL and

SwingConstants.HORIZONTAL constants.

void setValue(int value) It is used to set the current value on the progress bar.

Java JProgressBar Example

import javax.swing.*;    

public class ProgressBarExample extends JFrame{    

JProgressBar jb;    

int i=0,num=0;     

ProgressBarExample(){    

jb=new JProgressBar(0,2000);    

jb.setBounds(40,40,160,30);         

jb.setValue(0);    

jb.setStringPainted(true);    

add(jb);    

setSize(250,150);    

setLayout(null);    

}    

public void iterate(){    

while(i<=2000){    

  jb.setValue(i);    

  i=i+20;    

  try{Thread.sleep(150);}catch(Exception e){}    

}    

}    

public static void main(String[] args) {    

    ProgressBarExample m=new ProgressBarExample();    

    m.setVisible(true);    

    m.iterate();    

}    

}    
Output:

Qasim Ali Page 196


Object Oriented Programming In Java

Java JTree
The JTree class is used to display the tree structured data or hierarchical data. JTree is a complex component. It has a 'root
node' at the top most which is a parent for all nodes in the tree. It inherits JComponent class.
JTree class declaration
Let's see the declaration for javax.swing.JTree class.

1. public class JTree extends JComponent implements Scrollable, Accessible  
Commonly used Constructors:

Constructor Description

JTree() Creates a JTree with a sample model.

JTree(Object[] Creates a JTree with every element of the specified array as the child of a

value) new root node.

JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which displays the

root) root node.

Java JTree Example

import javax.swing.*;  

import javax.swing.tree.DefaultMutableTreeNode;  

public class TreeExample {  

JFrame f;  

TreeExample(){  

    f=new JFrame();   

    DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");  

    DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");  

    DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");  

    style.add(color);  

    style.add(font);  

    DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");  

    DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");  

    DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");  

    DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");  

Qasim Ali Page 197


Object Oriented Programming In Java
    color.add(red); color.add(blue); color.add(black); color.add(green);      

    JTree jt=new JTree(style);  

    f.add(jt);  

    f.setSize(200,200);  

    f.setVisible(true);  

}  

public static void main(String[] args) {  

    new TreeExample();  

}}  

Output:

Java JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking on a tab with a given title or icon. It
inherits JComponent class.
JTabbedPane class declaration
Let's see the declaration for javax.swing.JTabbedPane class.

1. public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConstants  
Commonly used Constructors:

Constructor Description

JTabbedPane() Creates an empty TabbedPane with a default tab

placement of JTabbedPane.Top.

JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab

placement.

Qasim Ali Page 198


Object Oriented Programming In Java

JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab

tabLayoutPolicy) placement and tab layout policy.

Java JTabbedPane Example

import javax.swing.*;  

public class TabbedPaneExample {  

JFrame f;  

TabbedPaneExample(){  

    f=new JFrame();  

    JTextArea ta=new JTextArea(200,200);  

    JPanel p1=new JPanel();  

    p1.add(ta);  

    JPanel p2=new JPanel();  

    JPanel p3=new JPanel();  

    JTabbedPane tp=new JTabbedPane();  

    tp.setBounds(50,50,200,200);  

    tp.add("main",p1);  

    tp.add("visit",p2);  

    tp.add("help",p3);    

    f.add(tp);  

    f.setSize(400,400);  

    f.setLayout(null);  

    f.setVisible(true);  

}  

public static void main(String[] args) {  

    new TabbedPaneExample();  

}}  
Output:

Qasim Ali Page 199


Object Oriented Programming In Java

Java JPanel
The JPanel is a simplest container class. It provides space in which an application can attach any other component. It
inherits the JComponents class.
It doesn't have title bar.
JPanel class declaration

1. public class JPanel extends JComponent implements Accessible  
Commonly used Constructors:

Constructor Description

JPanel() It is used to create a new JPanel with a double buffer and a flow

layout.

JPanel(boolean It is used to create a new JPanel with FlowLayout and the specified

isDoubleBuffered) buffering strategy.

JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout manager.

Java JPanel Example

import java.awt.*;  

import javax.swing.*;  

public class PanelExample {  

     PanelExample()  

        {  

        JFrame f= new JFrame("Panel Example");    

        JPanel panel=new JPanel();  

        panel.setBounds(40,80,200,200);    

        panel.setBackground(Color.gray);  

        JButton b1=new JButton("Button 1");     

        b1.setBounds(50,100,80,30);    

Qasim Ali Page 200


Object Oriented Programming In Java
        b1.setBackground(Color.yellow);   

        JButton b2=new JButton("Button 2");   

        b2.setBounds(100,100,80,30);    

        b2.setBackground(Color.green);   

        panel.add(b1); panel.add(b2);  

        f.add(panel);  

                f.setSize(400,400);    

                f.setLayout(null);    

                f.setVisible(true);    

        }  

        public static void main(String args[])  

        {  

        new PanelExample();  

        }  

    }  
Output:

Java JFileChooser
The object of JFileChooser class represents a dialog window from which the user can select file. It inherits JComponent
class.
JFileChooser class declaration
Let's see the declaration for javax.swing.JFileChooser class.

1. public class JFileChooser extends JComponent implements Accessible  
Commonly used Constructors:

Constructor Description

JFileChooser() Constructs a JFileChooser pointing to the user's default

directory.

Qasim Ali Page 201


Object Oriented Programming In Java

JFileChooser(File currentDirectory) Constructs a JFileChooser using the given File as the

path.

JFileChooser(String Constructs a JFileChooser using the given path.

currentDirectoryPath)

Java JFileChooser Example

import javax.swing.*;    

import java.awt.event.*;    

import java.io.*;    

public class FileChooserExample extends JFrame implements ActionListener{    

JMenuBar mb;    

JMenu file;    

JMenuItem open;    

JTextArea ta;    

FileChooserExample(){    

open=new JMenuItem("Open File");    

open.addActionListener(this);            

file=new JMenu("File");    

file.add(open);             

mb=new JMenuBar();    

mb.setBounds(0,0,800,20);    

mb.add(file);              

ta=new JTextArea(800,800);    

ta.setBounds(0,20,800,800);              

add(mb);    

add(ta);              

}    

public void actionPerformed(ActionEvent e) {    

if(e.getSource()==open){    

    JFileChooser fc=new JFileChooser();    

    int i=fc.showOpenDialog(this);    

    if(i==JFileChooser.APPROVE_OPTION){    

        File f=fc.getSelectedFile();    

        String filepath=f.getPath();    

Qasim Ali Page 202


Object Oriented Programming In Java
        try{  

        BufferedReader br=new BufferedReader(new FileReader(filepath));    

        String s1="",s2="";                         

        while((s1=br.readLine())!=null){    

        s2+=s1+"\n";    

        }    

        ta.setText(s2);    

        br.close();    

        }catch (Exception ex) {ex.printStackTrace();  }                 

    }    

}    

}          

public static void main(String[] args) {    

    FileChooserExample om=new FileChooserExample();    

             om.setSize(500,500);    

             om.setLayout(null);    

             om.setVisible(true);    

             om.setDefaultCloseOperation(EXIT_ON_CLOSE);    

}    

}  
Output:

Qasim Ali Page 203


Object Oriented Programming In Java

Qasim Ali Page 204

You might also like