0% found this document useful (0 votes)
30 views203 pages

Vbspu Bca Java Note

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, secure, and versatile, making it suitable for various applications including game development, cloud computing, and artificial intelligence. Key features of Java include its simplicity, portability, multi-threading capabilities, and a strong emphasis on security.

Uploaded by

ishi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views203 pages

Vbspu Bca Java Note

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, secure, and versatile, making it suitable for various applications including game development, cloud computing, and artificial intelligence. Key features of Java include its simplicity, portability, multi-threading capabilities, and a strong emphasis on security.

Uploaded by

ishi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 203

What is Java?

Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since
Oak was already a registered company, so James Gosling and his team changed the name
from Oak to Java.
Platform: Any hardware or software environment in which a program runs, is known as a
platform. Since Java has a runtime environment (JRE) and API, it is called a platform.
Java Example
Let's have a quick look at Java programming example. A detailed description of Hello Java example
is available in next page.
Simple.java

class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
 class keyword is used to declare a class in Java.
 public keyword is an access modifier that 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 creating 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.
 String[] args or String args[] is used for command line argument. We will discuss it
in coming section.
 System.out.println() is used to print statement. Here, System is a class, out is an
object of the PrintStream class, println() is a method of the PrintStream class.

Uses of the Java programming language


Since Java is a versatile and free programming language, it has a multitude of uses:
 Development of videogames, both for mobile phones and computers. Its versatility
also allows creating modern videogames that include advanced technology such as
virtual reality.
 Cloud computing. Java is WORA (Write Once, Run Anywhere), making it the
optimal solution for developing decentralized applications in the cloud. Cloud
service providers choose Java to run programs on a wide range of platforms.
 Macro-data. Java is used in processing engines that can handle huge complex data
sets in real time.
 Artificial intelligence. Java’s stability and speed help develop artificial intelligence
applications such as natural language processing and deep learning.
 Internet of Things(IoT). Java is used for programming sensors and equipment into
peripheral devices that can independently connect to the Internet.

Features of Java
The primary objective of Java programming language creation was to make it portable, simple and
secure programming language. Apart from this, there are also some excellent features which play an
important role in the popularity of this language. The features of Java are also known as Java
buzzwords.
A list of the most important features of the Java language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun Microsystem, Java language is a simple programming language because:
 Java syntax is based on C++ (so easier for programmers to learn it after C++).
 Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
 There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.
Basic concepts of OOPs are:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which are
compiled into platform specific machines while Java is a write once, run anywhere language. A
platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-based
platform.
The Java platform differs from most other platforms in the sense that it is a software-based platform
that runs on top of other hardware-based platforms. It has two components:

 Runtime Environment
 API(Application Programming Interface)

Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:

 No explicit pointer
 Java Programs run inside a virtual machine sandbox
 Class loader: Class loader in Java is a part of the Java Runtime Environment (JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
 Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
 Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS etc.

Robust
The English mining of Robust is strong. Java is robust because:
 It uses strong memory management.
 There is a lack of pointers that avoids security problems.
 Java provides automatic garbage collection which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
 There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32
and 64-bit architectures in Java.

Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.

High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is
"close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an
interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.

Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.

Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.

Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.

JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM.
It physically exists. It contains a set of libraries + other files that JVM uses at runtime. The
implementation of JVM is also actively released by other companies besides Sun Micro
Systems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It
physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.

JVM (Java Virtual Machine) Architecture


JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed. JVMs are available for many hardware
and software platforms (i.e. JVM is platform dependent).

What is JVM?
It is:
 A specification where working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its implementation
has been provided by Oracle and other companies.
 An implementation its implementation is known as JRE (Java Runtime Environment).
 Runtime Instance Whenever you write java command on the command prompt to run
the java class, an instance of JVM is created.

What it does
The JVM performs following operation:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment
JVM provides definitions for the:
 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.

How to set path in Java


The path is required to be set for using tools such as javac, java, etc.
If you are saving the Java source file inside the JDK/bin directory, the path is not required to
be set because all the tools will be available in the current directory.
However, if you have your Java file outside the JDK/bin folder, it is necessary to set the path
of JDK.
There are two ways to set the path in Java:
 Temporary
 Permanent

1) How to set the Temporary Path of JDK in Windows


To set the temporary path of JDK, you need to follow the following steps:
 Open the command prompt
 Copy the path of the JDK/bin directory
 Write in command prompt: set path=copied_path
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin

2) How to set Permanent Path of JDK in Windows


For setting the permanent path of JDK, you need to follow these steps:
 Go to MyComputer properties -> advanced tab -> environment variables -> new tab
of user variable -> write path in variable name -> write path of bin folder in variable
value -> ok -> ok -> ok

Java Keywords
Java keywords are also known as reserved words. Keywords are particular words that act as a
key to a code. These are predefined words by Java so they cannot be used as a variable or
object name or class name.
Here is a list of keywords in the Java programming language. You cannot use any of the
following as identifiers in your programs. The keywords const and goto are reserved, even
though they are not currently used. true, false, and null might seem like keywords, but they
are actually literals; you cannot use them as identifiers in your programs.

abstract continue for new switch

assert*** default goto* package synchronized

boolean do if private this

break double implements protected throw

byte else import public throws

case enum**** instanceof return transient

catch extends int short try

char final interface static void

class finally long strictfp** volatile

const* float native super while


*
not used
**
added in 1.2
***
added in 1.4
****
added in 5.0

What is constant?
Constant is a value that cannot be changed after assigning it. Java does not directly support
the constants. There is an alternative way to define the constants in Java by using the non-
access modifiers static and final. In Java, to declare any variable as constant, we
use static and final modifiers. It is also known as non-access modifiers. According to
the Java naming convention the identifier name must be in capital letters.
Static and Final Modifiers
 The purpose to use the static modifier is to manage the memory.
 It also allows the variable to be available without loading any instance of the class in
which it is defined.
 The final modifier represents that the value of the variable cannot be changed. It also
makes the primitive data type immutable or unchangeable.
The syntax to declare a constant is as follows:
static final datatype identifier_name=value;
static final double PRICE=432.78;
In the above statement, the static modifier causes the variable to be available without an
instance of its defining class being loaded and the final modifier makes the variable fixed.
public class ConstantExample1
{
//declaring constant
private static final double PRICE=234.90;
public static void main(String[] args)
{
int unit = 10;
double total_bill;
System.out.print("Enter the number of units you have used: ");
total_bill=PRICE*unit;
System.out.println("The total amount you have to deposit is: "+total_bill);
}
}

Using Enumeration (Enum) as Constant


 It is the same as the final variables.
 It is a list of constants.
 Java provides the enum keyword to define the enumeration.
 It defines a class type by making enumeration in the class that may contain instance
variables, methods, and constructors.
Example of Enumeration
public class EnumExample {
public enum Colors {Red, Green, Blue, Purple, Black, White, Pink, Gray}
public static void main(String[] args)
{
for (Colors c : Colors.values())
System.out.println(c);
}

}
Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of
the memory location. It is a combination of "vary + able" which means its value can be
changed.
Types of Variables
There are three types of variables in Java:
 local variable
 instance variable
 static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.
public class A
{
static int m=100;//static variable
int data_nw=50;//instance variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
}

Data Types
Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.
There are 8 types of primitive data types:
 boolean data type
 byte data type
 char data type
 short data type
 int data type
 long data type
 float data type
 double data type
Data Type Default Value Default size
boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte

Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
 Unary Operator,
 Arithmetic Operator,
 Shift Operator,
 Relational Operator,
 Bitwise Operator,
 Logical Operator,
 Ternary Operator and
 Assignment Operator.

Java Operator Precedence


Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative */%
additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator


The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:
 incrementing/decrementing a value by one
 negating an expression
 inverting the value of a boolean

public class OperatorExample{


public static void main(String args[]){
int x=10;
System.out.println(x++);
System.out.println(++x);
System.out.println(x--);
System.out.println(--x);
}}

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);
System.out.println(~b);
System.out.println(!c);
System.out.println(!d);
}}

Java Arithmetic Operators


Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/b);
System.out.println(a%b);
}}

Java Left Shift Operator


The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.
public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);
System.out.println(10<<3);
System.out.println(20<<2);
System.out.println(15<<4);
}}

Java Right Shift Operator


The Java right shift operator >> is used to move the value of the left operand to right by the number of
bits specified by the right operand.

public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);
System.out.println(20>>2);
System.out.println(20>>3);
}}

Java Shift Operator Example: >> vs >>>


public class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}}
AND Operator (Logical && and Bitwise &)
The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);
System.out.println(a<b&a<c);
}}

OR Operator (Logical || and Bitwise |)


The logical || operator doesn't check the second condition if the first condition is true. It
checks the second condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);
System.out.println(a>b|a<c);

}}

Ternary Operator
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot
in Java programming. It is the only conditional operator which takes three operands.
public class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}

Java Assignment Operator


Java assignment operator is one of the most common operators. It is used to assign the value
on its right to the operand on its left.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}

Expressions
An expression is a construct made up of variables, operators, and method invocations, which
are constructed according to the syntax of the language, that evaluates to a single value.
You've already seen examples of expressions, illustrated in bold below:
int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);
int result = 1 + 2;
if (value1 == value2)
System.out.println("value1 == value2");

The data type of the value returned by an expression depends on the elements used in the
expression.
Statements
Statements are roughly equivalent to sentences in natural languages. A statement forms a
complete unit of execution. The following types of expressions can be made into a statement
by terminating the expression with a semicolon (;).
 Assignment expressions
 Any use of ++ or --
 Method invocations
 Object creation expressions
Such statements are called expression statements. Here are some examples of expression
statements.
// assignment statement
aValue = 8933.234;
// increment statement
aValue++;
// method invocation statement
System.out.println("Hello World!");
// object creation statement
Bicycle myBike = new Bicycle();

Blocks
A block is a group of zero or more statements between balanced braces and can be used
anywhere a single statement is allowed. The following example, BlockDemo, illustrates the
use of blocks:
class BlockDemo {
public static void main(String[] args) {
boolean condition = true;
if (condition) { // begin block 1
System.out.println("Condition is true.");
} // end block one
else { // begin block 2
System.out.println("Condition is false.");
} // end block 2
}
}
Control Statements or Control Flow
Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be
used to control the flow of Java code. Such statements are called control flow statements. It is
one of the fundamental features of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.
Decision making statements
 if statements
 switch statement
Loop statements
 do while loop
 while loop
 for loop
 for-each loop
Jump statements
 break statement
 continue statement

Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and
when. Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided. There are two types of decision-
making statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a
Boolean value, either true or false. In Java, there are four types of if-statements given below.
 Simple if statement
 if-else statement
 if-else-if ladder
 Nested if-statement
1) Simple if statement:

It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
Syntax of if statement is given below.
if(condition) {
statement 1; //executes when condition is true
}
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}

}
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In
other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter in the block of code where the condition is true. We can also
define an else statement at the end of the chain.
Syntax of if-else-if statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}

public class Student {


public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if
or else-if statement.
Syntax
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
public class Student {
public static void main(String[] args) {
String address = "Delhi, India";
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which
is being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.
Points to be noted about switch statement:
 The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
 Cases cannot be duplicate
 Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
 Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
 While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.
Syntax
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}

public class Student implements Cloneable {


public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value. The switch permits only int,
string, and Enum type variables to be used.

Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.
 for loop
 while loop
 do-while loop
for loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check
the condition, and increment/decrement in a single line of code. We use the for loop only
when we exactly know the number of times, we want to execute the block of code.
for(initialization, condition, increment/decrement) {
//block of statements
}
public class Calculattion {
public static void main(String[] args) {
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}

}
for-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection. In
the for-each loop, we don't need to update the loop variable. The syntax to use the for-each
loop in java is given below.
for(data_type var : array_name/collection_name){
//statements
}
public class Calculation {
public static void main(String[] args) {
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
}
}

}
while loop
The while loop is also used to iterate over the number of statements multiple times. However,
if we don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.
Syntax
while(condition){
//looping statements
}
public class Calculation {
public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}
do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.
do
{
//statements
} while (condition);

public class Calculation {


public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.
break statement
As the name suggests, the break statement is used to break the current flow of the program
and transfer the control to the next statement outside a loop or switch statement. However, it
breaks only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
The break statement example with for loop

public class BreakExample {


public static void main(String[] args) {
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}
continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in
Java.
public class ContinueExample {
public static void main(String[] args) {
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
}
}
}

Comments
The Java comments are the statements in a program that are not executed by the compiler and
interpreter.
Comments are used to make the program more readable by adding the details of the code.
It makes easy to maintain the code and to find the errors easily.
The comments can be used to provide information or explanation about the variable,
method, class, or any statement.
It can also be used to prevent the execution of program code while testing the alternative
code.

Types of Java Comments


There are three types of comments in Java.
 Single Line Comment
 Multi Line Comment
 Documentation Comment
1) Java Single Line Comment
The single-line comment is used to comment only one line of the code. It is the widely used
and easiest way of commenting the statements.
Single line comments starts with two forward slashes (//). Any text in front of // is not
executed by Java.
2) Java Multi Line Comment

The multi-line comment is used to comment multiple lines of code. It can be used to explain a
complex code snippet or to comment multiple lines of code at a time (as it will be difficult to
use single-line comments there).
Multi-line comments are placed between /* and */. Any text between /* and */ is not
executed by Java.
3) Java Documentation Comment
Documentation comments are usually used to write large programs for a project or software
application as it helps to create documentation API. These APIs are needed for reference, i.e.,
which classes, methods, arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool. The documentation
comments are placed between /** and */.
simport java.io.*;

/**
* <h2> Calculation of numbers </h2>
* This program implements an application
* to perform operation such as addition of numbers
* and print the result
* <p>
* <b>Note:</b> Comments make the code readable and
* easy to understand.
*
* @author Anurati
* @version 16.0
* @since 2021-07-06
*/
public class Calculate{
/**
* This method calculates the summation of two integers.
* @param input1 This is the first parameter to sum() method
* @param input2 This is the second parameter to the sum() method.
* @return int This returns the addition of input1 and input2
*/
public int sum(int input1, int input2){
return input1 + input2;
}
/**
* This is the main method uses of sum() method.
* @param args Unused
* @see IOException
*/
public static void main(String[] args) {
// This is demo.
/* Hi I am showing
Demo here */
Calculate obj = new Calculate();
int result = obj.sum(40, 20);
System.out.println("Addition of numbers: " + result);
}
}

labeled loop
A label is a valid variable name that denotes the name of the loop to where the control of
execution should jump. To label a loop, place the label before the loop with a colon at the
end. Therefore, a loop with the label is called a labeled loop.
In layman terms, we can say that label is nothing but to provide a name to a loop. It is a good
habit to label a loop when using a nested loop. We can also use labels
with continue and break statements.

Labeled for Loop


Labeling a for loop is useful when we want to break or continue a specific for loop according
to requirement. If we put a break statement inside an inner for loop, the compiler will jump
out from the inner loop and continue with the outer loop again.
Syntax:
labelname:
for(initialization; condition; incr/decr)
{
//functionality of the loop
}

public class LabeledForLoop


{
public static void main(String args[])
{
int i, j;
//outer loop
outer: //label
for(i=1;i<=5;i++)
{
System.out.println();
//inner loop
inner: //label
for(j=1;j<=10;j++)
{
System.out.print(j + " ");
if(j==9)
break inner;
}
}
}
}

Labeled while Loop


Syntax:
labelName:
while ( ... )
{
//statements to execute
}

public class LabledWhileLoop


{
public static void main(String args[])
{
int i = 0;
whilelabel:
while (i < 5)
{
System.out.println("outer value of i= " + i);
i++;
forlabel:
for (int j = 0; j < 5; j++)
{
if (j > 0)
{
//execution transfer to the for loop
continue forlabel;
} //end of if
if (i > 1)
{
//execution transfer to the while loop
continue whilelabel;
} //end of if
System.out.println("inner value of i= " + i + ", j= " + j);
}
} //end of while
} //end of main

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes
and objects. It simplifies software development and maintenance by providing some
concepts:
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 is a real-world entity.
 An object is a runtime entity.
 The object is an entity which has state and behaviour.
 The object is an instance of a class.
Class
Collection of objects is called class. It is a logical entity.
A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It can't be physical. A class can also be defined as a blueprint
from which you can create an individual object. Class doesn't consume any space.
A class in Java can contain:

 Fields
 Methods
 Constructors
 Blocks
 Nested class and interface
class <class_name>{
field;
method;
}
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. In Java, we use
method overloading and method overriding to achieve polymorphism.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.
In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of Method
 Code Reusability
 Code Optimization
new keyword in Java
The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.

Object and Class Example: main within the class


class Student{
int id;
String name;
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}

class Student{
int id;
String name;
}
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
3 Ways to initialize object
There are 3 ways to initialize object in Java.
 By reference variable
 By method
 By constructor
1. class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
2. class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}

Creating multiple objects


We can create multiple objects by one type only as we do in case of primitives.
Initialization of primitive variables:
int a=10, b=20;
Initialization of reference variables:
Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object is allocated in
the memory.
It is a special type of method which is used to initialize the object.
Rules for creating Java constructor
There are two rules defined for the constructor.
 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized
There are two types of constructors in Java:
 Default constructor (no-arg constructor)
 Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>(){}
//Java Program to create and call a default constructor

class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized
constructor.
//Java Program to demonstrate the use of the parameterized constructor.

class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Constructor Overloading in Java


In Java, a constructor is just like a method but without return type. It can also be overloaded
like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the list
and their types.
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Java Copy Constructor


There is no copy constructor in Java. However, we can copy the values from one object to
another like copy constructor in C++.
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}

Copying values without constructor


We can copy the values of one object into another by assigning the objects values to another
object. In this case, there is no need to create the constructor.
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}

this keyword in Java


There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.
Usage of Java this keyword
Here is given the 6 usage of java this keyword.
 this can be used to refer current class instance variable.
 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.

1) this: to refer current class instance variable


The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

2) this: to invoke current class method


You may invoke the method of the current class by using the this keyword. If you don't use
the this keyword, compiler automatically adds this keyword while invoking the method.
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}

3) this() : to invoke current class constructor


The this() constructor call can be used to invoke the current class constructor. It is used to
reuse the constructor. In other words, it is used for constructor chaining.
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}

class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}}
Rule: Call to this() must be the first statement in constructor.

4) this: to pass as an argument in the method


The this keyword can also be passed as an argument in the method. It is mainly used in the
event handling.
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}

5) this: to pass as argument in the constructor call


We can pass the this keyword in the constructor also. It is useful if we have to use one object
in multiple classes. Let's see the example:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}

6) this keyword can be used to return current class instance


We can return this keyword as an statement from the method. In such case, return type of the
method must be the class type (non-primitive).
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}

Proving this keyword


Let's prove that this keyword refers to the current class instance variable. In this program, we
are printing the reference variable and this, output of both variables are same.
class A5{
void m(){
System.out.println(this);//prints same reference ID
}
public static void main(String args[]){
A5 obj=new A5();
System.out.println(obj);//prints the reference ID
obj.m();
}
}

Inheritance in Java
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing
class.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only
Multiple inheritance is not supported in Java through class.
When one class inherits multiple classes, it is known as multiple inheritance.

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance.
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

}}

class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}

Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-
A relationship.
class Operation{
int square(int n){
return n*n;
}
}
class Circle{
Operation op;//aggregation
double pi=3.14;
double area(int radius){
op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
return pi*rsquare;
}
public static void main(String args[]){
Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}

When use Aggregation?


 Code reuse is also best achieved by aggregation when there is no is-a relationship.
 Inheritance should be used only if the relationship is-a is maintained throughout the
lifetime of the objects involved; otherwise, aggregation is the best choice.

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

Advantage of method overloading


Method overloading increases the readability of the program.

Different ways to overload the method


There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type

1) Method Overloading: changing no. of arguments


In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

2) Method Overloading: changing data type of arguments


In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));

}}

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer immediate parent
class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

Usage of Java super Keyword


 super can be used to refer immediate parent class instance variable.
 super can be used to invoke immediate parent class method.
 super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance variable.


We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}

2) super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method is
overridden.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor.
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Note: super() is added in each class constructor automatically by compiler if there is no
super() or this().
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}

Java final class


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

final class Bike{}


class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}

Object
Class Object is the root of the class hierarchy. Every class has Object as a superclass. All
objects, including arrays, implement the methods of this class.

Constructor and Description


Object()
Modifier and Type Method and Description
protected Object clone()
Creates and returns a copy of this object.
boolean equals(Object obj)
Indicates whether some other object is "equal to" this one.
protected void finalize()
Called by the garbage collector on an object when garbage
collection determines that there are no more references to the
object.
Class<?> getClass()
Returns the runtime class of this Object.
int hashCode()
Returns a hash code value for the object.
void notify()
Wakes up a single thread that is waiting on this object's monitor.
void notifyAll()
Wakes up all threads that are waiting on this object's monitor.
String toString()
Returns a string representation of the object.
void wait()
Causes the current thread to wait until another thread invokes
the notify() method or the notifyAll() method for this object.
void wait(long timeout)
Causes the current thread to wait until either another thread
invokes the notify() method or the notifyAll() method for this
object, or a specified amount of time has elapsed.
void wait(long timeout, int nanos)
Causes the current thread to wait until another thread invokes
the notify() method or the notifyAll() method for this object, or
some other thread interrupts the current thread, or a certain
amount of real time has elapsed.

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java. It
can have abstract and non-abstract methods (method with the body).
 An abstract class must be declared with an abstract keyword.
 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the
method.
Example of abstract class
abstract class A{}

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as an
abstract method.
Example of abstract method
abstract void printStatus();//no method body and abstract

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Rule: If there is an abstract method in a class, that class must be abstract.
Rule: If you are extending an abstract class that has an abstract method, you must either
provide the implementation of the method or make this class abstract.
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}

Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
How to declare an interface?
An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are public,
static and final by default. A class that implements an interface must implement all the
methods declared in the interface.
Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
In other words, Interface fields are public, static and final by default, and the methods are
public and abstract.

The relationship between classes and interfaces

interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

Multiple inheritance in Java by interface


interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Interface inheritance
A class implements an interface, but one interface extends another interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}

Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantage of Java Package


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

Simple example of java package


The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
javac -d directory javafilename
For example
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

How to access package from another package?


There are three ways to access the package from outside the package.
 import package.*;
 import package.classname;
 fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible
to the current package.
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.
Example of package by import fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
The standard of defining package is domain.company.package e.g. com.javatpoint.bean
or org.sssit.dao.
Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}

To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple

Output:Hello subpackage
How to send the class file to another directory or drive?
There is a scenario, I want to put the class file of A.java source file in classes folder of c:
drive. For example:

/save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the class file
resides.

e:\sources> set classpath=c:\classes;.;

e:\sources> java mypack.Simple

Another way to run this program by -classpath switch of java:


The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of java that tells
where to look for class file. For example:
e:\sources> java -classpath c:\classes mypack.Simple
Ways to load the class files or jar files

There are two ways to load the class files temporary and permanent.

Temporary
 By setting the classpath in the command prompt
 By -classpath switch
Permanent
 By setting the classpath in the environment variables
 By creating the jar file, that contains all the class files, and copying the jar file in the
jre/lib/ext folder.

Rule: There can be only one public class in a java source file and it must be saved by the
public class name.

Java Static Import


The static import feature of Java 5 facilitate the java programmer to access any static member
of a class directly. There is no need to qualify it by the class name.

Advantage of static import:


Less coding is required if you have access any static member of a class oftenly.

Disadvantage of static import:


If you overuse the static import feature, it makes the program unreadable and unmaintainable.
Simple Example of static import
import static java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
out.println("Hello");//Now no need of System.out
out.println("Java");
}
}

Access Modifiers in Java


There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.

There are four types of Java access modifiers:


Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc.

Understanding Java Access Modifiers

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is 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
}
}
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.
2) Default
If you don't use any modifier, it is treated as default 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 of default access modifier
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.
3) Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
It provides more accessibility than the default modifer.
Example of protected access modifier
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.
Example of public access modifier
//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Java Access Modifiers with Method Overriding
If you are overriding any method, overridden method (i.e. declared in subclass) must not be
more restrictive.
class A{
protected void msg(){System.out.println("Hello java");}
}

public class Simple extends A{


void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}
The default modifier is more restrictive than protected. That is why, there is a compile-time
error.

Encapsulation in Java
We can create a fully encapsulated class in Java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.

Advantage of Encapsulation in Java


By providing only a setter or getter method, you can make the class read-only or write-only.
In other words, you can skip the getter or setter methods.
It provides you the control over the data. Suppose you want to set the value of id which
should be greater than 100 only, you can write the logic inside the setter method. You can
write the logic not to store the negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access the
data through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
public class Student{
//private data member
private String name;
//getter method for name
public String getName(){
return name;
}
//setter method for name
public void setName(String name){
this.name=name
}
}
class Test{
public static void main(String[] args){
//creating instance of the encapsulated class
Student s=new Student();
//setting value in the name member
s.setName("vijay");
//getting value of the name member
System.out.println(s.getName());
}
}

Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory
location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we
need to use the sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store primitive
values or objects in an array in Java. Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.

Advantages
 Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
 Random access: We can get any data located at an index position.

Disadvantages
 Size Limit: We can store only the fixed size of elements in the array. It doesn't grow
its size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.

Types of Array in java


There are two types of array.
 Single Dimensional Array
 Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java


arrayRefVar=new datatype[size];

class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

For-each Loop for Java Array


We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the
loop.

The syntax of the for-each loop is given below:


for(data_type variable:array){
//body of the loop
}

class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};

//printing array using for-each loop


for(int i:arr)
System.out.println(i);
}}

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java


dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java


int[][] arr=new int[3][3];//3 row and 3 column

class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}

Wrapper classes in Java


The wrapper class in Java provides the mechanism to convert primitive into object and
object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects
into primitives automatically. The automatic conversion of primitive into an object is known
as autoboxing and vice-versa unboxing.
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal with objects many
times like in Collections, Serialization, Synchronization, etc. Let us see the different
scenarios, where we need to use the wrapper classes.
Change the value in Method: Java supports only call by value. So, if we pass a primitive
value, it will not change the original value. But, if we convert the primitive value in an object,
it will change the original value.
Serialization: We need to convert the objects into streams to perform the serialization. If we
have a primitive value, we can convert it in objects through the wrapper classes.
Synchronization: Java synchronization works with objects in Multithreading.
java.util package: The java.util package provides the utility classes to deal with objects.
Collection Framework: Java collection framework works with objects only. All classes of the
collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.
The eight classes of the java.lang package are known as wrapper classes in Java. The list of
eight wrapper classes are given below:

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float
double Double

public class WrapperExample3{


public static void main(String args[]){
byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;
//Autoboxing: Converting primitives into objects
Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;
//Printing objects
System.out.println("---Printing object values---");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);
//Unboxing: Converting Objects to Primitives
byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;
//Printing primitives
System.out.println("---Printing primitive values---");
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}}

Java String
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.

How to create a string object?


There are two ways to create String object:
By string literal
By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the
string already exists in the pool, a reference to the pooled instance is returned. If the string
doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
Note: String objects are stored in a special memory area known as the "string constant
pool".

2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}

class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}

class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}

class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
}
}

class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}

public class StringLowerExample{


public static void main(String args[]){
String s1="JAVATPOINT HELLO stRIng";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}
}
public class StringUpperExample{
public static void main(String args[]){
String s1="hello string";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}
}

public class StringTrimExample{


public static void main(String args[]){
String s1=" hello string ";
System.out.println(s1+"javatpoint");//without trim()
System.out.println(s1.trim()+"javatpoint");//with trim()
}
}

public class StringToCharArrayExample{


public static void main(String args[]){
String s1="hello";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
System.out.print(ch[i]);
}
}
}

public class StringToCharArrayExample{


public static void main(String args[]){
String s1="hello";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
System.out.print(ch[i]);
}
}
}

public class ReplaceAllExample1{


public static void main(String args[]){
String s1="javatpoint is a very good website";
String replaceString=s1.replaceAll("a","e");//replaces all occurrences of "a" to "e"
System.out.println(replaceString);
}
}

public class ReplaceExample1{


public static void main(String args[]){
String s1="javatpoint is a very good website";
String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'
System.out.println(replaceString);
}
}

java StringBuffer Class


Java StringBuffer class is used to create mutable (modifiable) String objects. The
StringBuffer class in Java is the same as String class except it is mutable i.e. it can be
changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}

class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}

class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}

class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}

class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}

What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is why
we need to handle exceptions.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is considered as
the unchecked exception. However, according to Oracle, there are three types of exceptions
namely:

 Checked Exception
 Unchecked Exception
 Error

1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.

2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

Java try block


Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
If an exception occurs at the particular statement in the try block, the rest of the block code
will not execute. So, it is recommended not to keep the code in try block that will not throw
an exception.
Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw an exception
}finally{}

Java catch block


Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.
The catch block must be used after the try block only. You can use multiple catch block with
a single try block.

public class TryCatchExample2 {


public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}

Java Catch Multiple Exceptions


A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.

Points to remember
 At a time only one exception occurs and at a time only one catch block is executed.
 All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

public class MultipleCatchBlock1 {


public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Java finally block


Java finally block is a block used to execute important code such as closing the connection,
etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception
occurs or not.
The finally block follows the try-catch block.
Note: If you don't handle the exception, before terminating the program, JVM executes
finally block (if any).

Why use Java finally block?


finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
The important statements to be printed can be placed in the finally block.

Usage of Java finally


Let's see the different cases where Java finally block can be used.
Case 1: When an exception does not occur
Let's see the below example where the Java program does not throw any exception, and the
finally block is executed after the try block.

class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of phe code...");
}
}

Case 2: When an exception occurr but not handled by the catch block
Let's see the the fillowing example. Here, the code throws an exception however the catch
block cannot handle it. Despite this, the finally block is executed after the try block and then
the program terminates abnormally.

public class TestFinallyBlock1{


public static void main(String args[]){
try {
System.out.println("Inside the try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

Case 3: When an exception occurs and is handled by the catch block


Let's see the following example where the Java code throws an exception and the catch block
handles the exception. Later the finally block is executed after the try-catch block. Further,
the rest of the code is also executed normally.

public class TestFinallyBlock2{


public static void main(String args[]){
try {
System.out.println("Inside try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
//handles the Arithmetic Exception / Divide by zero exception
catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}

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


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

Java throw Exception


In Java, exceptions allows us to write good quality codes where the errors are checked at the
compile time instead of runtime and we can create custom exceptions making the code
recovery and debugging easier.
The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has some message
with it that provides the error description. These exceptions may be related to user inputs,
server, etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly
used to throw a custom exception.
We can also define our own set of conditions and throw an exception explicitly using throw
keyword. For example, we can throw ArithmeticException if we divide a number by another
number. Here, we just need to set the condition and throw exception using throw keyword.

The syntax of the Java throw keyword is given below.


throw Instance i.e.,
throw new exception_class("error message");

Let's see the example of throw IOException.


throw new IOException("sorry device error");

Throwing Unchecked Exception


In this example, we have created a method named validate() that accepts an integer as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print
a message welcome to vote.

public class TestThrow1 {


//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}

Note: If we throw unchecked exception from a method, it is must to handle the exception or
declare in throws clause.
If we throw a checked exception using throw keyword, it is must to handle the exception
using catch block or the method must declare it using throws declaration.

Example 2: Throwing Checked Exception


Note: Every subclass of Error and RuntimeException is an unchecked exception in Java. A
checked exception is everything else under the Throwable class.

import java.io.*;
public class TestThrow2 {
//function to check if person is eligible to vote or not
public static void method() throws FileNotFoundException {
FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\abc.txt");
BufferedReader fileInput = new BufferedReader(file);
throw new FileNotFoundException();
}
//main method
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("rest of the code...");
}
}

Example 3: Throwing User-defined Exception


exception is everything else under the Throwable class.

// class represents user-defined exception


class UserDefinedException extends Exception
{
public UserDefinedException(String str)
{
// Calling constructor of parent Exception
super(str);
}
}
// Class that uses above MyException
public class TestThrow3
{
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new UserDefinedException("This is user-defined exception");
}
catch (UserDefinedException ude)
{
System.out.println("Caught the exception");
// Print the message from MyException object
System.out.println(ude.getMessage());
}
}
}

Java throws keyword


The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to provide
the exception handling code so that the normal flow of the program can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers' fault that he is not
checking the code before it being used.
Syntax of Java throws
return_type method_name() throws exception_class_name{
//method code
}

Which exception should be declared?


Ans: Checked exception only, because:

unchecked exception: under our control so we can correct our code.


error: beyond our control. For example, we are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword


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

import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}

Java Custom Exception


In Java, we can create our own exceptions that are derived classes of the Exception class.
Creating our own Exception is known as custom exception or user-defined exception.
Basically, Java custom exceptions are used to customize the exception according to user
need.
In order to create custom exception, we need to extend Exception class that belongs to
java.lang package.
Consider the following example, where we create a custom exception named

WrongFileNameException:
public class WrongFileNameException extends Exception {
public WrongFileNameException(String errorMessage) {
super(errorMessage);
}
}
// class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18){
// throw an object of user defined exception
throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object


System.out.println("Exception occured: " + ex);
}
System.out.println("rest of the code...");
}
}

// class representing custom exception


class MyCustomException extends Exception
{
}
// class that uses custom exception MyCustomException
public class TestCustomException2
{
// main method
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new MyCustomException();
}
catch (MyCustomException ex)
{
System.out.println("Caught the exception");
System.out.println(ex.getMessage());
}
System.out.println("rest of the code...");
}
}

Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a
single thread.

What is Thread in java


A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.

Life cycle of a Thread (Thread States)


In Java, a thread always exists in any one of the following states. These states are:
 New
 Active
 Blocked / Waiting
 Timed Waiting
 Terminated

Explanation of Different Thread States


New: Whenever a new thread is created, it is always in the new state. For a thread in the new
state, the code has not been run yet and thus has not begun its execution.
Active: When a thread invokes the start() method, it moves from the new state to the active
state. The active state contains two states within it: one is runnable, and the other
is running.
Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable
state, the thread may be running or may be ready to run at any given instant of time. It is the
duty of the thread scheduler to provide the thread time to run, i.e., moving the thread the
running state.
A program implementing multithreading acquires a fixed slice of time to each individual
thread. Each and every thread runs for a short span of time and when that allocated time slice
is over, the thread voluntarily gives up the CPU to the other thread, so that the other threads
can also run for their slice of time. Whenever such a scenario occurs, all those threads that are
willing to run, waiting for their turn to run, lie in the runnable state. In the runnable state,
there is a queue where the threads lie.
Running: When the thread gets the CPU, it moves from the runnable to the running state.
Generally, the most common change in the state of a thread is from runnable to running and
again back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently)
then, either the thread is in the blocked state or is in the waiting state.
Terminated: A thread reaches the termination state because of the following reasons:
When a thread has finished its job, then it exists or terminates normally.
Abnormal termination: It occurs when some unusual events such as an unhandled exception
or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is
dead, and there is no way one can respawn (active after kill) the dead thread.

Java Threads | How to create a thread in Java


There are two ways to create a thread:
 By extending Thread class
 By implementing Runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)
Commonly used methods of Thread class:
 public void run(): is used to perform action for a thread.
 public void start(): starts the execution of the thread.JVM calls the run() method on
the thread.
 public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
 public void join(): waits for a thread to die.
 public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
 public int getPriority(): returns the priority of the thread.
 public int setPriority(int priority): changes the priority of the thread.
 public String getName(): returns the name of the thread.
 public void setName(String name): changes the name of the thread.
 public Thread currentThread(): returns the reference of currently executing thread.
 public int getId(): returns the id of the thread.
 public Thread.State getState(): returns the state of the thread.
 public boolean isAlive(): tests if the thread is alive.
 public void yield(): causes the currently executing thread object to temporarily pause
and allow other threads to execute.
 public void suspend(): is used to suspend the thread(depricated).
 public void resume(): is used to resume the suspended thread(depricated).
 public void stop(): is used to stop the thread(depricated).
 public boolean isDaemon(): tests if the thread is a daemon thread.
 public void setDaemon(boolean b): marks the thread as daemon or user thread.
 public void interrupt(): interrupts the thread.
 public boolean isInterrupted(): tests if the thread has been interrupted.
 public static boolean interrupted(): tests if the current thread has been interrupted.
 Runnable interface:
 The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run().
 public void run(): is used to perform action for a thread.

Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs the
following tasks:
A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class


class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}

2) Java Thread Example by implementing Runnable interface


class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}

Priority of a Thread (Thread Priority)


Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, the thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses. Note that not only JVM a Java programmer can also assign the
priorities of a thread explicitly in a Java program.

Setter & Getter Method of Thread Priority


 public final int getPriority(): The java.lang.Thread.getPriority() method returns the
priority of the given thread.
 public final void setPriority(int newPriority): The java.lang.Thread.setPriority()
method updates or assign the priority of the thread to newPriority. The method throws
IllegalArgumentException if the value newPriority goes out of the range, which is 1
(minimum) to 10 (maximum).

3 constants defined in Thread class:


 public static int MIN_PRIORITY
 public static int NORM_PRIORITY
 public static int 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.

import java.lang.*;
public class ThreadPriorityExample extends Thread
{
// Method 1
// Whenever the start() method is called by a thread
// the run() method is invoked
public void run()
{
// the print statement
System.out.println("Inside the run() method");
}
// the main method
public static void main(String argvs[])
{
// Creating threads with the help of ThreadPriorityExample class
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
// We did not mention the priority of the thread.
// Therefore, the priorities of the thread is 5, the default value
// 1st Thread
// Displaying the priority of the thread
// using the getPriority() method
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
// 2nd Thread
// Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// 3rd Thread
// // Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// Setting priorities of above threads by
// passing integer arguments
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
// 6
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
// 3
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// 9
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
// Main thread
// Displaying name of the currently executing thread
System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName()
);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
// Priority of the main thread is 10 now
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority();
}
}

Java Thread suspend() method


The suspend() method of thread class puts the thread from running to waiting state. This
method is used if you want to stop the thread execution and start it again when a certain event
occurs. This method allows a thread to temporarily cease execution. The suspended thread
can be resumed using the resume() method.
Syntax
public final void suspend()
Return
This method does not return any value.
Exception
SecurityException: If the current thread cannot modify the thread.

public class JavaSuspendExp extends Thread


{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
// thread to sleep for 500 milliseconds
sleep(500);
System.out.println(Thread.currentThread().getName());
}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[])
{
// creating three threads
JavaSuspendExp t1=new JavaSuspendExp ();
JavaSuspendExp t2=new JavaSuspendExp ();
JavaSuspendExp t3=new JavaSuspendExp ();
// call run() method
t1.start();
t2.start();
// suspend t2 thread
t2.suspend();
// call run() method
t3.start();
}
}

Java Thread resume() method


The resume() method of thread class is only used with suspend() method. This method is
used to resume a thread which was suspended using suspend() method. This method allows
the suspended thread to start again.
Syntax
public final void resume()
Return value
This method does not return any value.
Exception
SecurityException: If the current thread cannot modify the thread.

public class JavaResumeExp extends Thread


{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
// thread to sleep for 500 milliseconds
sleep(500);
System.out.println(Thread.currentThread().getName());
}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[])
{
// creating three threads
JavaResumeExp t1=new JavaResumeExp ();
JavaResumeExp t2=new JavaResumeExp ();
JavaResumeExp t3=new JavaResumeExp ();
// call run() method
t1.start();
t2.start();
t2.suspend(); // suspend t2 thread
// call run() method
t3.start();
t2.resume(); // resume t2 thread
}
}

java Thread stop() method


The stop() method of thread class terminates the thread execution. Once a thread is stopped,
it cannot be restarted by start() method.
Syntax
public final void stop()
public final void stop(Throwable obj)
Parameter
obj : The Throwable object to be thrown.
Return
This method does not return any value.
Exception
SecurityException: This exception throws if the current thread cannot modify the thread.

public class JavaStopExp extends Thread


{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
// thread to sleep for 500 milliseconds
sleep(500);
System.out.println(Thread.currentThread().getName());
}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[])
{
// creating three threads
JavaStopExp t1=new JavaStopExp ();
JavaStopExp t2=new JavaStopExp ();
JavaStopExp t3=new JavaStopExp ();
// call run() method
t1.start();
t2.start();
// stop t3 thread
t3.stop();
System.out.println("Thread t3 is stopped");
}
}

Synchronization in Java
Synchronization in Java is the capability to control the access of multiple threads to any
shared resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.

Why use Synchronization?


The synchronization is mainly used to
 To prevent thread interference.
 To prevent consistency problem.

Types of Synchronization
There are two types of synchronization
 Process Synchronization
 Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
Mutual Exclusive
 Synchronized method.
 Synchronized block.
 Static synchronization.
Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. It
can be achieved by using the following three ways:
 By Using Synchronized Method
 By Using Synchronized Block
 By Using Static Synchronization

Concept of Lock in Java


Synchronization is built around an internal entity known as the lock or monitor. Every object
has a lock associated with it. By convention, a thread that needs consistent access to an
object's fields has to acquire the object's lock before accessing them, and then release the lock
when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock implementations.

Java Synchronized Method


If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.
class Table{
synchronized void printTable(int n){//synchronized method
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);
}
}
public class TestSynchronization2{
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();
}
}

Synchronized Block in Java


Synchronized block can be used to perform synchronization on any specific resource of the
method.
Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines, in
such cases, we can use synchronized block.
If we put all the codes of the method in the synchronized block, it will work same as the
synchronized method.

Points to Remember
Synchronized block is used to lock an object for any shared resource.
 Scope of synchronized block is smaller than the method.
 A Java synchronized block doesn't allow more than one JVM, to provide access
control to a shared resource.
 The system performance may degrade because of the slower working of synchronized
keyword.
 Java synchronized block is more efficient than Java synchronized method.

Syntax
synchronized (object reference expression) {
//code 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 class TestSynchronizedBlock1{
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();
}
}

Static Synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
class Table
{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
}
}
class MyThread2 extends Thread{
public void run(){
Table.printTable(10);
}
}
class MyThread3 extends Thread{
public void run(){
Table.printTable(100);
}
}
class MyThread4 extends Thread{
public void run(){
Table.printTable(1000);
}
}
public class TestSynchronization4{
public static void main(String t[]){
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}

Synchronized block on a class lock:


The block synchronizes on the lock of the object denoted by the reference .class name .class.
A static synchronized method printTable(int n) in class Table is equivalent to the following
declaration:
static void printTable(int n) {
synchronized (Table.class) { // Synchronized block on class A
// ...
}
}

Inter-thread Communication in Java


Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed.It is implemented by following methods of Object class:
 wait()
 notify()
 notifyAll()

1) wait() method
The wait() method causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.

Method Description

public final void wait()throws InterruptedException It waits until object is notified.

public final void wait(long timeout)throws It waits for the specified amount
InterruptedException of time.

2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened. The choice is
arbitrary and occurs at the discretion of the implementation.
Syntax:
public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()

Understanding the process of inter-thread communication


The point to point explanation of the above diagram is as follows:
 Threads enter to acquire lock.
 Lock is acquired by on thread.
 Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
 If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
 Now thread is available to acquire lock.
 After completion of the task, thread releases the lock and exits the monitor state of the
object.

class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}
}

Java I/O Tutorial


Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of 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
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream

Let's see the code to print output and an error message to the console.
System.out.println("simple message");
System.err.println("error message");

Let's see the code to get input from console.


int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character

OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array,
peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an
output stream of bytes. An output stream accepts output bytes and sends them to some sink.
Useful methods of OutputStream

Method Description

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

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


IOException output stream.

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

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

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

Method Description

1) public abstract int read()throws reads the next byte of data from the input stream. It
IOException returns -1 at the end of the file.

2) public int available()throws returns an estimate of the number of bytes that can be
IOException read from the current input stream.

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


IOException

InputStream Hierarchy

Java FileOutputStream Class


Java FileOutputStream is an output stream used for writing data to a file.
If you have to write primitive values into a file, use FileOutputStream class. You can write
byte-oriented as well as character-oriented data through FileOutputStream class. But, for
character-oriented data, it is preferred to use FileWriter than FileOutputStream.
FileOutputStream class declaration
Let's see the declaration for Java.io.FileOutputStream class:
public class FileOutputStream extends OutputStream

import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}

Java FileInputStream Class


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

import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
}

Java BufferedOutputStream Class


Java BufferedOutputStream class is used for buffering an output stream. It internally uses
buffer to store data. It adds more efficiency than to write data directly into a stream. So, it
makes the performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the
syntax for adding the buffer in an OutputStream:
OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\testo
ut.txt"));

Java BufferedOutputStream class declaration


Let's see the declaration for Java.io.BufferedOutputStream class:
public class BufferedOutputStream extends FilterOutputStream

import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Java BufferedInputStream Class
Java BufferedInputStream class is used to read information from stream. It internally uses
buffer mechanism to make the performance fast.
The important points about BufferedInputStream are:
When the bytes from the stream are skipped or read, the internal buffer automatically refilled
from the contained input stream, many bytes at a time.
When a BufferedInputStream is created, an internal buffer array is created.
Java BufferedInputStream class declaration
Let's see the declaration for Java.io.BufferedInputStream class:
public class BufferedInputStream extends FilterInputStream

import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}

Java SequenceInputStream Class


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

import java.io.*;
class InputStreamExample {
public static void main(String args[])throws Exception{
FileInputStream input1=new FileInputStream("D:\\testin.txt");
FileInputStream input2=new FileInputStream("D:\\testout.txt");
SequenceInputStream inst=new SequenceInputStream(input1, input2);
int j;
while((j=inst.read())!=-1){
System.out.print((char)j);
}
inst.close();
input1.close();
input2.close();
}
}

Java ByteArrayOutputStream Class


Java ByteArrayOutputStream class is used to write common data into multiple files. In this
stream, the data is written into a byte array which can be written to multiple streams later.
The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.
The buffer of ByteArrayOutputStream automatically grows according to data.

Java ByteArrayOutputStream class declaration


Let's see the declaration for Java.io.ByteArrayOutputStream class:
public class ByteArrayOutputStream extends OutputStream

import java.io.*;
public class DataStreamExample {
public static void main(String args[])throws Exception{
FileOutputStream fout1=new FileOutputStream("D:\\f1.txt");
FileOutputStream fout2=new FileOutputStream("D:\\f2.txt");
ByteArrayOutputStream bout=new ByteArrayOutputStream();
bout.write(65);
bout.writeTo(fout1);
bout.writeTo(fout2);
bout.flush();
bout.close();//has no effect
System.out.println("Success...");
}
}

Java ByteArrayInputStream Class


The ByteArrayInputStream is composed of two words: ByteArray and InputStream. As the
name suggests, it can be used to read byte array as input stream.
Java ByteArrayInputStream class contains an internal buffer which is used to read byte
array as stream. In this stream, the data is read from a byte array.
The buffer of ByteArrayInputStream automatically grows according to data.
Java ByteArrayInputStream class declaration
Let's see the declaration for Java.io.ByteArrayInputStream class:
public class ByteArrayInputStream extends InputStream

import java.io.*;
public class ReadExample {
public static void main(String[] args) throws IOException {
byte[] buf = { 35, 36, 37, 38 };
// Create the new byte array input stream
ByteArrayInputStream byt = new ByteArrayInputStream(buf);
int k = 0;
while ((k = byt.read()) != -1) {
//Conversion of a byte into character
char ch = (char) k;
System.out.println("ASCII value of Character is:" + k + "; Special character is: " + ch);
}
}
}

Java DataOutputStream Class


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

import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}

Java DataInputStream Class


Java DataInputStream class allows an application to read primitive data from the input stream
in a machine-independent way.
Java application generally uses the data output stream to write data that can later be read by a
data input stream.
Java DataInputStream class declaration
Let's see the declaration for java.io.DataInputStream class:
public class DataInputStream extends FilterInputStream implements DataInput

import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:\\testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
}
}

Java Writer
It is an abstract class for writing to character streams. The methods that a subclass must
implement are write(char[], int, int), flush(), and close(). Most subclasses will override some
of the methods defined here to provide higher efficiency, functionality or both.
import java.io.*;
public class WriterExample {
public static void main(String[] args) {
try {
Writer w = new FileWriter("output.txt");
String content = "I love my country";
w.write(content);
w.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Java Reader
Java Reader is an abstract class for reading character streams. The only methods that a
subclass must implement are read(char[], int, int) and close(). Most subclasses, however,
will override some of the methods to provide higher efficiency, additional functionality, or
both.
Some of the
implementation class are BufferedReader, CharArrayReader, FilterReader, InputStreamRead
er, PipedReader, StringReader

import java.io.*;
public class ReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("file.txt");
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
reader.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Java FileWriter Class
Java FileWriter class is used to write character-oriented data to a file. It is character-oriented
class which is used for file handling in java.
Unlike FileOutputStream class, you don't need to convert string into byte array because it
provides method to write string directly.
Java FileWriter class declaration
Let's see the declaration for Java.io.FileWriter class:
public class FileWriter extends OutputStreamWriter

import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}

Java FileReader Class


Java FileReader class is used to read data from the file. It returns data in byte format
like FileInputStream class.
It is character-oriented class which is used for file handling in java.
Java FileReader class declaration
Let's see the declaration for Java.io.FileReader class:
public class FileReader extends InputStreamReader

import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}

Java BufferedWriter Class


Java BufferedWriter class is used to provide buffering for Writer instances. It makes the
performance fast. It inherits Writer class. The buffering characters are used for providing the
efficient writing of single arrays, characters, and strings.

Class declaration
Let's see the declaration for Java.io.BufferedWriter class:
public class BufferedWriter extends Writer

import java.io.*;
public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("D:\\testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to javaTpoint.");
buffer.close();
System.out.println("Success");
}
}

Java BufferedReader Class


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

import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}

Java CharArrayReader Class


The CharArrayReader is composed of two words: CharArray and Reader. The
CharArrayReader class is used to read character array as a reader (stream). It
inherits Reader class.
Java CharArrayReader class declaration
Let's see the declaration for Java.io.CharArrayReader class:
public class CharArrayReader extends Reader

import java.io.CharArrayReader;
public class CharArrayExample{
public static void main(String[] ag) throws Exception {
char[] ary = { 'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't' };
CharArrayReader reader = new CharArrayReader(ary);
int k = 0;
// Read until the end of a file
while ((k = reader.read()) != -1) {
char ch = (char) k;
System.out.print(ch + " : ");
System.out.println(k);
}
}
}

Java CharArrayWriter Class


The CharArrayWriter class can be used to write common data to multiple files. This class
inherits Writer class. Its buffer automatically grows when data is written in this stream.
Calling the close() method on this object has no effect.
Java CharArrayWriter class declaration
Let's see the declaration for Java.io.CharArrayWriter class:
public class CharArrayWriter extends Writer

import java.io.CharArrayWriter;
import java.io.FileWriter;
public class CharArrayWriterExample {
public static void main(String args[])throws Exception{
CharArrayWriter out=new CharArrayWriter();
out.write("Welcome to javaTpoint");
FileWriter f1=new FileWriter("D:\\a.txt");
FileWriter f2=new FileWriter("D:\\b.txt");
FileWriter f3=new FileWriter("D:\\c.txt");
FileWriter f4=new FileWriter("D:\\d.txt");
out.writeTo(f1);
out.writeTo(f2);
out.writeTo(f3);
out.writeTo(f4);
f1.close();
f2.close();
f3.close();
f4.close();
System.out.println("Success...");
}
}

Java Scanner
Scanner class in Java is found in the java.util package. Java provides various ways to read
input from the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by
default. It provides many methods to read and parse various primitive values.
The Java Scanner class is widely used to parse text for strings and primitive types using a
regular expression. It is the simplest way to get input in Java. By the help of Scanner in Java,
we can get input from the user in primitive types such as int, long, double, byte, float, short,
etc.
The Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.
The Java Scanner class provides nextXXX() methods to return the type of value such as
nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(),
nextBoolean(), etc. To get a single character from the scanner, you can call next().charAt(0)
method which returns a single character.
Java Scanner Class Declaration
public final class Scanner
extends Object
implements Iterator<String>
How to get Java Scanner
To get the instance of Java Scanner which reads input from the user, we need to pass the
input stream (System.in) in the constructor of Scanner class. For Example:
Scanner in = new Scanner(System.in);
To get the instance of Java Scanner which parses the strings, we need to pass the strings in
the constructor of Scanner class. For Example:
Scanner in = new Scanner("Hello Javatpoint");

import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}

Java Networking
Java Networking is a concept of connecting two or more computing devices together so that
we can share resources.
Java socket programming provides facility to share data between different computing
devices.

Advantage of Java Networking


 Sharing resources
 Centralize software management
The java.net package supports two protocols,
TCP: Transmission Control Protocol provides reliable communication between the sender
and receiver. TCP is used along with the Internet Protocol referred as TCP/IP.
UDP: User Datagram Protocol provides a connection-less protocol service by allowing
packet of data to be transferred along two or more nodes

Java Networking Terminology


The widely used Java networking terminologies are given below:
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is
composed of octets that range from 0 to 255.
It is a logical address that can be changed.
2) Protocol
A protocol is a set of rules basically that is followed for communication.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications.
The port number is associated with the IP address for communication between two
applications.
4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC address.
5) Connection-oriented and connection-less protocol
In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but
slow. The example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not
reliable but fast. The example of connection-less protocol is UDP.
6) Socket
A socket is an endpoint between two way communications.

Java Socket Programming


Java Socket programming is used for communication between the applications running on
different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
The client in socket programming must know two information:
 IP Address of Server, and
 Port number.
 Socket class
A socket is simply an endpoint for communications between the machines. The Socket class
can be used to create a socket.

ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.

import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}

import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}

Java InetAddress class


Java InetAddress class represents an IP address. The java.net.InetAddress class provides
methods to get the IP of any host name for example www.javatpoint.com, www.google.com,
www.facebook.com, etc.
An IP address is represented by 32-bit or 128-bit unsigned number. An instance of
InetAddress represents the IP address with its corresponding host name. There are two types
of addresses: Unicast and Multicast. The Unicast is an identifier for a single interface
whereas Multicast is an identifier for a set of interfaces.
Moreover, InetAddress has a cache mechanism to store successful and unsuccessful host
name resolutions.

import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}

Java DatagramSocket and DatagramPacket


Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming using the UDP instead of TCP.

Datagram
Datagrams are collection of information sent from one device to another device via the
established network. When the datagram is sent to the targeted device, there is no assurance
that it will reach to the target device safely and completely. It may get damaged or lost in
between. Likewise, the receiving device also never know if the datagram received is damaged
or not. The UDP protocol is used to implement the datagrams in Java.

Java DatagramSocket class


Java DatagramSocket class represents a connection-less socket for sending and receiving
datagram packets. It is a mechanism used for transmitting datagram packets over network.`
A datagram is basically an information but there is no guarantee of its content, arrival or
arrival time.

Java DatagramPacket Class


Java DatagramPacket is a message that can be sent or received. It is a data container. If you
send multiple packet, it may arrive in any order. Additionally, packet delivery is not
guaranteed.

/DSender.java
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
ds.send(dp);
ds.close();
}
}

//DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}

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.

Advantage of Applet
There are many advantages of applet. They are as follows:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.

Drawback of Applet
 Plugin is required at client browser to execute applet.

Lifecycle of Java Applet


 Applet is initialized.
 Applet is started.
 Applet is painted.
 Applet is stopped.
 Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1
life cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
 public void init(): is used to initialized the Applet. It is invoked only once.
 public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
 public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
 public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object
that can be used for drawing oval, rectangle, arc etc.

How to run an Applet?


There are two ways to run an applet
 By html file.
 By appletViewer tool (for testing purpose).

Simple example of Applet by html file:


To execute the applet by html file, create an applet and compile it. After that create an html
file and place the applet code in html file. Now click the html file.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
Note: class must be public because its object is created by Java Plugin software that resides
on the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer First.java. Now Html file is not
required but it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java

Displaying Graphics in Applet


import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>

Displaying Image in Applet


Applet is mostly used in games and animation. For this purpose image is required to be
displayed. The java.awt.Graphics class provide a method drawImage() to display the image.
Syntax of drawImage() method:

public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the
specified image.

How to get the object of Image:


The java.applet.Applet class provides getImage() method that returns the object of Image. Syntax:

public Image getImage(URL u, String image){}


Other required methods of Applet class to display image:

public URL getDocumentBase(): is used to return the URL of the document in which
applet is embedded.
public URL getCodeBase(): is used to return the base URL.

Example of displaying image in applet:

import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"sonoo.jpg");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}

In the above example, drawImage() method of Graphics class is used to display the
image. The 4th argument of drawImage() method of is ImageObserver object. The
Component class implements ImageObserver interface. So current class object would
also be treated as ImageObserver because Applet class indirectly extends the Component
class.

myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>

Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to be moved.

Example of animation in applet:

import java.awt.*;
import java.applet.*;
public class AnimationExample extends Applet {
Image picture;
public void init() {
picture =getImage(getDocumentBase(),"bike_1.gif");
}
public void paint(Graphics g) {
for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);
try{Thread.sleep(100);}catch(Exception e){}
}
}
}

In the above example, drawImage() method of Graphics class is used to display the
image. The 4th argument of drawImage() method of is ImageObserver object. The
Component class implements ImageObserver interface. So current class object would also
be treated as ImageObserver because Applet class indirectly extends the Component
class.

myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>

Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.

Example of Painting in Applet:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{
public void init(){
addMouseMotionListener(this);
setBackground(Color.red);
}
public void mouseDragged(MouseEvent me){
Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),5,5);
}
public void mouseMoved(MouseEvent me){}
}

In the above example, getX() and getY() method of MouseEvent is used to get the
current x-axis and y-axis. The getGraphics() method of Component class returns the
object of Graphics.

myapplet.html
<html>
<body>
<applet code="MouseDrag.class" width="300" height="300">
</applet>
</body>
</html>

EventHandling in Applet

As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see
the simple example of event handling in applet that prints a message by click on the button.

Example of EventHandling in applet:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}

In the above example, we have created all the controls in init() method because it is
invoked only once.

myapplet.html
<html>
<body>
<applet code="EventApplet.class" width="300" height="300">
</applet>
</body>
</html>

Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
The AWT tutorial will help the user to understand Java GUI programming in simple and easy
steps.

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.
It is basically a screen where the where the components are placed at their specific locations.
Thus it contains and controls the layout of components.
Note: A container itself is a component (see the above diagram), therefore we can add a
container inside container.

Types of containers:
There are four types of containers in Java AWT:
 Window
 Panel
 Frame
 Dialog

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. We need to create an instance of Window class to
create this container.

Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.

Frame
The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used
container while developing an AWT application.
Useful Methods of Component Class

Method Description
public void add(Component c) Inserts a component on this component.

public void setSize(int width,int Sets the size (width and height) of the component.
height)

public void setLayout(LayoutManager Defines the layout manager for the component.
m)

public void setVisible(boolean status) Changes the visibility of the component, by


default false.

Java AWT Example


To create simple AWT example, you need a frame. There are two ways to create a GUI using
Frame in AWT.
 By extending Frame class (inheritance)
 By creating the object of Frame class (association)

AWT Example by Inheritance


Let's see a simple example of AWT where we are inheriting Frame class. Here, we are
showing Button component on the Frame.

AWTExample1.java
// importing Java AWT class
import java.awt.*;
// extending Frame class to our class AWTExample1
public class AWTExample1 extends Frame {
// initializing using constructor
AWTExample1() {
// creating a button
Button b = new Button("Click Me!!");
// setting button position on screen
b.setBounds(30,100,80,30);
// adding button into frame
add(b);
// frame size 300 width and 300 height
setSize(300,300);
// setting the title of Frame
setTitle("This is our basic AWT example");
// no layout manager
setLayout(null);
// now frame will be visible, by default it is not visible
setVisible(true);
}
// main method
public static void main(String args[]) {
// creating instance of Frame class
AWTExample1 f = new AWTExample1();
}
}

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame class. Here, we
are creating a TextField, Label and Button component on the Frame.

AWTExample2.java
// importing Java AWT class
import java.awt.*;
// class AWTExample2 directly creates instance of Frame class
class AWTExample2 {
// initializing using constructor
AWTExample2() {
// creating a Frame
Frame f = new Frame();
// creating a Label
Label l = new Label("Employee id:");
// creating a Button
Button b = new Button("Submit");
// creating a TextField
TextField t = new TextField();
// setting position of above components in the frame
l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);
// adding components into frame
f.add(b);
f.add(l);
f.add(t);
// frame size 300 width and 300 height
f.setSize(400,300);
// setting the title of frame
f.setTitle("Employee info");
// no layout
f.setLayout(null);
// setting visibility of frame
f.setVisible(true);
}
// main method
public static void main(String args[]) {
// creating instance of Frame class
AWTExample2 awt_obj = new AWTExample2();
}

Event and Listener (Java Event Handling)


Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc. The java.awt.event package provides many event classes and Listener
interfaces for event handling.

Java Event classes and Listener interfaces

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling


Following steps are required to perform event handling:
 Register the component with the Listener
 Registration Methods
For registering the component with the Listener, many classes provide the registration
methods. For example:
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){}

Java Event Handling Code


We can put the event handling code into one of the following places:
 Within class
 Other class
 Anonymous class

1) Java event handling by Within class


import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above
example that sets the position of the component it may be button, textfield etc.

2) Java event handling by outer class


import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}

import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}

3) Java event handling by anonymous class


import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}

Java 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.
When we press a button and release it, AWT sends an instance of ActionEvent to that button
by calling processEvent on the button. The processEvent method of the button receives the
all the events, then it passes an action event by calling its own method processActionEvent.
This method passes the action event on to action listeners that are interested in the action
events generated by the button.
To perform an action on a button being pressed and released, the ActionListener interface
needs to be implemented. The registered new listener can receive events from the button by
calling addActionListener method of the button. The Java application can use the button's
action command as a messaging protocol.
AWT Button Class Declaration
public class Button extends Component implements Accessible
import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {
// create instance of frame with the label
Frame f = new Frame("Button Example");
// create instance of button with label
Button b = new Button("Click Here");
// set the position for the button in frame
b.setBounds(50,100,80,30);
// add button to the frame
f.add(b);
// set size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Java 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.
It is called a passive control as it does not create any event when it is accessed. To create a
label, we need to create the object of Label class.
AWT Label Class Declaration
public class Label extends Component implements Accessible

import java.awt.*;
public class LabelExample {
public static void main(String args[]){
// creating the object of Frame class and Label class
Frame f = new Frame ("Label example");
Label l1, l2;
// initializing the labels
l1 = new Label ("First Label.");
l2 = new Label ("Second Label.");
// set the location of label
l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);
// adding labels to the frame
f.add(l1);
f.add(l2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

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.
When we enter a key in the text field (like key pressed, key released or key typed), the event
is sent to TextField. Then the KeyEvent is passed to the registered KeyListener. It can also
be done using ActionEvent; if the ActionEvent is enabled on the text field, then the
ActionEvent may be fired by pressing return key. The event is handled by
the ActionListener interface.
AWT TextField Class Declaration
public class TextField extends TextComponent

import java.awt.*;
public class TextFieldExample1 {
// main method
public static void main(String args[]) {
// creating a frame
Frame f = new Frame("TextField Example");
// creating objects of textfield
TextField t1, t2;
// instantiating the textfield objects
// setting the location of those objects in the frame
t1 = new TextField("Welcome to Javatpoint.");
t1.setBounds(50, 100, 200, 30);
t2 = new TextField("AWT Tutorial");
t2.setBounds(50, 150, 200, 30);
// adding the components to frame
f.add(t1);
f.add(t2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

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.
The text area allows us to type as much text as we want. When the text in the text area
becomes larger than the viewable area, the scroll bar appears automatically which helps us to
scroll the text up and down, or right and left.
AWT TextArea Class Declaration
public class TextArea extends TextComponent

import java.awt.*;
public class TextAreaExample
{
// constructor to initialize
TextAreaExample() {
// creating a frame
Frame f = new Frame();
// creating a text area
TextArea area = new TextArea("Welcome to javatpoint");
// setting location of text area in frame
area.setBounds(10, 30, 300, 300);
// adding text area to frame
f.add(area);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new TextAreaExample();
}
}

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".
AWT Checkbox Class Declaration
public class Checkbox extends Component implements ItemSelectable, Accessible

// importing AWT class


import java.awt.*;
public class CheckboxExample1
{
// constructor to initialize
CheckboxExample1() {
// creating the frame with the title
Frame f = new Frame("Checkbox Example");
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
// setting location of checkbox in frame
checkbox2.setBounds(100, 150, 50, 50);
// adding checkboxes to frame
f.add(checkbox1);
f.add(checkbox2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main (String args[])
{
new CheckboxExample1();
}
}

Java AWT CheckboxGroup


The object of CheckboxGroup class is used to group together a set of Checkbox. At a time
only one check box button is allowed to be in "on" state and remaining check box button in
"off" state. It inherits the object class.
Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special
control for creating radio buttons in AWT.
AWT CheckboxGroup Class Declaration
public class CheckboxGroup extends Object implements Serializable

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

Java AWT Choice


The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits Component class.
AWT Choice Class Declaration
public class Choice extends Component implements ItemSelectable, Accessible

// importing awt class


import java.awt.*;
public class ChoiceExample1 {
// class constructor
ChoiceExample1() {
// creating a frame
Frame f = new Frame();
// creating a choice component
Choice c = new Choice();
// setting the bounds of choice menu
c.setBounds(100, 100, 75, 75);
// adding items to the choice menu
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
// adding choice menu to frame
f.add(c);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new ChoiceExample1();
}
}

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.
AWT List class Declaration
public class List extends Component implements ItemSelectable, Accessible

// importing awt class


import java.awt.*;
public class ListExample1
{
// class constructor
ListExample1() {
// creating the frame
Frame f = new Frame();
// creating the list of 5 rows
List l1 = new List(5);
// setting the position of list component
l1.setBounds(100, 100, 75, 75);
// adding list items into the list
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
// adding the list to frame
f.add(l1);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new ListExample1();
}
}

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.
AWT Canvas class Declaration
public class Canvas extends Component implements Accessible

// importing awt class


import java.awt.*;
// class to construct a frame and containing main method
public class CanvasExample
{
// class constructor
public CanvasExample()
{
// creating a frame
Frame f = new Frame("Canvas Example");
// adding canvas to frame
f.add(new MyCanvas());
// setting layout, size and visibility of frame
f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new CanvasExample();
}
}

// class which inherits the Canvas class


// to create Canvas
class MyCanvas extends Canvas
{
// class constructor
public MyCanvas() {
setBackground (Color.GRAY);
setSize(300, 200);
}
// paint() method to draw inside the canvas
public void paint(Graphics g)
{
// adding specifications
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
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.
It can be added to top-level container like Frame or a component like Panel. The Scrollbar
class extends the Component class.
AWT Scrollbar Class Declaration
public class Scrollbar extends Component implements Adjustable, Accessible

// importing awt package


import java.awt.*;
public class ScrollbarExample1 {
// class constructor
ScrollbarExample1() {
// creating a frame
Frame f = new Frame("Scrollbar Example");
// creating a scroll bar
Scrollbar s = new Scrollbar();
// setting the position of scroll bar
s.setBounds (100, 100, 50, 100);
// adding scroll bar to the frame
f.add(s);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[]) {
new ScrollbarExample1();
}
}
Java AWT MenuItem and Menu
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a
menu must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the menu
bar. It inherits the MenuItem class.
AWT MenuItem class declaration
public class MenuItem extends MenuComponent implements Accessible
AWT Menu class declaration
public class Menu extends MenuItem implements MenuContainer, Accessible

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

Java AWT Dialog


The Dialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Window class.
Unlike Frame, it doesn't have maximize and minimize buttons.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons
but Dialog doesn't have.
AWT Dialog class declaration
public class Dialog extends Window

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

Java AWT Panel


The Panel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the Container class.
It doesn't have title bar.
AWT Panel class declaration
public class Panel extends Container implements Accessible

import java.awt.*;
public class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}

Java AWT PopupMenu


PopupMenu can be dynamically popped up at specific position within a component. It
inherits the Menu class.
AWT PopupMenu class declaration
public class PopupMenu extends Menu implements MenuContainer, Accessible

import java.awt.*;
import java.awt.event.*;
class PopupMenuExample
{
PopupMenuExample(){
final Frame f= new Frame("PopupMenu Example");
final PopupMenu popupmenu = new PopupMenu("Edit");
MenuItem cut = new MenuItem("Cut");
cut.setActionCommand("Cut");
MenuItem copy = new MenuItem("Copy");
copy.setActionCommand("Copy");
MenuItem paste = new MenuItem("Paste");
paste.setActionCommand("Paste");
popupmenu.add(cut);
popupmenu.add(copy);
popupmenu.add(paste);
f.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
popupmenu.show(f , e.getX(), e.getY());
}
});
f.add(popupmenu);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PopupMenuExample();
}
}

Java ActionListener Interface


The Java ActionListener is notified whenever you click on the button or menu item. It is
notified against ActionEvent. The ActionListener interface is found in
java.awt.event package. It has only one method: actionPerformed().
actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the registered
component.
public abstract void actionPerformed(ActionEvent e);

How to write ActionListener


The common approach is to implement the ActionListener. If you implement the
ActionListener class, you need to follow 3 steps:
1) Implement the ActionListener interface in the class:
public class ActionListenerExample Implements ActionListener
2) Register the component with the Listener:
component.addActionListener(instanceOfListenerclass);
3) Override the actionPerformed() method:
public void actionPerformed(ActionEvent e){
//Write the code here
}

import java.awt.*;
import java.awt.event.*;
//1st step
public class ActionListenerExample implements ActionListener{
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
//2nd step
b.addActionListener(this);
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
//3rd step
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
}

Java MouseListener Interface


The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event package. It has
five methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
 public abstract void mouseClicked(MouseEvent e);
 public abstract void mouseEntered(MouseEvent e);
 public abstract void mouseExited(MouseEvent e);
 public abstract void mousePressed(MouseEvent e);
 public abstract void mouseReleased(MouseEvent e);

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

Java Adapter Classes


Java adapter classes provide the default implementation of listener interfaces. If you inherit
the adapter class, you will not be forced to provide the implementation of all the methods of
listener interfaces. So it saves code.
Pros of using Adapter classes:
 It assists the unrelated classes to work combinedly.
 It provides ways to use classes in different ways.
 It increases the transparency of classes.
 It provides a way to include related patterns in the class.
 It provides a pluggable kit for developing an application.
 It increases the reusability of the class.
The adapter classes are found in java.awt.event,
java.awt.dnd and javax.swing.event packages. The Adapter classes with their corresponding
listener interfaces are given below.

java.awt.event Adapter classes

Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener

java.awt.dnd Adapter classes

Adapter class Listener interface

DragSourceAdapter DragSourceListener

DragTargetAdapter DragTargetListener

javax.swing.event Adapter classes

Adapter class Listener interface

MouseInputAdapter MouseInputListener

InternalFrameAdapter InternalFrameListener
Java WindowAdapter Example
In the following example, we are implementing the WindowAdapter class of AWT and one
its methods windowClosing() to close the frame window.

// importing the necessary libraries


import java.awt.*;
import java.awt.event.*;
public class AdapterExample {
// object of Frame
Frame f;
// class constructor
AdapterExample() {
// creating a frame with the title
f = new Frame ("Window Adapter");
// adding the WindowListener to the frame
// overriding the windowClosing() method
f.addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e) {
f.dispose();
}
});
// setting the size, layout and
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);
}
// main method
public static void main(String[] args) {
new AdapterExample();
}
}
Java WindowListener Interface
The Java WindowListener is notified whenever you change the state of window. It is notified
against WindowEvent. The WindowListener interface is found in java.awt.event package. It
has three methods.
WindowListener interface declaration
The declaration for java.awt.event.WindowListener interface is shown below:
public interface WindowListener extends EventListener
Methods of WindowListener interface
The signature of 7 methods found in WindowListener interface with their usage are given
below:

Sr. Method signature Description


no.

1. public abstract void It is called when the Window is set to be an


windowActivated (WindowEvent e); active Window.

2. public abstract void windowClosed It is called when a window has been closed as the
(WindowEvent e); result of calling dispose on the window.

3. public abstract void windowClosing It is called when the user attempts to close the
(WindowEvent e); window from the system menu of the window.

4. public abstract void It is called when a Window is not an active


windowDeactivated (WindowEvent Window anymore.
e);

5. public abstract void It is called when a window is changed from a


windowDeiconified (WindowEvent minimized to a normal state.
e);

6. public abstract void windowIconified It is called when a window is changed from a


(WindowEvent e); normal to a minimized state.

7. public abstract void windowOpened It is called when window is made visible for the
(WindowEvent e); first time.

Methods inherited by the WindowListener


This interface inherits methods from the EventListener interface.
Working of WindowListener interface
If a class needs to process some Window events, an object should exist which can implement
the interface.
As the object is already registered with Listener, an event will be generated on all the states
of window.
This helps in generation of invocation of relevant method in listener's object. And then
WindowEvent is passed after invocation.
Java WindowListener Example
In the following example, we are going to implement all the method of WindowListener
interface one by one.

// importing necessary libraries of awt


import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
// class which inherits Frame class and implements WindowListener interface
public class WindowExample extends Frame implements WindowListener {
// class constructor
WindowExample() {
// adding WindowListener to the frame
addWindowListener(this);
// setting the size, layout and visibility of frame
setSize (400, 400);
setLayout (null);
setVisible (true);
}
// main method
public static void main(String[] args) {
new WindowExample();
}
// overriding windowActivated() method of WindowListener interface which prints the given
string when window is set to be active
public void windowActivated (WindowEvent arg0) {
System.out.println("activated");
}
// overriding windowClosed() method of WindowListener interface which prints the given str
ing when window is closed
public void windowClosed (WindowEvent arg0) {
System.out.println("closed");
}
// overriding windowClosing() method of WindowListener interface which prints the given st
ring when we attempt to close window from system menu
public void windowClosing (WindowEvent arg0) {
System.out.println("closing");
dispose();
}
// overriding windowDeactivated() method of WindowListener interface which prints the give
n string when window is not active
public void windowDeactivated (WindowEvent arg0) {
System.out.println("deactivated");
}
// overriding windowDeiconified() method of WindowListener interface which prints the give
n string when window is modified from minimized to normal state
public void windowDeiconified (WindowEvent arg0) {
System.out.println("deiconified");
}
// overriding windowIconified() method of WindowListener interface which prints the given s
tring when window is modified from normal to minimized state
public void windowIconified(WindowEvent arg0) {
System.out.println("iconified");
}
// overriding windowOpened() method of WindowListener interface which prints the given s
tring when window is first opened
public void windowOpened(WindowEvent arg0) {
System.out.println("opened");
}
}

Java ItemListener Interface


The Java ItemListener is notified whenever you click on the checkbox. It is notified against
ItemEvent. The ItemListener interface is found in java.awt.event package. It has only one
method: itemStateChanged().
itemStateChanged() method
The itemStateChanged() method is invoked automatically whenever you click or unclick on
the registered checkbox component.
public abstract void itemStateChanged(ItemEvent e);

import java.awt.*;
import java.awt.event.*;
public class ItemListenerExample implements ItemListener{
Checkbox checkBox1,checkBox2;
Label label;
ItemListenerExample(){
Frame f= new Frame("CheckBox Example");
label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
checkBox1 = new Checkbox("C++");
checkBox1.setBounds(100,100, 50,50);
checkBox2 = new Checkbox("Java");
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
checkBox1.addItemListener(this);
checkBox2.addItemListener(this);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if(e.getSource()==checkBox1)
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
if(e.getSource()==checkBox2)
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
public static void main(String args[])
{
new ItemListenerExample();
}
}

Java AWT Toolkit


Toolkit class is the abstract superclass of every implementation in the Abstract Window
Toolkit. Subclasses of Toolkit are used to bind various components. It inherits Object class.
AWT Toolkit class declaration
public abstract class Toolkit extends Object

import java.awt.*;
public class ToolkitExample {
public static void main(String[] args) {
Toolkit t = Toolkit.getDefaultToolkit();
System.out.println("Screen resolution = " + t.getScreenResolution());
Dimension d = t.getScreenSize();
System.out.println("Screen width = " + d.width);
System.out.println("Screen height = " + d.height);
}
}
import java.awt.event.*;
public class ToolkitExample {
public static void main(String[] args) {
Frame f=new Frame("ToolkitExample");
Button b=new Button("beep");
b.setBounds(50,100,60,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Toolkit.getDefaultToolkit().beep();
}
});
}
}

import java.awt.*;
class ToolkitExample {
ToolkitExample(){
Frame f=new Frame();
Image icon = Toolkit.getDefaultToolkit().getImage("D:\\icon.png");
f.setIconImage(icon);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public static void main(String args[]){
new ToolkitExample();
}
}

Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout
managers. There are the following classes that represent the layout managers:
 java.awt.BorderLayout
 java.awt.FlowLayout
 java.awt.GridLayout
 java.awt.CardLayout
 java.awt.GridBagLayout
 javax.swing.BoxLayout
 javax.swing.GroupLayout
 javax.swing.ScrollPaneLayout
 javax.swing.SpringLayout etc.

Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west,
and center. Each region (area) may contain one component only. It is the default layout of a
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
Constructors of BorderLayout class:
BorderLayout(): creates a border layout but with no gaps between the components.
BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.

import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border()
{
f = new JFrame();
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}

Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.
Constructors of GridLayout class
GridLayout(): creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with the given rows and columns
but no gaps between the components.
GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given
rows and columns along with given horizontal and vertical gaps.

// import statements
import java.awt.*;
import javax.swing.*;
public class GridLayoutExample
{
JFrame frameObj;
// constructor
GridLayoutExample()
{
frameObj = new JFrame();
// creating 9 buttons
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
// adding buttons to the frame
// since, we are using the parameterless constructor, therfore;
// the number of columns is equal to the number of buttons we
// are adding to the frame. The row count remains one.
frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);
// setting the grid layout using the parameterless constructor
frameObj.setLayout(new GridLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new GridLayoutExample();
}
}

Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after another (in a
flow). It is the default layout of the applet or panel.
Fields of FlowLayout class

 public static final int LEFT


 public static final int RIGHT
 public static final int CENTER
 public static final int LEADING
 public static final int TRAILING
Constructors of FlowLayout class
FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal
and vertical gap.
FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment
and the given horizontal and vertical gap.

import java.awt.*;
import javax.swing.*;
public class FlowLayoutExample
{
JFrame frameObj;
// constructor
FlowLayoutExample()
{
// creating a frame object
frameObj = new JFrame();
// creating the buttons
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");
JButton b10 = new JButton("10");
// adding the buttons to frame
frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b4);
frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.add(b8);
frameObj.add(b9); frameObj.add(b10);
// parameter less constructor is used
// therefore, alignment is center
// horizontal as well as the vertical gap is 5 units.
frameObj.setLayout(new FlowLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}

Java BoxLayout
The Java BoxLayout class is used to arrange the components either vertically or
horizontally. For this purpose, the BoxLayout class provides four constants. They are as
follows:
Note: The BoxLayout class is found in javax.swing package.
Fields of BoxLayout Class
 public static final int X_AXIS: Alignment of the components are horizontal from
left to right.
 public static final int Y_AXIS: Alignment of the components are vertical from top
to bottom.
 public static final int LINE_AXIS: Alignment of the components is similar to the
way words are aligned in a line, which is based on the ComponentOrientation
property of the container. If the ComponentOrientation property of the container is
horizontal, then the components are aligned horizontally; otherwise, the components
are aligned vertically. For horizontal orientations, we have two cases: left to right, and
right to left. If the value ComponentOrientation property of the container is from left
to right, then the components are rendered from left to right, and for right to left, the
rendering of components is also from right to left. In the case of vertical orientations,
the components are always rendered from top to bottom.
 public static final int PAGE_AXIS: Alignment of the components is similar to the
way text lines are put on a page, which is based on the ComponentOrientation
property of the container. If the ComponentOrientation property of the container is
horizontal, then components are aligned vertically; otherwise, the components are
aligned horizontally. For horizontal orientations, we have two cases: left to right, and
right to left. If the value ComponentOrientation property of the container is also from
left to right, then the components are rendered from left to right, and for right to left,
the rendering of components is from right to left. In the case of vertical orientations,
the components are always rendered from top to bottom.
Constructor of BoxLayout class
BoxLayout(Container c, int axis): creates a box layout that arranges the components with
the given axis.
import java.awt.*;
import javax.swing.*;

public class BoxLayoutExample1 extends Frame {


Button buttons[];
public BoxLayoutExample1 () {
buttons = new Button [5];
for (int i = 0;i<5;i++) {
buttons[i] = new Button ("Button " + (i + 1));
// adding the buttons so that it can be displayed
add (buttons[i]);
}
// the buttons will be placed horizontally
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}
// main method
public static void main(String args[]){
BoxLayoutExample1 b=new BoxLayoutExample1();
}
}

Java CardLayout
The Java CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known as
CardLayout.
Constructors of CardLayout Class
CardLayout(): creates a card layout with zero horizontal and vertical gap.
CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical
gap.
Commonly Used Methods of CardLayout Class
 public void next(Container parent): is used to flip to the next card of the given
container.
 public void previous(Container parent): is used to flip to the previous card of the
given container.
 public void first(Container parent): is used to flip to the first card of the given
container.
 public void last(Container parent): is used to flip to the last card of the given
container.
 public void show(Container parent, String name): is used to flip to the specified
card with the given name.

// import statements
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class CardLayoutExample1 extends JFrame implements ActionListener
{
CardLayout crd;
// button variables to hold the references of buttons
JButton btn1, btn2, btn3;
Container cPane;
// constructor of the class
CardLayoutExample1()
{
cPane = getContentPane();
//default constructor used
// therefore, components will
// cover the whole area
crd = new CardLayout();
cPane.setLayout(crd);
// creating the buttons
btn1 = new JButton("Apple");
btn2 = new JButton("Boy");
btn3 = new JButton("Cat");
// adding listeners to it
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
cPane.add("a", btn1); // first card is the button btn1
cPane.add("b", btn2); // first card is the button btn2
cPane.add("c", btn3); // first card is the button btn3
}
public void actionPerformed(ActionEvent e)
{
// Upon clicking the button, the next card of the container is shown
// after the last card, again, the first card of the container is shown upon clicking
crd.next(cPane);
}
// main method
public static void main(String argvs[])
{
// creating an object of the class CardLayoutExample1
CardLayoutExample1 crdl = new CardLayoutExample1();
// size is 300 * 300
crdl.setSize(300, 300);
crdl.setVisible(true);
crdl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along
their baseline.
The components may not be of the 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
the constraints object, we arrange the component's display area on the grid. The
GridBagLayout manages each component's minimum and preferred sizes in order to
determine the component's size. GridBagLayout components are also arranged in the
rectangular grid but can have many different sizes and can occupy multiple rows or columns.
Constructor
GridBagLayout(): The parameterless constructor is used to create a grid bag layout
manager.

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

ScrollPaneLayout
The layout manager is used by JScrollPane. JScrollPaneLayout is responsible for nine
components: a viewport, two scrollbars, a row header, a column header, and four "corner"
components.
Constructor
ScrollPaneLayout(): The parameterless constructor is used to create a new
ScrollPanelLayout.

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
public class ScrollPaneDemo extends JFrame
{
public ScrollPaneDemo() {
super("ScrollPane Demo");
ImageIcon img = new ImageIcon("child.png");
JScrollPane png = new JScrollPane(new JLabel(img));
getContentPane().add(png);
setSize(300,250);
setVisible(true);
}
public static void main(String[] args) {
new ScrollPaneDemo();
}
}

Displaying image:
For displaying image, we can use the method drawImage() of Graphics class.

Syntax of drawImage() method:

public abstract boolean drawImage(Image img, int x, int y, ImageObserver


observer): is used draw the specified image.

import java.awt.*;
import javax.swing.JFrame;
public class MyCanvas extends Canvas{
public void paint(Graphics g) {
Toolkit t=Toolkit.getDefaultToolkit();
Image i=t.getImage("p3.gif");
g.drawImage(i, 120,100,this);
}
public static void main(String[] args) {
MyCanvas m=new MyCanvas();
JFrame f=new JFrame();
f.add(m);
f.setSize(400,400);
f.setVisible(true);
}
}

Displaying graphics:
java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:

public abstract void drawString(String str, int x, int y): is used to draw the specified string.
public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified
width and height.
public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with
the default color and specified width and height.
public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with
the specified width and height.
public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the
default color and specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the
points(x1, y1) and (x2, y2).
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is
used draw the specified image.
public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
public abstract void setColor(Color c): is used to set the graphics current color to the specified
color.
public abstract void setFont(Font font): is used to set the graphics current font to the specified
font.
import java.awt.*;
import javax.swing.JFrame;
public class DisplayGraphics extends Canvas{
public void paint(Graphics g) {
g.drawString("Hello",40,40);
setBackground(Color.WHITE);
g.fillRect(130, 30,100, 80);
g.drawOval(30,130,50, 60);
setForeground(Color.RED);
g.fillOval(130,130,50, 60);
g.drawArc(30, 200, 40,50,90,60);
g.fillArc(30, 130, 40,50,180,40);
}
public static void main(String[] args) {
DisplayGraphics m=new DisplayGraphics();
JFrame f=new JFrame();
f.add(m);
f.setSize(400,400);
//f.setLayout(null);
f.setVisible(true);
}
}

Play an Audio file using Java


Clip is a java interface available in javax.sound.sampled package and introduced in Java7.
Following steps are to be followed to play a clip object.
Create an object of AudioInputStream by using AudioSystem.getAudioInputStream(File file).
AudioInputStream converts an audio file into stream.
Get a clip reference object from AudioSystem.
Stream an audio input stream from which audio data will be read into the clip by using open()
method of Clip interface.
Set the required properties to the clip like frame position, loop, microsecond position.
Start the clip

// Java program to play an Audio


// file using Clip Object
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class SimpleAudioPlayer
{
// to store current position
Long currentFrame;
Clip clip;
// current status of clip
String status;
AudioInputStream audioInputStream;
static String filePath;
// constructor to initialize streams and clip
public SimpleAudioPlayer()
throws UnsupportedAudioFileException,
IOException, LineUnavailableException
{
// create AudioInputStream object
audioInputStream =
AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile());
// create clip reference
clip = AudioSystem.getClip();
// open audioInputStream to the clip
clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
public static void main(String[] args)
{
try
{
filePath = "Your path for the file";
SimpleAudioPlayer audioPlayer = new SimpleAudioPlayer();
audioPlayer.play();
Scanner sc = new Scanner(System.in);
while (true)
{
System.out.println("1. pause");
System.out.println("2. resume");
System.out.println("3. restart");
System.out.println("4. stop");
System.out.println("5. Jump to specific time");
int c = sc.nextInt();
audioPlayer.gotoChoice(c);
if (c == 4)
break;
}
sc.close();
}
catch (Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
// Work as the user enters his choice
private void gotoChoice(int c)
throws IOException, LineUnavailableException, UnsupportedAudioFileException
{
switch (c)
{
case 1:
pause();
break;
case 2:
resumeAudio();
break;
case 3:
restart();
break;
case 4:
stop();
break;
case 5:
System.out.println("Enter time (" + 0 +
", " + clip.getMicrosecondLength() + ")");
Scanner sc = new Scanner(System.in);
long c1 = sc.nextLong();
jump(c1);
break;
}
}
// Method to play the audio
public void play()
{
//start the clip
clip.start();
status = "play";
}
// Method to pause the audio
public void pause()
{
if (status.equals("paused"))
{
System.out.println("audio is already paused");
return;
}
this.currentFrame =
this.clip.getMicrosecondPosition();
clip.stop();
status = "paused";
}
// Method to resume the audio
public void resumeAudio() throws UnsupportedAudioFileException, IOException,
LineUnavailableException
{
if (status.equals("play"))
{
System.out.println("Audio is already "+
"being played");
return;
}
clip.close();
resetAudioStream();
clip.setMicrosecondPosition(currentFrame);
this.play();
}
// Method to restart the audio
public void restart() throws IOException, LineUnavailableException,
UnsupportedAudioFileException
{
clip.stop();
clip.close();
resetAudioStream();
currentFrame = 0L;
clip.setMicrosecondPosition(0);
this.play();
}
// Method to stop the audio
public void stop() throws UnsupportedAudioFileException,
IOException, LineUnavailableException
{
currentFrame = 0L;
clip.stop();
clip.close();
}
// Method to jump over a specific part
public void jump(long c) throws UnsupportedAudioFileException, IOException,

LineUnavailableException
{
if (c > 0 && c < clip.getMicrosecondLength()) {
clip.stop();
clip.close();
resetAudioStream();
currentFrame = c;
clip.setMicrosecondPosition(c);
this.play();
}
}
// Method to reset audio stream
public void resetAudioStream() throws UnsupportedAudioFileException, IOException,

LineUnavailableException
{
audioInputStream = AudioSystem.getAudioInputStream(
new File(filePath).getAbsoluteFile());
clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
}

Video Player In Java


JMF download is represented by two types: platform dependent and multiplatform version. Sun
Company offers platform versions that are specific to Solaris and Windows. (The Linux version
of Blackdown is also available).
You can find the JMF API on the Oracle website or your favorite search engine.
There are 4 jar files in the file to add to the project.
It's easy if you work in STS, therefore, to add files to your project, simply right-click on the
project name and then choose to Create Path-Configure Compile Path-Add External JARs.
Playing media files through JMF(Java Media Framework) is a simple operation. Manager and
Player are the key classes and a leader set of methods createPlayer (), each player back. When
you have created a player, it tells you to start playback.
The player is a type of controller and the drivers allow you to register a ControllerListener.
ControllerListener contains a single method: public void controllerUpdate (ControllerEvent
event). This method is used to capture different events with media data, for example. To get to
the end of the video data, exit the download, start, and end of the multimedia data playback.

import java.awt.Dimension;
import javax.swing.*;
import javax.media.bean.playerbean.MediaPlayer;

class VideoPlayer extends JFrame{


MediaPlayer player;//our video player

public VideoExample(String path){


super("Simple video player");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(640,480));//set the player window size
player = new MediaPlayer();
player.setMediaLocation("file:///" + path);
player.setPlaybackLoop(false);//repeat the video file
player.prefetch();
add(player);
player.start(); - start the player
setVisible(true);
}

public static void main(String []args){


VideoExample ve = new VideoExample(filePath);
}
}

Animation in java:

import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
class Animation extends JComponent {
// Instance variables that define the current characteristics
// of your animated object.
int ballX = 50;
int ballY = 50;
final int BALL_SIZE = 50;
// Ball's speed for x and y
private float ballSpeedX = 3;
private float ballSpeedY = 3;
private static final int UPDATE_RATE = 24;
// This special method is automatically called when the scene needs to be drawn.
public void paintComponent(Graphics g) {
// Clear the background to white
g.setColor(Color.WHITE);
g.fillRect(0, 0, 800, 600);
// Draw the ball at the current ballX, ballY position
g.setColor(Color.ORANGE); // Orange like a basketball?
g.fillOval(ballX, ballY, BALL_SIZE, BALL_SIZE);
}
// Pause the program for ms milliseconds so the animation doesn't go too fast
public void pause(int ms) {
try {
Thread.sleep(ms);
}
catch (InterruptedException ex) {
System.out.println("Error occurred!");
}
}
public void playAnimation() {
// Inside the loop you should do 4 things:
// Update the ball position variables (ballX and ballY)
while (true) {
//Calculate the ball's new position
ballX += ballSpeedX;
ballY += ballSpeedY;
//Check the new position to see if a bounce occurs;
//If the bounce occurs, the moving direction changes
if (ballX < 0 || ballX + BALL_SIZE > 800){
ballSpeedX = -ballSpeedX;
} else if (ballY <0 || ballY + BALL_SIZE > 580) {
ballSpeedY = -ballSpeedY;
}
//Use repaint() to draw the ball in the new location
repaint();
//Use pause(x) to pause the program's execution for x milliseconds (you should fill in a
value for x)
pause(10);
}
}
public static void main(String[] args) {
Animation my_animation = new Animation();
JFrame frame = new JFrame();
// Set the size of the window
frame.add(my_animation);
// Set the title of the window
frame.setTitle("My Animation");
frame.setSize(800, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Launch your animation!
my_animation.playAnimation();
}
}

You might also like