Java Notes 1
Java Notes 1
UNIT-I
Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop concepts, coping
with complexity, abstraction mechanisms. A way of viewing world – Agents, responsibility, messages,
methods, History of Java, Java buzzwords, data types, variables, scope and lifetime of variables, arrays,
operators, expressions, control statements, type conversion and casting, simple java program,
concepts of classes, objects, constructors, methods, access control, this keyword, garbage collection,
overloading methods and constructors, method binding, inheritance, overriding and exceptions,
parameter passing, recursion, nested and inner classes, exploring string class.
OBJECT ORIENTED THINKING
When computers were first invented, programming was done manually by toggling in a binary
machine instructions by use of front panel.
As programs began to grow, high level languages were introduced that gives the programmer more
tools to handle complexity.
The first widespread high level language is FORTRAN. Which gave birth to structured
programming in 1960’s. The Main problem with the high level language was they have no specific
structure and programs becomes larger, the problem of complexity also increases.
So C became the popular structured oriented language to solve all the above problems.
However in SOP, when project reaches certain size its complexity exceeds. So in 1980’s a new way
of programming was invented and it was OOP. OOP is a programming methodology that helps to
organize complex programs through the use of inheritance, encapsulation & polymorphism.
NEED FOR OOP PARADIGM
Traditionally, the structured programming techniques were used earlier.
There were many problems because of the use of structured programming technique.
The structured programming made use of a top-down approach.
To overcome these problems the object oriented programming concept was created.
The object oriented programming makes use of bottom-up approach.
It also manages the increasing complexity.
The description of an object-oriented program can be given as, a data that controls access to code.
The object-oriented programming technique builds a program using the objects along with a set of
well-defined interfaces to that object.
The object-oriented programming technique is a paradigm, as it describes the way in which
elements within a computer program must be organized.
It also describes how those elements should interact with each other.
In OOP, data and the functionality are combined into a single entity called an object.
Classes as well as objects carry specific functionality in order to perform operations and to achieve
the desired result.
The data and procedures are loosely coupled in procedural paradigm.
Whereas in OOP paradigm, the data and methods are tightly coupled to form objects.
These objects helps to build structure models of the problem domain and enables to get effective
solutions.
OOP uses various principles (or) concepts such as abstraction, inheritance, encapsulation and
polymorphism. With the help of abstraction, the implementation is hidden and the functionality is
exposed.
Use of inheritance can eliminate redundant code in a program. Encapsulation enables the data and
methods to wrap into a single entity. Polymorphism enables the reuse of both code and design.
SUMMARY OF OOP CONCEPTS
Everything is an object.
Computation is performed by objects communicating with each other, requesting that other objects
perform actions. Objects communicate by sending & receiving messages. A message is a request for
an action bundled with whatever arguments may be necessary to complete the task.
Each object has its own memory, which consists of other objects.
Every Object is an instance of class. A class simply represents a grouping of similar objects, such as
integers or lists.
The class is the repository for behavior associated with an object. That is all objects that are
instances of same class can perform the same actions.
Classes are organized into a singly rooted tree structure, called inheritance hierarchy.
OOP CONCEPTS
OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which every
program is follows the concept of object. In other words, OOP is a way of writing programs based on
the object concept.
The object-oriented programming paradigm has the following core concepts.
Class
Object
Encapsulation
Inheritance
Polymorphism
Abstraction
Class
Class is a blue print which is containing only list of variables and methods and no memory is allocated
for them. A class is a group of objects that has common properties.
Object
Any entity that has state and behavior is known as an object.
For example a chair, pen, table, keyboard, bike, etc. It can be physical or logical. An Object can
be defined as an instance of a class.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Encapsulation
Encapsulation is the process of combining data and code into a single unit.
In OOP, every object is associated with its data and code.
In programming, data is defined as variables and code is defined as methods.
The java programming language uses the class concept to implement encapsulation.
Inheritance
Inheritance is the process of acquiring properties and behaviors from one object to another
object or one class to another class.
In inheritance, we derive a new class from the existing class. Here, the new class acquires the
properties and behaviors from the existing class.
In the inheritance concept, the class which provides properties is called as parent class and the
class which recieves the properties is called as child class.
Person
name,
designation
learn(),
walk(),
eat()
Abstraction
Abstraction is hiding the internal details and showing only essential functionality.
In the abstraction concept, we do not show the actual implementation to the end user, instead
we provide only essential things.
For example, if we want to drive a car, we does not need to know about the internal
functionality like how wheel system works? how brake system works? how music system
works? etc.
COPING WITH COMPLEXITY
Coping with complexity in Java, or any programming language, is an essential skill for software
developers.
As your Java projects grow in size and complexity, maintaining, debugging, and extending your
code can become challenging.
Here are some strategies to help you cope with complexity in Java:
1. Modularization: Breaking down the code into smaller, self-contained modules, classes, or
packages to manage complexity. Each module should have a specific responsibility and interact
with others through well-defined interfaces.
2. Design Patterns: Using established design patterns to solve common architectural and design
problems. Design patterns provide proven solutions to recurring challenges in software
development.
3. Encapsulation: Restricting access to class members using access modifiers (public, private,
protected) to hide implementation details and provide a clear API for interacting with the class.
4. Abstraction: Creating abstract classes and interfaces to define contracts that classes must adhere
to, making it easier to work with different implementations.
5. Documentation: Writing comprehensive documentation, including code comments and Javadoc, to
explain how the code works, its purpose, and how to use it.
6. Testing: Implementing unit tests to ensure that individual components of the code function
correctly, which helps identify and prevent bugs.
7. Code Reviews: Collaborating with team members to review and provide feedback on code to catch
issues and ensure code quality.
8. Version Control: Using version control systems like Git to manage changes, track history, and
collaborate with others effectively.
9. Refactoring: Regularly improving and simplifying the codebase by removing redundancy and
improving its structure.
ABSTRACTION MECHANISM
In Java, abstraction is a fundamental concept in object-oriented programming that allows you to
hide complex implementation details while exposing a simplified and well-defined interface.
Abstraction mechanisms in Java include the use of abstract classes and interfaces.
A WAY OF VIEWING WORLD
A way of viewing the world is an idea to illustrate the object-oriented programming concept with
an example of a real-world situation.
Let us consider a situation, I am at my office and I wish to get food to my family members who are
at my home from a hotel. Because of the distance from my office to home, there is no possibility of
getting food from a hotel myself. So, how do we solve the issue?
To solve the problem, let me call zomato (an agent in food delevery community), tell them the
variety and quantity of food and the hotel name from which I wish to delever the food to my family
members.
AGENTS AND COMMUNITIES
Let us consider a situation, I am at my office and I wish to get food to my family members who are at
my home from a hotel. Because of the distance from my office to home, there is no possibility of getting
food from a hotel myself. So, how do we solve the issue?
To solve the problem, let me call zomato (an agent in food delevery community), tell them the
variety and quantity of food and the hotel name from which I wish to delever the food to my family
members. An object-oriented program is structured as a community of interacting agents, called
objects. Where each object provides a service (data and methods) that is used by other
members of the community.
In our example, the online food delivery system is a community in which the agents are zomato
and set of hotels. Each hotel provides a variety of services that can be used by other members like
zomato, myself, and my family in the community.
RESPONSIBILITIES
In object-oriented programming, behaviors of an object described in terms of responsibilities.
In our example, my request for action indicates only the desired outcome (food delivered to my
family). The agent (zomato) free to use any technique that solves my problem. By discussing a problem
in terms of responsibilities increases the level of abstraction. This enables more independence
between the objects in solving complex problems.
MESSAGES & METHODS
To solve my problem, I started with a request to the agent zomato, which led to still more requestes
among the members of the community until my request has done. Here, the members of a community
interact with one another by making requests until the problem has satisfied.
-9223372036854775808 to
long 8 bytes 0L
+9223372036854775807
Float Data Types
Float data types are represent numbers with decimal point.
Minimum and Maximum
Data Type Memory Size Default Value
values
Note: Float data type can represent up to 7 digits accurately after decimal point.
Double data type can represent up to 15 digits accurately after decimal point.
Character Data Type
Character data type are represents a single character like a, P, &, *,..etc.
Minimum and Maximum
Data Type Memory Size Default Value
values
Local Variables
Variables declared inside the methods or constructors or blocks are called as local variables.
The scope of local variables is within that particular method or constructor or block in which they
have been declared.
Local variables are allocated memory when the method or constructor or block in which they are
declared is invoked and memory is released after that particular method or constructor or block is
executed.
Access modifiers cannot be assigned to local variables.
It can’t be defined by a static keyword.
Local variables can be accessed directly with their name.
Program
class LocalVariables
{
public void show()
{
int a = 10;
System.out.println("Inside show method, a = " + a);
}
public void display()
{
int b = 20;
System.out.println("Inside display method, b = " + b);
//System.out.println("Inside display method, a = " + a); // error
}
public static void main(String args[])
{
LocalVariables obj = new LocalVariables();
obj.show();
obj.display();
}
}
Instance Variables:
Variables declared outside the methods or constructors or blocks but inside the class are called
as instance variables.
The scope of instance variables is inside the class and therefore all methods, constructors and
blocks can access them.
Instance variables are allocated memory during object creation and memory is released during
object destruction. If no object is created, then no memory is allocated.
For each object, a separate copy of instance variable is created.
Heap memory is allocated for storing instance variables.
Access modifiers can be assigned to instance variables.
It is the responsibility of the JVM to assign default value to the instance variables as per the type of
Variable.
Instance variables can be called directly inside the instance area.
Instance variables cannot be called directly inside the static area and necessarily requires an object
reference for calling them.
Program
class InstanceVariable
{
int x = 100;
public void show()
{
System.out.println("Inside show method, x = " + x);
x = x + 100;
}
public void display()
{
System.out.println("Inside display method, x = " + x);
}
public static void main(String args[])
{
ClassVariables obj = new ClassVariables();
obj.show();
obj.display();
}
}
Static variables
Static variables are also known as class variable.
Static variables are declared with the keyword ‘static ‘ .
A static variable is a variable whose single copy in memory is shared by all the objects, any
modification to it will also effect other objects.
Static keyword in java is used for memory management, i.e it saves memory.
Static variables gets memory only once in the class area at the time of class loading.
Static variables can be invoked without the need for creating an instance of a class.
Static variables contain values by default. For integers, the default value is 0. For Booleans, it is
false. And for object references, it is null.
Syntax: static datatype variable name;
Example: static int x=100;
Syntax: classname.variablename;
Example
class Employee
{
static int empid=500;
static void emp1()
{
empid++;
System.out.println("Employee id:"+empid);
}
}
class Sample
{
public static void main(String args[])
{
Employee.emp1();
Employee.emp1();
Employee.emp1();
Employee.emp1();
Employee.emp1();
Employee.emp1();
}
}
ARRAYS
An array is a collection of similar data values with a single name.
An array can also be defined as, a special type of variable that holds multiple values of the same
data type at a time.
In java, arrays are objects and they are created dynamically using new operator.
Every array in java is organized using index values.
The index value of an array starts with '0' and ends with 'zise-1'.
We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
One Dimensional Array
Multi Dimensional Array
One Dimensional Array
In the java programming language, an array must be created using new operator and with a specific
size. The size must be an integer value but not a byte, short, or long. We use the following syntax to
create an array.
Syntax
data_type array_name[ ] = new data_type[size];
(or)
data_type[ ] array_name = new data_type[size];
Example
class Onedarray
{
public static void main(String args[])
{
int a[]=new int[5];
a[0]=10;
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
for(int i=0;i<5;i++)
System.out.println(a[i]);
}
}
In java, an array can also be initialized at the time of its declaration.
When an array is initialized at the time of its declaration, it need not specify the size of the array
and use of the new operator.
Here, the size is automatically decided based on the number of values that are initialized.
Example
int list[ ] = {10, 20, 30, 40, 50};
Multidimensional Array
In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-
dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays.
To create a multidimensional array variable, specify each additional index using another set of
square brackets.
Syntax
data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
data_type[ ][ ] array_name = new data_type[rows][columns];
When an array is initialized at the time of declaration, it need not specify the size of the array and
use of the new operator.
Here, the size is automatically decided based on the number of values that are initialized.
Example
class Twodarray
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
OPERATORS
An operator is a symbol that performs an operation. An operator acts on some variables called
operands to get the desired result.
Example: a+b
Here a, b are operands and + is operator.
Types of Operators
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment or Decrement operators
6. Conditional operator
7. Bit wise operators
1. Arithmetic Operators: Arithmetic Operators are used for mathematical calculations.
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modular
Operator Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
2. Logical OR ( || ) : Logical OR is denoted by double pipe characters (||). it is used to check the
combinations of more than one conditions. if any one condition true the complete condition becomes
true.
Truth table of Logical OR
Condition1 Condition2 Condition1 && Condition2
True True True
True False True
False True True
False False False
3. Logician NOT (!): Logical NOT is denoted by exclamatory characters (!), it is used to check the
opposite result of any given test condition. i.e, it makes a true condition false and false condition true.
Truth table of Logical NOT
Condition1 !Condition2
True False
False True
Operator Meaning
0 0 0
0 1 0
1 0 0
1 1 1
0 0 0
0 1 1
1 0 1
1 1 1
Example : int x = 10;
int y = 20;
x|y=?
x = 0000 1010
y = 0000 1011
x | y = 0000 1011 = 11
3. Bitwise Exclusive OR :
The XOR operator is denoted by a carrot (^) symbol.
It takes two values and returns true if they are different; otherwise returns false.
In binary, the true is represented by 1 and false is represented by 0.
Truth table of Bitwise XOR
Condition1 Condition2 Condition1 ^ Condition2
0 0 0
0 1 1
1 0 1
1 1 0
Example
ab+
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Example
+ab
CONTROL STATEMENTS
In java, the default execution flow of a program is a sequential order.
But the sequential order of execution flow may not be suitable for all situations.
Sometimes, we may want to jump from line to another line, we may want to skip a part of the
program, or sometimes we may want to execute a part of the program again and again.
To solve this problem, java provides control statements.
Types of Control Statements
If only one statement is being repeated, there is no need for the curly braces.
In for-statement, the execution begins with the initialization statement. After the initialization
statement, it executes Condition. If the condition is evaluated to true, then the block of statements
executed otherwise it terminates the for-statement. After the block of statements execution,
the modification statement gets executed, followed by condition again.
Example
public class ForTest
{
public static void main(String[] args)
{
for(int i = 0; i < 10; i++)
{
System.out.println("i = " + i);
}
System.out.println("Statement after for!");
}
}
3. Jump Statements
The java programming language supports jump statements that used to transfer execution control
from one line to another line.
The java programming language provides the following jump statements.
1. break statement
2. continue statement
break
When a break statement is encountered inside a loop, the loop is terminated and program control
resumes at the next statement following the loop.
Example
class BreakStatement
{
public static void main(String args[] )
{
int i;
i=1;
while(true)
{
if(i >10)
break;
System.out.print(i+" ");
i++;
}
}
}
Continue
This command skips the whole body of the loop and executes the loop with the next iteration. On
finding continue command, control leaves the rest of the statements in the loop and goes back to the
top of the loop to execute it with the next iteration (value).
Example
/* Print Number from 1 to 10 Except 5 */
class NumberExcept
{
public static void main(String args[] )
{
int i;
for(i=1;i<=10;i++)
{
if(i==5)
continue;
System.out.print(i +" ");
}
}
}
TYPE CONVERSION AND CASTING
Type Casting
When a data type is converted into another data type by a programmer using the casting operator
while writing a program code, the mechanism is known as type casting.
In typing casting, the destination data type may be smaller than the source data type when
converting the data type to another data type, that’s why it is also called narrowing conversion.
Syntax
destination_datatype = (target_datatype)variable;
Output
Before conversion: 166.66
After conversion into int type: 166
Type Conversion
If a data type is automatically converted into another data type at compile time is known as type
conversion.
The conversion is performed by the compiler if both data types are compatible with each other.
Remember that the destination data type should not be smaller than the source type.
It is also known as widening conversion of the data type.
Example
int a = 20;
Float b;
b = a; // Now the value of variable b is 20.000
Program
Output :
After conversion, the float value is: 7.0
STRUCTURE OF JAVA PROGRAM
Structure of a Java program contains the following elements:
Documentation Section
The documentation section is an important section but optional for a Java program.
It includes basic information about a Java program. The information includes the author's name,
date of creation, version, program name, company name, and description of the program. It
improves the readability of the program. Whatever we write in the documentation section, the Java
compiler ignores the statements during the execution of the program. To write the statements in the
documentation section, we use comments.
Comments there are three types
1. Single-line Comment: It starts with a pair of forwarding slash (//).
2. Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols.
Example : /* It is an example of
multiline comment */
3. Documentation Comment: It starts with the delimiter (/**) and ends with */.
SAMPLE JAVA PROGRAM
/* This is First Java Program */
Class sample
{
public static void main(String args[])
{
System.out.println(“Hello Java Programming”);
}
}
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility. It means it is visible to all.
static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static method.
The main method is executed by the JVM, so it doesn't require to create an object to invoke the main
method. So it saves memory.
void is the return type of the method. It means it doesn't return any value.
main represents the starting point of the program execution
String[] args is used for command line argument.
System.out.println() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class.
How to Compile and Run the Java Program
To Compile : javac Sample.java [ program name]
To Run : java Sample
Output : Hello Java Programming
EXECUTION PROCESS OF JAVA PROGRAM
WHAT IS JVM
Java Virtual Machine is the heart of entire java program execution process. It is responsible for taking
the .class file and converting each byte code instruction into the machine language instruction that can
be executed by the microprocessor.
CLASSES AND OBJECTS IN JAVA
CLASSES
In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are
used to represent real-world concepts and entities.
classes usually consist of two things: instance variables and methods.
The class represents a group of objects having similar properties and behavior.
For example, the animal type Dog is a class while a particular dog named Tommy is an object of
the Dog class.
It is a user-defined blueprint or prototype from which objects are created. For example, Student is
a class while a particular student named Ravi is an object.
The java class is a template of an object.
Every class in java forms a new data type.
Once a class got created, we can generate as many objects as we want.
Class Characteristics
Identity - It is the name given to the class.
State - Represents data values that are associated with an object.
Behavior - Represents actions can be performed by an object.
Properties of Java Classes
1. Class is not a real-world entity. It is just a template or blueprint or prototype from which objects
are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of methods.
4. A Class in Java can contain:
Data member
Method
Constructor
Nested Class
Interface
Creating a Class
In java, we use the keyword class to create a class. A class in java contains properties as variables and
behaviors as methods.
Syntax
class className
{
data members declaration;
methods definition;
}
The ClassName must begin with an alphabet, and the Upper-case letter is preferred.
The ClassName must follow all naming rules.
Example
Here is a class called Box that defines three instance variables: width, height, and depth.
class Box
{
double width;
double height;
double depth;
void volume()
{
………………….
}
}
OBJECT
In java, an object is an instance of a class.
Objects are the instances of a class that are created to use the attributes and methods of a class.
All the objects that are created using a single class have the same properties and methods. But the
value of properties is different for every object.
Syntax
ClassName objectName = new ClassName( );
The objectName must begin with an alphabet, and a Lower-case letter is preferred.
The objectName must follow all naming rules.
Example
Box mybox = new Box();
The new operator dynamically allocates memory for an object.
Example
class Box
{
double width;
double height;
double depth;
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
METHODS
A method is a block of statements under a name that gets executes only when it is called.
Every method is used to perform a specific task. The major advantage of methods is code re-
usability (define the code once, and use it many times).
In a java programming language, a method defined as a behavior of an object. That means, every
method in java must belong to a class.
Every method in java must be declared inside a class.
Every method declaration has the following characteristics.
returnType - Specifies the data type of a return value.
name - Specifies a unique name to identify it.
parameters - The data values it may accept or recieve.
{ } - Defienes the block belongs to the method.
Creating a method
A method is created inside the class
Syntax
class ClassName
{
returnType methodName( parameters )
{
// body of method
}
}
Calling a method
In java, a method call precedes with the object name of the class to which it belongs and a dot
operator.
It may call directly if the method defined with the static modifier.
Every method call must be made, as to the method name with parentheses (), and it must
terminate with a semicolon.
Syntax
objectName.methodName(actualArguments );
Example
//Adding a Method to the Box Class
Class Box
{
double width, height, depth;
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
mybox1.volume();
mybox2.volume();
}
}
CONSTRUCTORS
Constructor in Java is a special member method which will be called automatically by the JVM
whenever an object is created for placing user defined values in place of default values.
In a single word constructor is a special member method which will be called automatically
whenever object is created.
The purpose of constructor is to initialize an object called object initialization. Initialization is a
process of assigning user defined values at the time of allocation of memory space.
Syntax
ClassName()
{
.......
.......
}
Types Of Constructors
Based on creating objects in Java constructor are classified in two types. They are
1. Default or no argument Constructor
2. Parameterized constructor
1. Default Constructor
A constructor is said to be default constructor if and only if it never take any parameters.
If any class does not contain at least one user defined constructor then the system will create a
default constructor at the time of compilation it is known as system defined default constructor.
Note: System defined default constructor is created by java compiler and does not have any statement
in the body part. This constructor will be executed every time whenever an object is created if that
class does not contain any user defined constructor.
Example
class Test
{
int a, b;
Test()
{
a=10;
b=20;
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
}
}
class TestDemo
{
public static void main(String args[])
{
Test t1=new Test();
}
}
2. Parameterized Constructor
If any constructor contain list of variables in its signature is known as paremetrized constructor. A
parameterized constructor is one which takes some parameters.
Example
class Test
{
int a, b;
Test(int n1, int n2)
{
a=n1;
b=n2;
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
}
class TestDemo
{
public static void main(String args[])
{
Test t1=new Test(10, 20);
}
}
ACCESS CONTROL(MEMBER ACCESS)
In Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or data
member. It provides security, accessibility, etc to the user depending upon the access modifier used
with the element.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
1. Default Access Modifier
When no access modifier is specified for a class, method, or data member – It is said to be having
the default access modifier by default.
The default modifier is accessible only within package.
It cannot be accessed from outside the package.
It provides more accessibility than private. But, it is more restrictive than protected, and public.
Example
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A
{
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(); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.
2. Private
The private access modifier is accessible only within the class.
The private access modifier is specified using the keyword private.
The methods or data members declared as private are accessible only within the class in which
they are declared.
Any other class of the same package will not be able to access these members.
Top-level classes or interfaces can not be declared as private because private means “only visible
within the enclosing class”.
Example
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 a compile-time error.
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
3. Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier is specified using the keyword protected.
Example
In this example, we have created the two packages pack and mypack.
The A class of pack package is public, so can be accessed from outside the package.
But msg method of this package is declared as protected, so it can be accessed from outside the
class only through inheritance.
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
4. Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
The public access modifier is specified using the keyword public.
Example
//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();
}
}
3. By anonymous object:
1. new Employee();
OVERLOADING METHODS AND CONSTRUCTORS
OVERLOADING METHODS
Whenever same method name is exiting multiple times in the same class with different number of
parameter or different order of parameters or different types of parameters is known as method
overloading.
Method overloading in Java is also known as Compile-time Polymorphism, Static Polymorphism,
or Early binding.
Example
class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
void sum(float a, float b)
{
System.out.println(a+b);
}
}
class Methodload
{
public static void main(String args[])
{
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10, 20, 30);
obj.sum(10.05f, 15.20f);
}
}
OVERLOADING CONSTRUCTORS
Constructor overloading is a concept of having more than one constructor with different parameters
list, so that each constructor performs a different task.
Example
1. A class is created, but its name is decided by the compiler, which extends the Person class and
provides the implementation of the eat() method.
2. An object of the Anonymous class is created that is referred to by 'p,' a reference variable of Person
type.
3. LOCAL INNER CLASS
A class i.e. created inside a method is called local inner class in java.
If you want to invoke the methods of local inner class, you must instantiate this class inside the
method.
Example
public class localInner
{
private int data=30;
void display()
{
class Local
{
void msg()
{
System.out.println(data);
}
}
Local l=new Local();
l.msg();
}
public static void main(String args[])
{
localInner obj=new localInner();
obj.display();
}
}
4. STATIC NESTED CLASS
A static class i.e. created inside a class is called static nested class in java. It cannot access non-
static data members and methods. It can be accessed by outer class name.
It can access static data members of outer class including private.
Static nested class cannot access non-static (instance) data member or method.
Example
class TestOuter
{
static int data=30;
static class Inner
{
void msg()
{
System.out.println("data is "+data);
}
}
public static void main(String args[])
{
TestOuter.Inner obj=new TestOuter.Inner();
obj.msg();
}
}
In this example, you need to create the instance of static nested class because it has instance method
msg(). But you don't need to create the object of Outer class because nested class is static and static
properties, methods or classes can be accessed without object.
EXPLORING STRING CLASS
A string is a sequence of characters surrounded by double quotations. In a java programming
language, a string is the object of a built-in class String.
The string created using the String class can be extended. It allows us to add more characters after
its definition, and also it can be modified.
Example
String siteName = "javaprogramming";
siteName = "javaprogramminglanguage";
String handling methods
In java programming language, the String class contains various methods that can be used to handle
string data values.
The following table depicts all built-in methods of String class in java.
S.No Method Description
1 charAt(int) Finds the character at given index
2 length() Finds the length of given string
3 compareTo(String) Compares two strings
4 compareToIgnoreCase(String) Compares two strings, ignoring case
5 concat(String) Concatenates the object string with argument string.
6 contains(String) Checks whether a string contains sub-string
7 contentEquals(String) Checks whether two strings are same
8 equals(String) Checks whether two strings are same
9 equalsIgnoreCase(String) Checks whether two strings are same, ignoring case
10 startsWith(String) Checks whether a string starts with the specified string
11 isEmpty() Checks whether a string is empty or not
12 replace(String, String) Replaces the first string with second string
Replaces the first string with second string at all
replaceAll(String, String)
13 occurrences.
Extracts a sub-string from specified start and end index
substring(int, int)
14 values
15 toLowerCase() Converts a string to lower case letters
16 toUpperCase() Converts a string to upper case letters
17 trim() Removes whitespace from both ends
18 toString(int) Converts the value to a String object
Example
public class JavaStringExample
{
public static void main(String[] args)
{
String title = "Java Programming";
String siteName = "String Handling Methods";
System.out.println("Length of title: " + title.length());
System.out.println("Char at index 3: " + title.charAt(3));
System.out.println("Index of 'T': " + title.indexOf('T'));
System.out.println("Empty: " + title.isEmpty());
System.out.println("Equals: " + siteName.equals(title));
System.out.println("Sub-string: " + siteName.substring(9, 14));
System.out.println("Upper case: " + siteName.toUpperCase());
}
}
UNIT – II
Inheritance, Packages and Interfaces – Hierarchical abstractions, Base class object, subclass, subtype,
substitutability, forms of inheritance specialization, specification, construction, extension, limitation,
combination, benefits of inheritance, costs of inheritance. Member access rules, super uses, using final
with inheritance, polymorphism- method overriding, abstract classes, the Object class. Defining, Creating
and Accessing a Package, Understanding CLASSPATH, importing packages, differences between classes
and interfaces, defining an interface, implementing interface, applying interfaces, variables in interface
and extending interfaces. Exploring java.io.
INHERITANCE IN JAVA
Inheritance is an important pillar of OOP(Object-Oriented Programming).
The process of obtaining the data members and methods from one class to another class is known
as inheritance.
Important Terminologies Used in Java Inheritance
Super Class/Parent Class: The class whose features are inherited is known as a superclass(or a base
class or a parent class).
Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition to the
superclass fields and methods.
Why Do We Need Java Inheritance?
Code Reusability: The code written in the Superclass is common to all subclasses. Child classes can
directly use the parent class code.
Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the ways by
which Java achieves Run Time Polymorphism.
Abstraction: The concept of abstract where we do not have to provide all details is achieved through
inheritance. Abstraction only shows the functionality to the user.
How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java.
Using the extends keyword indicates you are derived from an existing class. In other words, “extends”
refers to increased functionality.
Syntax
class SubclassName extends SuperclassName
{
//methods and fields
}
TYPES OF INHERITANCE
Based on number of ways inheriting the feature of base class into derived class we have five types of
inheritance they are:
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid inheritance
1.Single inheritance
In single inheritance there exists single base class and single derived class.
Example
class Animal
{
String name;
void show()
{
System.out.println(“Animal name is:"+name);
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Barking");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.name="DOG";
d.show();
d.bark();
}
}
2. Multilevel inheritances in Java
When there is a chain of inheritance, it is known as multilevel inheritance.
In Multilevel inheritances there exists single base class, single derived class and multiple intermediate
base classes.
Example
In the example, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a
multilevel inheritance.
class Animal
{
String name;
void show()
{
System.out.println("Animal Name is"+name);
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Mother Dog Barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
System.out.println("Baby Dog weeping");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.name="MotherDog";
d.show();
d.bark();
d.weep();
}
}
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In
the below image, class A serves as a base class for the derived class B, C and D.
Example
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
}
}
4. Multiple inheritance
In multiple inheritance there exist multiple classes and single derived class.
The concept of multiple inheritance is not supported in java through concept of classes but it can be
supported through the concept of interface.
5. Hybrid inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t support multiple
inheritances with classes, hybrid inheritance is also not possible with classes. In Java, we can achieve
hybrid inheritance only through Interfaces.
SUBSTITUTABILITY
The inheritance concept used for the number of purposes in the java programming language. One of
the main purposes is substitutability.
The substitutability means that when a child class acquires properties from its parent class, the object
of the parent class may be substituted with the child class object.
For example, if B is a child class of A, anywhere we expect an instance of A we can use an instance of
B.
The substitutability can achieve using inheritance, whether using extends or implements keywords.
FORMS OF INHERITANCE
The following are the different forms of inheritance in java.
Specialization
Specification
Construction
Extension
Limitation
Combination
Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent class. It holds the
principle of substitutability.
Specification
This is another commonly used form of inheritance. In this form of inheritance, the parent class just
specifies which methods should be available to the child class but doesn't implement them. The java
provides concepts like abstract and interfaces to support this form of inheritance. It holds the principle
of substitutability.
Construction
This is another form of inheritance where the child class may change the behavior defined by the parent
class (overriding). It does not hold the principle of substitutability.
Extension
This is another form of inheritance where the child class may add its new properties. It holds the principle
of substitutability.
Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It does not hold
the principle of substitutability.
Combination
This is another form of inheritance where the subclass inherits properties from multiple parent classes.
Java does not support multiple inheritance type.
BENEFITS OF INHERITANCE
Inheritance helps in code reuse. The child class may use the code defined in the parent class without
re-writing it.
Inheritance can save time and effort as the main code need not be written again.
Inheritance provides a clear model structure which is easy to understand.
An inheritance leads to less development and maintenance costs.
With inheritance, we will be able to override the methods of the base class so that the meaningful
implementation of the base class method can be designed in the derived class. An inheritance leads
to less development and maintenance costs.
In inheritance base class can decide to keep some data private so that it cannot be altered by the
derived class.
THE COSTS OF INHERITANCE
Inheritance decreases the execution speed due to the increased time and effort it takes, the program
to jump through all the levels of overloaded classes.
Inheritance makes the two classes (base and inherited class) get tightly coupled. This means one
cannot be used independently of each other.
The changes made in the parent class will affect the behavior of child class too.
The overuse of inheritance makes the program more complex.
ACCESS CONTROL(MEMBER ACCESS)
In Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or data
member. It provides security, accessibility, etc to the user depending upon the access modifier used with
the element.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
1. Default Access Modifier
When no access modifier is specified for a class, method, or data member – It is said to be having
the default access modifier by default.
The default modifier is accessible only within package.
It cannot be accessed from outside the package.
It provides more accessibility than private. But, it is more restrictive than protected, and public.
Example
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A
{
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(); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from
outside the package.
2. private
The private access modifier is accessible only within the class.
The private access modifier is specified using the keyword private.
The methods or data members declared as private are accessible only within the class in which
they are declared.
Any other class of the same package will not be able to access these members.
Top-level classes or interfaces can not be declared as private because private means “only visible
within the enclosing class”.
Example
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 a compile-time error.
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
4. public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
The public access modifier is specified using the keyword public.
Example
//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();
}
}
Table: class member access
Let's understand the access modifiers in Java by a simple table.
Private YES NO NO NO
Return
Method Description
Value
hashCode() returns the hashcode number for object being used. int
notifyAll() wakes up all the threads, waiting on invoking object's monitor. void
wait() causes the current thread to wait, until another thread notifies. void
wait(long,int) causes the current thread to wait for the specified milliseconds void
and nanoseconds, until another thread notifies.
Example
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
A obj = new A();
obj.print();
obj.show();
}
}
STREAM BASED I/O (JAVA.IO)
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.
We can perform file handling in Java by Java I/O API.
STREAM
In Java, streams are the sequence of data that are read from the source and written to the destination.
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
1. System.in: This is the standard input stream that is used to read characters from the keyboard or
any other standard input device.
2. System.out: This is the standard output stream that is used to produce the result of a program on
an output device like the computer screen.
3. System.err: This is the standard error stream that is used to output all the error data that a
program might throw, on a computer screen or any standard output device.
TYPES OF STREAMS
Depending on the type of operations, streams can be divided into two primary classes:
InPutStream − The InputStream is used to read data from a source.
read(char[] array) - reads the characters from the stream and stores in the specified array
read(char[] array, int start, int length) - reads the number of characters equal to length from the
stream and stores in the specified array starting from the start
mark() - marks the position in the stream up to which data has been read
reset() - returns the control to the point in the stream where the mark is set
skip() - discards the specified number of characters from the stream
Writer Class
The Writer class of the java.io package is an abstract super class that represents a stream of
characters.
Since Writer is an abstract class, it is not useful by itself. However, its subclasses can be used to write
data.
Subclasses of Writer
Stream class Description
BufferedWriter Handles buffered output stream.
FileWriter Output stream that writes to file.
PrintWriter Output Stream that contain print() and println() method.
Methods of Writer
The Writer class provides different methods that are implemented by its subclasses. Here are
some of the methods:
write(char[] array) - writes the characters from the specified array to the output stream
write(String data) - writes the specified string to the writer
append(char c) - inserts the specified character to the current writer
flush() - forces to write all the data present in the writer to the corresponding destination
close() - closes the writer
READING CONSOLE INPUT
There are times when it is important for you to get input from users for execution of programs. To do this
you need Java Reading Console Input Methods.
Java Reading Console Input Methods
1. Using BufferedReader Class
2. Using Scanner Class
3. Using Console Class
1. Using BufferedReader Class
Reading input data using the BufferedReader class is the traditional technique. This way of the
reading method is used by wrapping the System.in (standard input stream) in
an InputStreamReader which is wrapped in a BufferedReader, we can read input from the console.
The BufferedReader class has defined in the java.io package.
We can use read() method in BufferedReader to read a character.
int read() throws IOException
Reading Console Input Characters Example:
import java.io.*;
class ReadingConsoleInputTest
{
public static void main(String args[])
{
char ch;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, char 'x' to exit.");
do
{
ch = (char) br.read();
System.out.println(ch);
} while(ch != 'x');
}
}
How to read a string input in java?
readLine() method is used to read the string in the BufferedReader.
Program to take String input from Keyboard in Java
import java.io.*;
class MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}
2. Using the Scanner Class
Scanner is one of the predefined class which is used for reading the data dynamically from the keyboard.
Import Scanner Class in Java
java.util.Scanner
Constructor of Scanner Class
Scanner(InputStream)
This constructor create an object of Scanner class by talking an object of InputStream class. An object of
InputStream class is called in which is created as a static data member in the System class.
Syntax of Scanner Class in Java
Scanner sc=new Scanner(System.in);
Here the object 'in' is use the control of keyboard
}
WRITING CONSOLE OUTPUT
print and println methods in System.out are mostly used for console output.
These methods are defined by the class PrintStream which is the type of object referenced by
System.out.
System.out is the byte stream.
PrintStream is the output derived from OutputStream. write method is also defined in PrintStream
for console output.
void write(int byteval)
//Java code to Write a character in Console Output
import java.io.*;
class WriteCharacterTest
{
public static void main(String args[])
{
int byteval;
byteval = 'J';
System.out.write(byteval);
System.out.write('\n');
}
}
UNIT - III
Exception handling and Multithreading - Concepts of exception handling, benefits of exception handling,
Termination or resumptive models, exception hierarchy, usage of try, catch, throw, throws and finally,
built in exceptions, creating own exception subclasses. String handling, Exploring java.util. Differences
between multithreading and multitasking, thread life cycle, creating threads, thread priorities,
synchronizing threads, inter thread communication, thread groups, daemon threads. Enumerations,
autoboxing, annotations, generics.
CONCEPTS OF EXCEPTION HANDLING
EXCEPTION
An Exception is a run time error, which occurs during the execution of a program, that distrupts the
normal flow of the program's instructions.
It is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run
time, that disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object.
This object is called the exception object.
It contains information about the exception, such as the name and description of the exception and
the state of the program when the exception occurred.
Major reasons why an exception Occurs
Invalid user input
Device failure
Loss of network connection
Physical limitations (out of disk memory)
Code errors
Opening an unavailable file
Errors
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer, and we should not try to handle errors.
EXCEPTION HANDLING IN JAVA
The Exception Handling in Java is one of the powerful feature to handle the runtime errors so that
normal flow of the application can be maintained.
Exception Handling is used to convert system error message into user friendly error message.
Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5; //Exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement 5, the
rest of the code will not be executed i.e. statement 6 to 10 will not be executed.
If we perform exception handling, the rest of the statement will be executed. That is why we use
exception handling in Java.
UNCAUGHT EXCEPTIONS(WITH OUT USING TRY & CATCH)
Example without Exception Handling
class ExceptionDemo
{
public static void main(String[] args)
{
int a=30, b=0;
int c=a/b;
System.out.println("Denominator should not be zero");
}
}
Output: Exception in thread "main" java.lang.ArithmeticException: / by zero at
ExceptionDemo.main(ExceptionDemo.java:7)
Explanation:
Abnormally terminate program and give a message like below,
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionDemo.main(ExceptionDemo.java:7)
This error message is not understandable by user so we convert this error message into user
friendly error message, like "denominator should not be zero".
BENEFITS OF EXCEPTIONHANDLING
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types
TERMINATION OR RESUMPTIVE MODELS
In java, there are two exception models. Java programming language has two models of exception
handling. The exception models that java supports are as follows.
Termination Model
Resumptive Model
Termination Model
In the termination model, when a method encounters an exception, further processing in that
method is terminated and control is transferred to the nearest catch block that can handle the type
of exception encountered.
In other words we can say that in termination model the error is so critical there is no way to get
back to where the exception occurred.
Resumptive Model
The alternative of termination model is resumptive model.
In resumptive model, the exception handler is expected to do something to stable the situation, and
then the faulting method is retried.
In resumptive model we hope to continue the execution after the exception is handled.
In resumptive model we may use a method call that want resumption like behavior.
We may also place the try block in a while loop that keeps re-entering the try block until the result
is satisfactory.
EXCEPTION HIERARCHY
HOW TO HANDLE THE EXCEPTION
Use Five keywords for Handling the Exception
1. try
2. catch
3. throw
4. throws
5. finally
1. try block
The try block contains set of statements where an exception can occur.
In other words try block always contains problematic statements.
A try block is always followed by a catch block, which handles the exception that occurs in associated
try block. A try block must be followed by catch blocks or finally block or both.
Syntax
try
{
//statements that may cause an exception
}
2. catch block
A catch block is where we handle the exceptions, this block must follow the try block.
A single try block can have multiple catch blocks associated with it. We can catch different
exceptions in different catch blocks.
When an exception occurs in try block, the corresponding catch block that handles that particular
exception executes.
For example if an arithmetic exception occurs in try block then the statements enclosed in catch
block for arithmetic exception executes.
Syntax of try-catch in java
try
{
// statements causes problem at run time
}
catch(type of exception-1 object-1)
{
// statements provides user friendly error message
}
catch(type of exception-2 object-2)
{
// statements provides user friendly error message
}
Example1: ArithmeticException
class ExceptionDemo
{
public static void main(String[] args)
{
int a=30, b=0;
try
{
int c=a/b;
}
catch (ArithmeticException e)
{
System.out.println("Denominator should not be zero");
}
}
}
Example2: NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try
{
String a = null; //null value
System.out.println(a.charAt(0));
}
catch(NullPointerException e)
{
System.out.println("NullPointerException..");
}
}
}
Output: NullPointerException..
Example3: FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo
{
public static void main(String args[])
{
try
{ // Following file does not exist
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
catch(FileNotFoundException e)
{
System.out.println("File does not exist");
}
}
}
Output: File does not exist
MULTIPLE CATCH BLOCKS
We can write multiple catch blocks for generating multiple user friendly error messages to make our
application strong.
Example
class ExceptionDemo
{
public static void main(String[] args)
{
int a=30, b=0;
try
{
int c=a/b;
System.out.println("Result: "+c);
}
catch(NullPointerException e)
{
System.out.println("Enter valid number");
}
catch(ArithmeticException e)
{
System.out.println("Denominator not be zero");
}
}
}
NESTED TRY STATEMENTS
The try block within a try block is known as nested try block in java.
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself
may cause another error. In such cases, exception handlers have to be nested.
Syntax
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
…………
}
}
catch(Exception e)
{
………..
}
Example
class NestedTry
{
public static void main(String args[])
{
try
{
try
{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
catch(Exception e)
{
System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
3. throw
The throw keyword in Java is used to explicitly throw an exception from a method or any block of
code.
We can throw either checked or unchecked exception.
The throw keyword is mainly used to throw custom exceptions.
Syntax
throw Instance
Example
throw new ArithmeticException("/ by zero");
Example
class ThrowExcep
{
static void fun()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
}
}
public static void main(String args[])
{
try
{
fun();
}
catch(NullPointerException e)
{
System.out.println("Caught in main.");
}
}
}
Output: Caught inside fun().
Caught in main.
4. throws
throws is a keyword in java language which is used to throw the exception which is raised in the called
method to it's calling method throws keyword always followed by method signature.
Syntax
returnType methodName(parameter) throws Exception_class....
{
.....
}
Example
class ThrowsExecp
{
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
fun();
}
catch(IllegalAccessException e)
{
System.out.println("caught in main.");
}
}
}
Output:
Inside fun().
caught in main.
5.finally Block
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.
Example
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
RE-THROWING EXCEPTIONS
Sometimes we may need to rethrow an exception in Java.
If a catch block cannot handle the particular exception it has caught, we can rethrow the exception.
The rethrow expression causes the originally thrown object to be rethrown.
Because the exception has already been caught at the scope in which the rethrow expression occurs,
it is rethrown out to the next enclosing try block. Therefore, it cannot be handled by catch blocks at
the scope in which the rethrow expression occurred.
Any catch blocks for the enclosing try block have an opportunity to catch the exception.
Example
class RethrowExcep
{
static void fun()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
}
}
public static void main(String args[])
{
try
{
fun();
}
catch(NullPointerException e)
{
System.out.println("Caught in main.");
}
}
}
Output:
Caught inside fun().
Caught in main.
CREATING OWN EXCEPTION(CUSTOM EXCEPTION IN JAVA)
If any exception is design by the user known as user defined or Custom Exception. Custom Exception is
created by user.
Rules to design user defined Exception
1. Create a package with valid user defined name.
2. Create any user defined class.
3. Make that user defined class as derived class of Exception or RuntimeException class.
4. Declare parametrized constructor with string variable.
5. call super class constructor by passing string variable within the derived class constructor.
6. Save the program with public class name.java
Example
package nage;
public class InvalidAgeException extends Exception
{
public InvalidAgeException (String s)
{
super(s);
}
}
A Class that uses above InvalidAgeException:
class CustomException
{
static void validate(int age) throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
try
{
validate(13);
}
catch(Exception m)
{
System.out.println("Exception occured: "+m);
}
System.out.println("rest of the code...");
}
}
Output:
Exception occured: InvalidAgeException:not valid
rest of the code...
BUILT IN EXCEPTIONS
The Java programming language has several built-in exception class that support exception handling.
Every exception class is suitable to explain certain error situations at run time.
All the built-in exception classes in Java were defined a package java.lang.
EXCEPTION TYPES IN JAVA
In java, exceptions are mainly categorized into two types, and they are as follows.
Checked Exceptions
Unchecked Exceptions
Checked Exceptions
The checked exception is an exception that is checked by the compiler during the compilation
process to confirm whether the exception is handled by the programmer or not. If it is not handled,
the compiler displays a compilation error using built-in classes.
The checked exceptions are generally caused by faults outside of the code itself like missing
resources, networking errors, and problems with threads come to mind.
The following are a few built-in classes used to handle checked exceptions in java.
In the exception class hierarchy, the checked exception classes are the direct children of the
Exception class.
List of checked exceptions in Java
1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the
specified class cannot be found in the classpath.
2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an object, but
that the object's class does not implement the Cloneable interface.
3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers do
not allow.
4 InstantiationException
It is thrown when an application tries to create an instance of a class using the newInstance
method in class, but the specified class object cannot be instantiated because it is an
interface or is an abstract class.
5 InterruptedException
S. No. Exception Class with Description
6 NoSuchFieldException
It indicates that the class doesn't have a field of a specified name.
7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at compile
time, a NoSuchMethodException occurs during reflection when we try to access a method
that does not exist.
Unchecked Exceptions
The unchecked exception is an exception that occurs at the time of program execution. The
unchecked exceptions are not caught by the compiler at the time of compilation.
The unchecked exceptions are generally caused due to bugs such as logic errors, improper use of
resources, etc.
In the exception class hierarchy, the unchecked exception classes are the children of
RuntimeException class, which is a child class of Exception class.
List of unchecked exceptions in Java
1 ArithmeticException
It handles the arithmetic exceptions like division by zero
2 ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of the array.
3 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type of
object into an array of objects
5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to another.
6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal or
inappropriate argument.
7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or has
attempted to notify other threads that wait on an object's monitor, without owning the
specified monitor.
S. No. Exception Class with Description
8 IllegalStateException
It signals that a method has been invoked at an illegal or inappropriate time.
9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to modify the
state of the thread when it is illegal.
10 IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as an array
, vector , string , and so forth.
11 NegativeArraySizeException
It is thrown if an applet tries to create an array with negative size.
12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.
13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or integer, but
the format of the input string is not appropriate or illegal.
14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.
15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is either
negative, or greater than the size of the string itself.
16 UnsupportedOperationException
It is thrown to indicate that the requested operation is not supported.
STRING HANDLING
A string is a sequence of characters surrounded by double quotations. In a java programming
language, a string is the object of a built-in class String.
The string created using the String class can be extended. It allows us to add more characters after
its definition, and also it can be modified.
Example
String siteName = "javaprogramming";
siteName = "javaprogramminglanguage";
String handling methods
In java programming language, the String class contains various methods that can be used to handle
string data values.
The following table depicts all built-in methods of String class in java.
S.No Method Description
1 charAt(int) Finds the character at given index
2 length() Finds the length of given string
3 compareTo(String) Compares two strings
4 compareToIgnoreCase(String) Compares two strings, ignoring case
5 concat(String) Concatenates the object string with argument string.
6 contains(String) Checks whether a string contains sub-string
7 contentEquals(String) Checks whether two strings are same
8 equals(String) Checks whether two strings are same
9 equalsIgnoreCase(String) Checks whether two strings are same, ignoring case
10 startsWith(String) Checks whether a string starts with the specified string
11 isEmpty() Checks whether a string is empty or not
12 replace(String, String) Replaces the first string with second string
Replaces the first string with second string at all
replaceAll(String, String)
13 occurrences.
Extracts a sub-string from specified start and end index
substring(int, int)
14 values
15 toLowerCase() Converts a string to lower case letters
16 toUpperCase() Converts a string to upper case letters
17 trim() Removes whitespace from both ends
18 toString(int) Converts the value to a String object
Example
public class JavaStringExample
{
public static void main(String[] args)
{
String title = "Java Programming";
String siteName = "String Handling Methods";
System.out.println("Length of title: " + title.length());
System.out.println("Char at index 3: " + title.charAt(3));
System.out.println("Index of 'T': " + title.indexOf('T'));
System.out.println("Empty: " + title.isEmpty());
System.out.println("Equals: " + siteName.equals(title));
System.out.println("Sub-string: " + siteName.substring(9, 14));
System.out.println("Upper case: " + siteName.toUpperCase());
}
}
MULTI-TASKING AND MULTI-THREADING
Introduction
Multi-tasking and multi-threading are two techniques used in operating systems to manage multiple
processes and tasks.
Multi-tasking is the ability of an operating system to run multiple processes or tasks concurrently,
sharing the same processor and other resources.
In multi-tasking, the operating system divides the CPU time between multiple tasks, allowing them
to execute simultaneously.
Each task is assigned a time slice, or a portion of CPU time, during which it can execute its code.
Multi-tasking is essential for increasing system efficiency, improving user productivity, and
achieving optimal resource utilization.
Multi-threading is a technique in which an operating system divides a single process into multiple
threads, each of which can execute concurrently.
Threads share the same memory space and resources of the parent process, allowing them to
communicate and synchronize data easily.
Multi-threading is useful for improving application performance by allowing different parts of the
application to execute simultaneously.
DIFFERENCE BETWEEN MULTI-TASKING AND MULTI-THREADING
t2.start();
t3.start();
}
}
THREAD PRIORITIES
In a java programming language, every thread has a property called priority.
Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules
the threads according to their priority (known as preemptive scheduling).
The thread with more priority allocates the processor first.
But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.
Three constants defined in Thread class:
1. MIN_PRIORITY
2. NORM_PRIORITY
3. MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
The java programming language Thread class provides two methods setPriority(int),
and getPriority( ) to handle thread priorities.
setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread.
It takes an integer range from 1 to 10 as an argument and returns nothing (void).
Example
threadObject.setPriority(4);
or
threadObject.setPriority(MAX_PRIORITY);
getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread.
It does not takes any argument and returns name of the thread as String.
Example
String threadName = threadObject.getPriority();
Example1
class SampleThread extends Thread
{
public void run()
{
System.out.println("Inside SampleThread");
System.out.println("CurrentThread: " + Thread.currentThread().getName());
}
}
public class My_Thread_Test
{
public static void main(String[] args)
{
SampleThread threadObject1 = new SampleThread();
SampleThread threadObject2 = new SampleThread();
threadObject1.setName("first");
threadObject2.setName("second");
threadObject1.setPriority(4);
threadObject2.setPriority(Thread.MAX_PRIORITY);
threadObject1.start();
threadObject2.start();
}
}
Output:
Inside SampleThread
Inside SampleThread
CurrentThread: second
CurrentThread: first
Example2
class MultiThread extends Thread
{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[])
{
MultiThread m1=new MultiThread ();
MultiThread m2=new MultiThread ();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
SYNCHRONIZING THREADS
SYNCHRONIZATION
The java programming language supports multithreading.
The problem of shared resources occurs when two or more threads get execute at the same time.
In such a situation, we need some way to ensure that the shared resource will be accessed by only
one thread at a time, and this is performed by using the concept called synchronization.
The synchronization is the process of allowing only one thread to access a shared resource
at a time.
UNDERSTANDING THE PROBLEM WITHOUT SYNCHRONIZATION
In this example, there is no synchronization, so output is inconsistent.
Example:
class Table
{
void printTable(int n)
{
//method not synchronized
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
class TestSynchronization
{
public static void main(String args[])
{
Table obj = new Table(); //only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
100
10
200
15
300
20
400
25
500
Thread Synchronization
In java, the synchronization is achieved using the following concepts.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be
done by two ways in java:
1. by synchronized method
2. by synchronized block
Java synchronized method
If you declare any method as synchronized, it is known as synchronized method.
When a method created using a synchronized keyword, it allows only one object to access it at a
time.
When an object calls a synchronized method, it put a lock on that method so that other objects or
thread that are trying to call the same method must wait, until the lock is released.
Once the lock is released on the shared resource, one of the threads among the waiting threads will
be allocated to the shared resource.
In the above image, initially the thread-1 is accessing the synchronized method and other threads
(thread-2, thread-3, and thread-4) are waiting for the resource (synchronized method).
When thread-1 completes it task, then one of the threads that are waiting is allocated with the
synchronized method, in the above it is thread-3.
Example:
class Table
{
synchronized void printTable(int n)
{
for(int i = 1; i <= 10; i++)
System.out.println(n + " * " + i + " = " + i*n);
}
}
class MyThread1 extends Thread
{
Table table = new Table();
int number;
MyThread1(Table table, int number)
{
this.table = table;
this.number = number;
}
public void run()
{
table.printTable(number);
}
}
class MyThread2 extends Thread
{
Table table = new Table();
int number;
MyThread2(Table table, int number)
{
this.table = table;
this.number = number;
}
public void run()
{
table.printTable(number);
}
}
class ThreadSynchronizationExample
{
public static void main(String[] args)
{
Table table = new Table();
MyThread1 thread1 = new MyThread1(table, 5);
MyThread2 thread2 = new MyThread2(table, 10);
thread1.start();
thread2.start();
}
}
Output:
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100
Synchronized Block in Java
The synchronized block is used when we want to synchronize only a specific sequence of lines in a
method.
For example, let's consider a method with 20 lines of code where we want to synchronize only a
sequence of 5 lines code, we use the synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
synchronized (object reference expression)
{
//code block
}
Example of synchronized block
class Table
{
void printTable(int n)
{
synchronized(this)
{ //synchronized block
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}//end of the method
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
INTERTHREAD COMMUNICATION
Inter thread communication is the concept where two or more threads communicate to solve the
problem of polling.
In java, polling is the situation to check some condition repeatedly, to take appropriate action, once
the condition is true.
That means, in inter-thread communication, a thread waits until a condition becomes true such that
other threads can execute its task.
The inter-thread communication allows the synchronized threads to communicate with each other.
Java provides the following methods to achieve inter thread communication.
Method Description
void wait( ) It makes the current thread to pause its execution until other thread in the
same monitor calls notify( )
void notify( ) It wakes up the thread that called wait( ) on the same object.
void notifyAll() It wakes up all the threads that called wait( ) on the same object.
1 public void setDaemon(boolean status) is used to mark the current thread as daemon
thread or user thread.
class TestAnnotation1
{
public static void main(String args[])
{
Animal a=new Dog();
a.eatSomething();
}
}
Output: Comple Time Error
@Deprecated
@Deprecated annotation marks that this method is deprecated so compiler prints warning. It informs
user that it may be removed in the future versions. So, it is better not to use such methods.
Example
class A
{
void m()
{
System.out.println("hello m");
}
@Deprecated
void n()
{
System.out.println("hello n");
}
}
class TestAnnotation3
{
public static void main(String args[])
{
A a=new A();
a.n();
}
}
Output
At Compile Time:
Note: Test.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
At Runtime:
hello n
JAVA GENERICS
Java Generics allows us to create a single class, interface, and method that can be used with different
types of data (objects).
This helps us to reuse our code.
Note: Generics does not work with primitive types ( int , float, char, etc).
UNIT - IV
Event Handling: Events, Event sources, Event classes, Event Listeners, Delegation event model,
handling mouse and keyboard events, Adapter classes. The AWT class hierarchy, user interface
components- labels, button, canvas, scrollbars, text components, check box, checkbox groups, choices,
lists panels –scrollpane, dialogs, menubar, graphics, layout manager – layout manager types – border,
grid, flow, card and grid bag.
EVENT HANDLING
In general we can not perform any operation on dummy GUI screen even any button click or select
any item.
To perform some operation on these dummy GUI screen you need some predefined classes and
interfaces.
All these type of classes and interfaces are available in java.awt.event package.
Changing the state of an object is known as an event.
The process of handling the request in GUI screen is known as event handling (event represent an
action). It will be changes component to component.
Note: In event handling mechanism event represent an action class and Listener represent an interface.
Listener interface always contains abstract methods so here you need to write your own logic.
EVENTS
The Events are the objects that define state change in a source.
An event can be generated as a reaction of a user while interacting with GUI elements.
Some of the event generation activities are moving the mouse pointer, clicking on a button, pressing
the keyboard key, selecting an item from the list, and so on.
We can also consider many other user operations as events.
EVENT SOURCES
A source is an object that causes and generates an event.
It generates an event when the internal state of the object is changed.
The sources are allowed to generate several different types of events.
A source must register a listener to receive notifications for a specific event.
Each event contains its registration method.
Syntax
public void addTypeListener (TypeListener e1)
From the above syntax, the Type is the name of the event, and e1 is a reference to the event listener.
For example, for a keyboard event listener, the method will be called as addKeyListener().
For the mouse event listener, the method will be called as addMouseMotionListener().
When an event is triggered using the respected source, all the events will be notified to registered
listeners and receive the event object.
This process is known as event multicasting.
EVENT LISTENERS
It is also known as event handler.
Listener is responsible for generating response to an event.
From java implementation point of view the listener is also an object.
Listener waits until it receives an event.
Once the event is received, the listener process the event and then returns.
EVENT CLASSES AND LISTENER INTERFACES
In this model, a source generates an event and forwards it to one or more listeners.
The listener waits until it receives an event. Once it receives the event, it is processed by the listener
and returns it.
REGISTRATION METHODS
For registering the component with the Listener, many classes provide the registration methods.
Button
public void addActionListener(ActionListener a)
{
}
MenuItem
public void addActionListener(ActionListener a)
{
}
TextField
public void addActionListener(ActionListener a)
{
}
public void addTextListener(TextListener a)
{
}
TextArea
public void addTextListener(TextListener a)
{
}
Checkbox
public void addItemListener(ItemListener a)
{
}
Choice
public void addItemListener(ItemListener a)
{
}
List
public void addActionListener(ActionListener a)
{
}
public void addItemListener(ItemListener a)
{
}
STEPS TO PERFORM EVENT HANDLING
Following steps are required to perform event handling:
Implement the Listener interface and overrides its methods
Now the object of concerned event class is created automatically and information about the source
The Java MouseListener is notified whenever you change the state of mouse. It is notified against
MouseEvent. The MouseListener interface is found in java.awt.event package. It has five methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
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);
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);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
l.setText("Mouse Released");
}
public static void main(String[] args)
{
new MouseListenerExample();
}
}
Output:
EVENT HANDLING FOR KEYBOARD
The Java KeyListener is notified whenever you change the state of key. It is notified against KeyEvent.
The KeyListener interface is found in java.awt.event package. It has three methods.
Methods of KeyListener interface
1. public abstract void keyPressed(KeyEvent e);
2. public abstract void keyReleased(KeyEvent e);
3. public abstract void keyTyped(KeyEvent e);
EXAMPLE
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener
{
Label l;
TextArea area;
KeyListenerExample()
{
l=new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e)
{
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e)
{
l.setText("Key Released");
}
public void keyTyped(KeyEvent e)
{
l.setText("Key Typed");
}
public static void main(String[] args)
{
new KeyListenerExample();
}
}
Output:
ADAPTER CLASSES
In a program, when a listener has many abstract methods to override, it becomes complex for the
programmer to override all of them.
For example, for closing a frame, we must override seven abstract methods of WindowListener,
but we need only one method of them.
For reducing complexity, Java provides a class known as "adapters" or adapter class.
Adapters are abstract classes, that are already being overriden.
Adapter class Listener interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
Java WindowAdapter Example
import java.awt.*;
import java.awt.event.*;
public class AdapterExample
{
Frame f;
AdapterExample()
{
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
f.dispose();
}
});
f.setSize(400,400);
f.setVisible(true);
}
public static void main(String[] args)
{
new AdapterExample();
}
}
JAVA AWT HIERARCHY
The hierarchy of Java AWT classes are given below.
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there
are classes for each component as shown in above diagram. In order to place every component in a
particular position on a screen, we need to add them to a container.
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.
AWT FRAME
The Frame is the container that contain title bar and can have menu bars. It can have other components
like button, textfield etc.
Frame f=new Frame();
Methods
1. setTitle()
It is used to display user defined message on title bar.
Frame f=new Frame();
f.setTitle("myframe");
2. setBackground()
It is used to set background or image of frame.
Frame f=new Frame();
f.setBackground(Color.red);
3. setForground()
It is used to set the foreground text color.
Frame f=new Frame();
f.setForground(Color.red);
4. setSize()
It is used to set the width and height for frame.
Frame f=new Frame();
f.setSize(400,300);
5. setVisible()
It is used to make the frame as visible to end user.
Frame f=new Frame();
f.setVisible(true);
Note: You can write setVisible(true) or setVisible(false), if it is true then it visible otherwise not visible.
7.add()
It is used to add non-container components (Button, List) to the frame.
Frame f=new Frame();
Button b=new Button("Click");
f.add(b);
Explanation: In above code we add button on frame using f.add(b), here b is the object of Button class..
Example
import java.awt.*;
class FrameDemo
{
public static void main(String[] args)
{
Frame f=new Frame();
f.setTitle("myframe");
f.setBackground(Color.cyan);
f.setForeground(Color.red);
f.setLayout(new FlowLayout());
Button b1=new Button("Submit");
Button b2=new Button("Cancel");
f.add(b1);f.add(b2);
f.setSize(500,300);
f.setVisible(true);
}
}
Output
AWT PANEL
It is a predefined class used to provide a logical container to hold various GUI component. Panel always
should exist as a part of frame.
Note: Frame is always visible to end user where as panel is not visible to end user.
Panel is a derived class of container class so you can use all the methods which is used in frame.
Syntax
Panel p=new Panel();
Example
import java.awt.*;
class PanelFrame
{
PanelFrame()
{
Frame f=new Frame();
f.setSize(600,400);
f.setBackground(Color.pink);
f.setLayout(new BorderLayout());
Panel p1=new Panel();
p1.setBackground(Color.cyan);
Label l1 =new Label("Enter Uname");
TextField tf1=new TextField(15);
Label l2=new Label("Enter Passward");
TextField tf2=new TextField(15);
p1.add(l1);
p1.add(tf1);
p1.add(l2);
p1.add(tf2);
f.add("North",p1);
Panel p2=new Panel();
p2.setBackground(Color.yellow);
Button b1=new Button("Send");
Button b2=new Button("Clear");
p2.add(b1);
p2.add(b2);
f.add("South",p2);
f.setVisible(true);}
public static void main(String[] args)
{
PanelFrame pf=new PanelFrame();
}
}
Output:
AWT Label
The object of the Label class is a component for placing text in a container. It is used to display a single
line of read only text. The text can be changed by a programmer but a user cannot edit it directly.
Example
import java.awt.*;
public class LabelExample
{
public static void main(String args[])
{
Frame f = new Frame ("Label example");
Label l1, l2;
l1 = new Label ("First Label.");
l2 = new Label ("Second Label.");
l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);
f.add(l1);
f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output
Java AWT Button
A button is basically a control component with a label that generates an event when pushed.
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.
Example
import java.awt.*;
public class ButtonExample
{
public static void main (String[] args)
{
Frame f = new Frame("Button Example");
Button b = new Button("Click Here");
b.setBounds(50,100,80,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
Java AWT Canvas
The Canvas class controls and represents a blank rectangular area where the application can draw or
trap input events from the user. It inherits the Component class.
Example
import java.awt.*;
public class CanvasExample
{
public CanvasExample()
{
Frame f = new Frame("Canvas Example");
f.add(new MyCanvas());
f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);
}
public static void main(String args[])
{
new CanvasExample();
}
}
class MyCanvas extends Canvas
{
public MyCanvas()
{
setBackground (Color.GRAY);
setSize(300, 200);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
Output:
Java AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is
a GUI component allows us to see invisible number of rows and columns.
Example
import java.awt.*;
public class ScrollbarExample1
{
ScrollbarExample1()
{
Frame f = new Frame("Scrollbar Example");
Scrollbar s = new Scrollbar();
s.setBounds (100, 100, 50, 100);
f.add(s);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ScrollbarExample1();
}
}
Output:
Java AWT TextField
The object of a TextField class is a text component that allows a user to enter a single line text and edit
it. It inherits TextComponent class, which further inherits Component class.
Exmple:
import java.awt.*;
public class TextFieldExample1
{
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);
}
}
Output:
Java AWT TextArea
The object of a TextArea class is a multiline region that displays text. It allows the editing of multiple line
text. It inherits TextComponent class.
Example
import java.awt.*;
public class TextAreaExample
{
TextAreaExample()
{
Frame f = new Frame();
TextArea area = new TextArea("Welcome to javatpoint");
area.setBounds(10, 30, 300, 300);
f.add(area);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}
}
Output
Java AWT Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
Example
import java.awt.*;
public class CheckboxExample1
{
CheckboxExample1()
{
Frame f = new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
checkbox2.setBounds(100, 150, 50, 50);
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main (String args[])
{
new CheckboxExample1();
}
}
Output
Java AWT CheckboxGroup
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only one check
box button is allowed to be in "on" state and remaining check box button in "off" state. It inherits
the object class.
Example
import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample()
{
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
Output
Java AWT Choice
The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on
the top of a menu. It inherits Component class.
Example
import java.awt.*;
public class ChoiceExample1
{
ChoiceExample1()
{
Frame f = new Frame();
Choice c = new Choice();
c.setBounds(100, 100, 75, 75);
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ChoiceExample1();
}
}
Output
Java AWT List
The object of List class represents a list of text items. With the help of the List class, user can choose
either one item or multiple items. It inherits the Component class.
Example
import java.awt.*;
public class ListExample1
{
ListExample1()
{
Frame f = new Frame();
List l1 = new List(5);
l1.setBounds(100, 100, 75, 75);
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
f.add(l1);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample1();
}
}
Output
Java AWT Dialog
The Dialog control represents a top level window with a border and a title used to take some form of
input from the user. It inherits the Window class.
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.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
Output
Java AWT Menubar
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(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}
Output
Java AWT Graphics
Graphics is an abstract class provided by Java AWT which is used to draw or paint on the components.
It consists of various fields which hold information like components to be painted, font, color, XOR
mode, etc., and methods that allow drawing various shapes on the GUI components.
Example
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyFrame extends Frame
{
public MyFrame()
{
setVisible(true);
setSize(300, 200);
addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.drawRect(100, 100, 100, 50);
}
public static void main(String[] args)
{
new MyFrame();
}
}
Output
JAVA LAYOUT MANAGERS
The Layout Managers are used to arrange components in a particular manner.
Layout Manager is an interface that is implemented by all the classes of layout managers.
There are following classes that represents the layout managers:
1. BorderLayout
2. FlowLayout
3. GridLayout
4. CardLayout
5. GridBagLayout
BORDERLAYOUT
The BorderLayout is used to arrange the components in five regions: north, south, east, west and center.
Each region (area) may contain one component only. It is the default layout of frame or window.
The BorderLayout provides five constants for each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
EXAMPLE
import java.awt.*;
import javax.swing.*;
public class Border
{
Border()
{
JFrame 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(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new Border();
}
}
Output:
FLOWLAYOUT
This layout is used to arrange the GUI components in a sequential flow (that means one after another
in horizontal way)
You can also set flow layout of components like flow from left, flow from right.
FlowLayout Left
Frame f=new Frame();
f.setLayout(new FlowLayout(FlowLayout.LEFT));
FlowLayout Right
Frame f=new Frame();
f.setLayout(new FlowLayout(FlowLayout.RIGHT))
EXAMPLE
import java.awt.*;
import javax.swing.*;
public class MyFlowLayout
{
MyFlowLayout()
{
JFrame 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));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyFlowLayout();
}
}
Output:
GRIDLAYOUT
This layout is used to arrange the GUI components in the table format.
EXAMPLE
import java.awt.*;
import javax.swing.*;
public class MyGridLayout
{
MyGridLayout()
{
JFrame 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");
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));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyGridLayout();
}
}
Output
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.
Commonly used methods of CardLayout class
1. public void next(Container parent): is used to flip to the next card of the given container.
2. public void previous(Container parent): is used to flip to the previous card of the given container.
3. public void first(Container parent): is used to flip to the first card of the given container.
4. public void last(Container parent): is used to flip to the last card of the given container.
5. public void show(Container parent, String name): is used to flip to the specified card with the given
name.
EXAMPLE
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);
}
public static void main(String[] args)
{
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:
GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along their
baseline.
The components may not be of same size. Each GridBagLayout object maintains a dynamic,
rectangular grid of cells.
Each component occupies one or more cells known as its display area. Each component associates
an instance of GridBagConstraints.
With the help of constraints object we arrange component's display area on the grid.
The GridBagLayout manages each component's minimum and preferred sizes in order to determine
component's size.
Example
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame
{
public static void main(String[] args)
{
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample()
{
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:
UNIT – V
Applets – Concepts of Applets, differences between applets and applications, life cycle of an applet,
types of applets, creating applets, passing parameters to applets. Swing – Introduction, limitations of
AWT, MVC architecture, components, containers, exploring swing- JApplet, JFrame and JComponent,
Icons and Labels, text fields, buttons – The JButton class, Check boxes, Radio buttons, Combo boxes,
Tabbed Panes, Scroll Panes, Trees, and Tables.
JAVA APPLET
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Applets are used to make the website more dynamic and entertaining.
An applet is embedded in an HTML page using the APPLET or OBJECT tag and hosted on a web
server.
Important points
All applets are sub-classes of java.applet.Applet class.
Applets are not stand-alone programs. Instead, they run within either a web browser or an applet
viewer. JDK provides a standard applet viewer tool called applet viewer.
In general, execution of an applet does not begin at main() method.
Output of an applet window is not performed by System.out.println(). Rather it is handled with
various AWT methods, such as drawString().
HIERARCHY OF APPLET
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is
the subclass of Component.
DIFFERENCES BETWEEN APPLETS AND APPLICATIONS
Parameters Java Application Java Applet
Definition Applications are just like a Java Applets are small Java programs that are
program that can be executed designed to be included with the HTML web
independently without using the document. They require a Java-enabled web
web browser. browser for execution.
main() method The application program requires a The applet does not require the main()
main() method for its execution. method for its execution instead init()
method is required.
Compilation The “javac” command is used to Applet programs are compiled with the
compile application programs, “javac” command and run using either the
which are then executed using the “appletviewer” command or the web
“java” command. browser.
File access Java application programs have full Applets don’t have local disk and network
access to the local file system and access.
network.
Access level Applications can access all kinds of Applets can only access browser-specific
resources available on the system. services. They don’t have access to the local
system.
Installation First and foremost, the installation The Java applet does not need to be
of a Java application on the local installed beforehand.
computer is required.
Execution Applications can execute the Applets cannot execute programs from the
programs from the local system. local machine.
Program An application program is needed An applet program is needed to perform
to perform some tasks directly for small tasks or part of them.
the user.
Run It cannot run on its own; it needs It cannot start on its own, but it can be
JRE to execute. executed using a Java-enabled web
browser.
Connection Connectivity with other servers is It is unable to connect to other servers.
with servers possible.
Read and Write It supports the reading and writing It does not support the reading and writing
Operation of files on the local computer. of files on the local computer.
Security Application can access the system’s Executed in a more restricted environment
data and resources without any with tighter security. They can only use
security limitations. services that are exclusive to their browser.
Restrictions Java applications are self- Applet programs cannot run on their own,
contained and require no necessitating the maximum level of
additional security because they security.
are trusted.
LIFE CYCLE OF AN APPLET
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
2. Remote Applet
A remote applet is designed and developed by another developer.
It is located or available on a remote computer that is connected to the internet.
In order to run the applet stored in the remote computer, our system is connected to the internet
then we can download run it.
In order to locate and load a remote applet, we must know the applet's address on the web that is
referred to as Uniform Recourse Locator(URL).
Method Description
public void setLayout(LayoutManager m) sets the layout manager for the component.
CONTAINER
The Container is a component 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.
JPANEL
The Panel is the container that doesn't contain title bar and menu bars.
It can have other components like button, textfield etc.
JDIALOG
The JDialog control represents a top level window with a border and a title used to take some form
of input from the user.
It inherits the Dialog class.
Unlike JFrame, it doesn't have maximize and minimize buttons.
JFrame
The Frame is the container that contain title bar and can have menu bars. It can have other components
like button, textfield etc.
There are two ways to create a frame:
1. By creating the object of Frame class (association)
2. By extending Frame class (inheritance)
1. By creating the object of Frame class (association)
import javax.swing.*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame();
JButton b=new JButton("click");
f.add(b);
f.setSize(400,500);
f.setVisible(true);
}
}
2. By extending Frame class (inheritance)
We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.
EXAMPLE
import javax.swing.*;
public class Simple2 extends JFrame
{
Simple2()
{
JButton b=new JButton("click");
add(b);
setSize(400,500);
setVisible(true);
}
public static void main(String[] args)
{
new Simple2();
}
}
Output
SWING COMPONENTS
JButton
The JButton class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed.
It inherits AbstractButton class.
Example
import javax.swing.*;
public class ButtonExample
{
public static void main(String[] args)
{
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
f.add(b);
f.setSize(400,400);
f.setVisible(true);
}
}
Output:
JLabel
The object of JLabel class is a component for placing text in a container.
It is used to display a single line of read only text.
The text can be changed by an application but a user cannot edit it directly.
It inherits JComponent class.
Example
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1=new JLabel("First Label.");
t1.setBounds(50,100, 200,30);
JLabel l2=new JLabel("Second Label.");
t1.setBounds(50,100, 200,30);
f.add(l1);
f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output
JTextField
The object of a JTextField class is a text component that allows the editing of a single line text.
It inherits JTextComponent class.
Example
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Java Swings");
t1.setBounds(50,100, 200,30);
t2=new JTextField("Swing Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
JTextArea
The object of a JTextArea class is a multiline region that displays text. It allows the editing of multiple
line text. It inherits JTextComponent class.
Example
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample()
{
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
f.add(area);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}
Output
JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
Example
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample()
{
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Output
JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from multiple
options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.
Example
import javax.swing.*;
public class RadioButtonExample
{
JFrame f;
RadioButtonExample()
{
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);
bg.add(r2);
f.add(r1);
f.add(r2);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new RadioButtonExample();
}
}
Output
JComboBox
The object of Choice class is used to show popup menu of choices.
Choice selected by user is shown on the top of a menu.
It inherits JComponent class.
Example
import javax.swing.*;
public class ComboBoxExample
{
JFrame f;
ComboBoxExample()
{
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
f.add(cb);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args)
{
new ComboBoxExample();
}
}
Output
JTable
The JTable class is used to display data in tabular form.
It is composed of rows and columns.
Example
import javax.swing.*;
public class TableExample
{
JFrame f;
TableExample()
{
f=new JFrame();
String data[][]={ {"101","Amit","670000"}, {"102","Jai","780000"}, {"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args)
{
new TableExample();
}
}
Output
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.
Example
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample
{
JFrame f;
TreeExample()
{
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args)
{
new TreeExample();
}
}
Output:
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.
Example
import javax.swing.*;
public class TabbedPaneExample
{
JFrame f;
TabbedPaneExample()
{
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args)
{
new TabbedPaneExample();
}
}
Output:
JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a
scroll pane to display a large component or a component whose size can change dynamically.
Example
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
public class JScrollPaneExample
{
private static final long serialVersionUID = 1L;
private static void createAndShowGUI()
{
final JFrame frame = new JFrame("Scroll Pane Example");
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());
JTextArea textArea = new JTextArea(20, 20);
JScrollPane scrollableTextArea = new JScrollPane(textArea);
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
Output: