Object Oriented Programming in Java: Qasim Ali
Object Oriented Programming in Java: Qasim Ali
Object Oriented Programming in Java: Qasim Ali
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or
paradigm to design a program using classes and objects. It simplifies the software development and maintenance by
providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be
physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides
code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to convince the customer
differently, to draw something e.g. shape or rectangle etc.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the
internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is
wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are
private here.
1) OOPs makes development and maintenance easier where as in Procedure-oriented programming language it is
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
What is Java
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:
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.
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.
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.
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.
It is used to develop rich internet applications. It uses light-weight user interface API.
There are many java versions that has been released. Current stable release of Java is Java SE 8.
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
There are two types of platforms software-based and hardware-based. Java provides software-based platform.
1. Runtime Environment
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
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) 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
o Loads code
o Verifies code
o Executes code
o Memory area
o Register set
Classloader
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
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.
PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed.
Execution Engine
It contains:
1) A virtual processor
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.
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.
public class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
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
void is the return type of the method, it means it doesn't return any value.
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
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.
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.
byte
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
short
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.
int
Integer is generally used as the default data type for integral values unless there is a concern about memory.
long
Default value is 0L
Float is mainly used to save memory in large arrays of floating point numbers
Float data type is never used for precise values such as currency
double
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
boolean
This data type is used for simple flags that track true/false conditions
char
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.
1. import package.*;
2. import package.classname;
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();
}
}
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();
}
}
o fields
o methods
o constructors
o blocks
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
String getTitle()
return title;
int getPubYear()
return pubYear;
title = _title;
pubYear = _pubYear;
}
}
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 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:
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
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.
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:
in java.lang package.
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.
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);
}
}
1. By reference variable
2. By method
3. By constructor
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();
}
Object and Class Example: Employee
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;
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();
}
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;
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);
}
Output
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;
}
}
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
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.
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{
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
}
If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package.
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Acc w w o o
ess i i u u
Mo t t t t
P Y N N N
ri
D Y Y N N
lt
P Y Y Y N
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.
2. Parameterized 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.
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
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();
}
}
In this example, we have created the constructor of Student class that have two parameters. We can have any number of
class Student4{
int id;
String name;
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();
}
}
Difference between constructor and method in java
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.
The java compiler provides a default constructor if Method is not provided by compiler
Constructor name must be same as the class name. Method name may or may not be
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.
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.
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.
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...");}
}
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 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.
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
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();
}
}
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
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.
Output
The value of the variable named age in super class is: 24
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);
}
}
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
Shape Class Inheritance Example with Setters and Getters and Constructor Overloading
package javaapplication1;
/**
*/
public Shape(String n)
name=n;
this.name=name;
this.area=area;
this.perimeter=perimeter;
return name;
return area;
return perimeter;
package javaapplication1;
/**
*/
super(n);
length=l;
public Rectangle(String n)
super(n);
super(n);
length=l;
width=w;
If(l>0)
length=l;
else
If(w>0)
width=w;
else
return length;
return width;
super.setArea(getWidth()*getLength());
setPerimeter(2*(getWidth()+getLength()));
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());
package javaapplication1;
/**
*/
r.calculateArea();
r.calculatePerimeter();
r.display();
r1.setWidth(20);
r1.calculateArea();
r1.calculatePerimeter();
r1.display();
}
Problem Statement
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
Output
POWER ON
----------------------
Channel: 2
Volume: 5
----------------------
Channel up: +
Channel down: -
Volume up: ++
Volume down: --
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;
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.
2. Interface (100%)
1. abstract class A{}
abstract method
A method that is declared as abstract and does not have implementation is known as 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();
}
}
1. calculateArea
2. calculatePerimeter
package javaapplication1;
/**
*/
public Shape(String n)
this.name=name;
this.area=area;
this.perimeter=perimeter;
return name;
return area;
return perimeter;
package javaapplication1;
/**
super(n);
length=l;
public Rectangle(String n)
super(n);
super(n);
length=l;
width=w;
if(l>0)
length=l;
else
if(w>0)
width=w;
else
return length;
return width;
super.setArea(getWidth()*getLength());
setPerimeter(2*(getWidth()+getLength()));
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());
package javaapplication1;
import java.util.*;
/**
*/
super(n);
radius=r;
public Circle(String n)
super(n);
if(r>0)
radius=r;
else
return radius;
setArea(3.145*getRadius()*getRadius());
setPerimeter(2*3.15*getRadius());
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());
package javaapplication1;
/**
*/
r.calculateArea();
r.calculatePerimeter();
r.display();
c.calculateArea();
c.calculatePerimeter();
c.display();
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.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
obj.run();
}
}//end of class
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();
}
}
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();
class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}
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();
}
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.
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.
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);
}
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
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");
Emp e2=new Emp(112,"arun",address2);
e.display();
e2.display();
}
}
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;
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.
The java compiler adds public and abstract keywords before the interface method. More, it adds public, static and
final keywords before data members.
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
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.
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){
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.
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.
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();
}
}
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();
}
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();
}
@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 parentMethod()
horse.parentMethod();
animal.parentMethod();
}
}
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.
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.
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...");}
}
void eat(){System.out.println("dog is eating...");}
public static void main(String args[]){
Animal a=new Dog();
a.eat();
}
}
Polymorphism Example
package polymorphism;
this.name=name;
name=n;
return name;
if(a>0)
area=a;
else
System.out.println("Invalid area");
return area;
if(p>0)
peri=p;
else
System.out.println("Invalid perimeter");
return peri;
package polymorphism;
super(n);
radius=r;
if(r>0)
radius=r;
else
System.err.println("Invalid Radius");
return radius;
setArea(3.145*getRadius()*getRadius());
setPeri(2*3.145*getRadius());
System.out.println("Radius of Circle="+getRadius());
System.out.println("Area of Circle="+getArea());
System.out.println("Perimeter of Circle="+getPeri());
package polymorphism;
super(n);
side=s;
if(s>0)
side=s;
else
return side;
setArea(getSide()*getSide());
setPeri(4*getSide());
System.out.println("Radius of Square="+getSide());
System.out.println("Area of Square="+getArea());
System.out.println("Perimeter of Square="+getPeri());
package polymorphism;
Shape sh;
sh=s;
sh.calculateArea();
sh.calculatePeri();
sh.show();
sh=c;
sh.calculateArea();
sh.calculatePeri();
sh.show();
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.
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;
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.
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.
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.
Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
1. try
2. catch
3. finally
4. throw
5. throws
try{
//code that may throw exception
try{
//code that may throw exception
}finally{}
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...");
}
}
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...");
}
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 .
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.
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...
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
Note: If you don't handle exception, before terminating the program, JVM executes finally block(if any).
o Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.
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{
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...");
}
}
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).
1. throw new IOException("sorry device error”);
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
1. return_type method_name() throws exception_class_name{
2. //method code
3. }
o error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError or
StackOverflowError.
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.
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.
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{
}
}
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...
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
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
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.
exception.
only.
) instance.
) method. signature.
) exceptions. e.g.
IOException,SQLException.
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, subclass overridden method cannot
o If the superclass method declares an exception, subclass overridden method can declare same,
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");}
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
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.
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
import java.io.*;
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class TestExceptionChild3 extends Parent{
public static void main(String args[]){
Parent p=new TestExceptionChild3();
try{
p.msg();
}catch(Exception e){}
}
}
Output:child
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
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{
}catch(Exception e){}
}
}
Output:child
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
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.
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
2) public int available()throws returns an estimate of the number of bytes that can
3) public void close()throws IOException is used to close the current input stream.
InputStream Hierarchy
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
void write(int b) It is used to write the specified byte to the file output stream.
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.
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);}
}
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
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
protected void finalize() It is used to ensure that the close method is call when there is no more
import java.io.FileInputStream;
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
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
}catch(Exception e){System.out.println(e);}
}
}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);}
}
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
stream.
int size) used for writing the data to the specified output
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
package com.javatpoint;
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
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.
o When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the
1. public class BufferedInputStream extends FilterInputStream
Java BufferedInputStream class constructors
Constructor Description
int size) buffer size and saves it argument, the input stream IS,
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.
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
void close() It closes the input stream and releases any of the system resources associated
void reset() It repositions the stream at a position the mark method was last called on
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()
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);}
}
1. public class SequenceInputStream extends InputStream
Constructors of SequenceInputStream class
Constructor Description
InputStream s2) two input stream in order, first s1 and then s2.
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 available() It is used to return the maximum number of byte that can be read
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");
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..");
}
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();
}
}
1. public class FileWriter extends OutputStreamWriter
Constructors of FileWriter class
Constructor Description
FileWriter(File file) Creates a new file. It gets file name in File object.
Method Description
package com.javatpoint;
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
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
FileReader(File It gets filename in file instance. It opens the given file in read mode. If
Method Description
int read() It is used to return a character in ASCII form. It returns -1 at the end of file.
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;
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.
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
BufferedWriter(Writer wrt, int It is used to create a buffered character output stream that uses
Class methods
Method Description
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.
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
BufferedReader(Reader rd, int It is used to create a buffered character input stream that uses
Method Description
int read(char[] cbuf, int off, It is used for reading characters into a portion of an array.
int len)
boolean markSupported() It is used to test the input stream support for the mark and reset
method.
boolean ready() It is used to test whether the input stream is ready to be read.
void reset() It repositions the stream at a position the mark method was last called
readAheadLimit)
void close() It closes the input stream and releases any of the system resources
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
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: ");
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)
value.
void writeChar(int v) It is used to write char to the output stream as a 2-byte value.
characters.
void writeByte(int v) It is used to write a byte to the output stream as a 1-byte value.
bytes.
void writeUTF(String str) It is used to write a string to the output stream using UTF-8
Method Description
int read(byte[] b) It is used to read the number of bytes from the input stream.
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
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)
1. public class PrintStream extends FilterOutputStream implements Closeable. Appendable
Methods of PrintStream class
Method Description
the line.
void println(char c) It prints the specified char value and terminates the
line.
void println(int i) It prints the specified int value and terminates the
line.
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 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
void format(Locale l, Object format, It writes the formatted string to the current stream
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);
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
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
Output
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;
File Copied...
Java program to append text/string in a file
Example:
import java.io.*;
//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
import java.io.*;
}
}
Output
Serialization in Java
Serialization in java is a mechanism of writing the state of an object into a byte stream.
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
these classes may get certain capability. The Cloneable and Remote are also marker interfaces.
The String class and all the wrapper classes implements java.io.Serializable interface by default.
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
Important Methods
Method Description
IOException {}
IOException {} stream.
IOException {} stream.
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
1) public creates an
ObjectInputStream(InputStream ObjectInputStream
specified InputStream.
Important Methods
Method Description
ClassNotFoundException{}
IOException {} ObjectInputStream.
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
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.
If a class has a reference of another class, all the references must be Serializable otherwise serialization process will
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.
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;
}
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
The Externalizable interface provides the facility of writing the state of an object into a byte stream in compress
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
o is optional.
What is Collection framework
Collection framework represents a unified architecture for storing and manipulating group of objects. It has:
2. Algorithm
Do You Know ?
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 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?
invoking collection.
invoking collection.
specified collection.
contains(Object element)
3 equals(Object element)
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:
hasNext()
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.
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
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.
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.
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");
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.
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.
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.
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
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.
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.
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
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.
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.
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.
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.
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
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
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.
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.
Class Description
HashMap HashMap is the implementation of Map but it doesn't maintain any order.
TreeMap TreeMap is the implementation of Map and SortedMap, it maintains ascending order.
Method Description
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.
Method Description
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
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
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
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
13. Sorting
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
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 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.
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.
import java.awt.*;
class First2{
First2(){
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();
}}
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.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
1. Attach Relevant Listener to your class(Either by Inheritence / Outer Class / by Anonymous Class)
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 MenuItem
o TextField
o TextArea
o Checkbox
o Choice
o List
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{
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.
import java.awt.*;
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");
}
}
import java.awt.*;
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.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps
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);
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
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns
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");
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. 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
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:
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();
}
}
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
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.
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.
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);
}
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.
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:
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();
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new LabelExample();
}
}
Output:
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);
} }
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();
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:
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();
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:
Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special control for creating radio
buttons in AWT.
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:
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() {
String data = "Programming language Selected: "+ c.getItem(c.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String args[])
{
new ChoiceExample();
}
}
Output:
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);
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:
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();
}
Output:
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);
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:
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");
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:
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:
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);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
Output:
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.");
}
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
} }
Output:
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);
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:
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample2 extends Frame implements MouseListener{
MouseListenerExample2(){
addMouseListener(this);
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:
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;
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:
1. public abstract void keyPressed(KeyEvent e);
2. public abstract void keyReleased(KeyEvent e);
3. public abstract void keyTyped(KeyEvent e);
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) {
}
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:
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);
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:
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);
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) {
}
}
Output:
o By 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);
}
new WindowExample();
}
Output:
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(){
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.
) dependent. are platform-
independent.
) are heavyweight. are lightweight.
components such as
colorchooser, tabbedpane
etc.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications.
Do You Know
Method Description
height)
public void setLayout(LayoutManager sets the layout manager for the component.
m)
default false.
import javax.swing.*;
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
}
}
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.
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(Object[][] rows, Object[] columns) Creates a table with the specified data.
import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
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:
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) {
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.
1. public class JOptionPane extends JComponent implements Accessible
Constructor Description
message.
Methods Description
parentComponent, Object message, String title, int given title and messageType.
messageType)
parentComponent, Object message) Yes, No and Cancel; with the title, Select
an Option.
parented to parentComponent.
void setInputValue(Object newValue) It is used to set the input value that was
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:
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:
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:
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);
}
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:
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;
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();
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
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);
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();
}
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(int min, It is used to create a horizontal progress bar with the specified minimum
JProgressBar(int It is used to create a progress bar with the specified orientation, it can be
SwingConstants.HORIZONTAL constants.
JProgressBar(int It is used to create a progress bar with the specified orientation, minimum
max)
Method Description
setStringPainted(boolean b)
void setOrientation(int It is used to set the orientation, it may be either vertical or horizontal
SwingConstants.HORIZONTAL constants.
void setValue(int value) It is used to set the current value on the progress bar.
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:
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(Object[] Creates a JTree with every element of the specified array as the child of a
JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which displays the
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");
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
placement of JTabbedPane.Top.
placement.
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:
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
JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout manager.
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);
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
directory.
path.
currentDirectoryPath)
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();
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: