0% found this document useful (0 votes)
696 views

Java Notes

Java is an object-oriented programming language and platform. There are four main types of applications that can be created using Java: 1) standalone applications, 2) web applications, 3) enterprise applications, and 4) mobile applications. Java was initially developed by James Gosling at Sun Microsystems and released in 1995.

Uploaded by

harsha gvd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
696 views

Java Notes

Java is an object-oriented programming language and platform. There are four main types of applications that can be created using Java: 1) standalone applications, 2) web applications, 3) enterprise applications, and 4) mobile applications. Java was initially developed by James Gosling at Sun Microsystems and released in 1995.

Uploaded by

harsha gvd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 105

1) Standalone Application

UNIT-1 JAVA BASICS


Standalone applications are also known as desktop
What is Java applications or window-based applications. These
are traditional software that we need to install on
Java is a programming language and a platform. every machine. Examples of standalone application
are Media player, antivirus, etc. AWT and Swing are
Java is a high level, robust, object-oriented and used in Java for creating standalone applications.
secure programming language.
2) Web Application
Platform: Any hardware or software environment in
which a program runs, is known as a platform. Since An application that runs on the server side and
Java has a runtime environment (JRE) and API, it is creates a dynamic page is called a web application.
called a platform. Currently, Servlet, JSP, Struts, Spring, Hibernate,
JSF, etc. technologies are used for creating web
applications in Java.

3) Enterprise Application
Java Example
An application that is distributed in nature, such as
Let's have a quick look at Java programming banking applications, etc. is called enterprise
example. A detailed description of hello Java application. It has advantages of the high-level
example is available in next page. security, load balancing, and clustering. In Java, EJB
is used for creating enterprise applications.
1. class Simple{
2. public static void main(String args[]){ 4) Mobile Application
3. System.out.println("Hello Java");
4. } An application which is created for mobile devices
5. } is called a mobile application. Currently, Android
and Java ME are used for creating mobile
applications.

Application Why Java Programming named


According to Sun, 3 billion devices run Java. There "Java"?
are many devices where Java is currently used.
Some of them are as follows: 5) Why had they chosen java name for java
language? The team gathered to choose a new
1. Desktop Applications such as acrobat reader, name. The suggested words were "dynamic",
media player, antivirus, etc. "revolutionary", "Silk", "jolt", "DNA", etc. They
2. Web Applications such as irctc.co.in, wanted something that reflected the essence of the
javatpoint.com, etc. technology: revolutionary, dynamic, lively, cool,
3. Enterprise Applications such as banking unique, and easy to spell and fun to say.
applications.
4. Mobile According to James Gosling, "Java was one of the
5. Embedded System top choices along with Silk". Since Java was so
6. Smart Card unique, most of the team members preferred Java
7. Robotics than other names.
8. Games, etc.
6) Java is an island of Indonesia where first coffee
was produced (called java coffee).

7) Notice that Java is just a name, not an acronym.


Types of Java Applications
There are mainly 4 types of applications that can be
created using Java programming:
8) Initially developed by James Gosling at Sun Java was designed and
C++ was
Microsystems (which is now a subsidiary of Oracle created as an
designed for
Corporation) and released in 1995. interpreter for printing
systems and
systems but later
applications
Features of Java Design extended as a support
programming. It
Goal network computing. It
was an extension
was designed with a
The features of Java are also known as java of C
goal of being easy to
buzzwords. programming
use and accessible to a
language.
broader audience.
1. Simple
2. Object-Oriented
C++ supports the Java doesn't support
3. Portable Goto
4. Platform independent goto statement. the goto statement.
5. Secured
6. Robust Java doesn't support
7. Architecture neutral Multiple C++ supports multiple inheritance
8. Interpreted inheritanc multiple through class. It can be
e inheritance. achieved by interfaces
in java.

Operator C++ supports


Java doesn't support
Overloadi operator
operator overloading.
ng overloading.

Java supports pointer


internally. However,
C++ supports
you can't write the
pointers. You can
Pointers pointer program in
write pointer
java. It means java has
program in C++.
restricted pointer
support in java.

Java uses compiler and


interpreter both. Java
C++ uses
source code is
compiler only.
9. High Performance converted into
C++ is compiled
10. Multithreaded bytecode at
Compiler and run using the
11. Distributed compilation time. The
and compiler which
12. Dynamic interpreter executes
Interprete converts source
this bytecode at
r code into machine
C++ vs Java runtime and produces
code so, C++ is
output. Java is
Compariso platform
C++ Java interpreted that is why
n Index dependent.
it is platform
independent.
Platform-
C++ is platform- Java is platform-
independe
dependent. independent. Call by C++ supports Java supports call by
nt
Value and both call by value value only. There is no
Call by and call by call by reference in
Java is mainly used for
reference reference. java.
application
C++ is mainly programming. It is
Mainly C++ supports
used for system widely used in Structure Java doesn't support
used for structures and
programming. window, web-based, and Union structures and unions.
unions.
enterprise and mobile
applications. C++ doesn't have Java has built-in
Thread
Support built-in support thread support.
for threads. It
relies on third-
party libraries for
thread support.

Java supports
C++ doesn't
Document documentation
support
ation comment (/** ... */) to
documentation
comment create documentation Types of Variables
comment.
for java source code.
There are three types of variables in java:
Java has no virtual
C++ supports
keyword. We can • local variable
virtual keyword
Virtual so that we can
override all non-static • instance variable
methods by default. In • static variable
Keyword decide whether or
other words, non-static
not override a
methods are virtual by 1) Local Variable
function.
default.
A variable declared inside the body of the method is
Java supports unsigned called local variable. You can use this variable only
right shift >>> within that method and the other methods in the
operator that fills zero class aren't even aware that the variable exists.
unsigned C++ doesn't
at the top for the
right shift support >>>
negative numbers. For A local variable cannot be defined with "static"
>>> operator.
positive numbers, it keyword.
works same like >>
operator.
2) Instance Variable
Java uses a single
A variable declared inside the class but outside the
inheritance tree always
because all classes are body of the method, is called instance variable. It is
C++ creates a not declared as static.
Inheritanc the child of Object
new inheritance
e Tree class in java. The
tree always. It is called instance variable because its value is
object class is the root
of the inheritance tree instance specific and is not shared among instances.
in java.
3) Static variable
Java is not so
C++ is nearer to A variable which is declared as static is called static
Hardware interactive with
hardware. variable. It cannot be local. You can create a single
hardware.
copy of static variable and share among all the
Java is also an object- instances of the class. Memory allocation for static
oriented language. variable happens only once when the class is loaded
C++ is an object-
However, everything in the memory.
oriented
(except fundamental
language.
Object- types) is an object in Example to understand the types of variables in java
However, in C
oriented Java. It is a single root
language, single
hierarchy as 1. class A{
root hierarchy is
everything gets 2. int data=50;//instance variable
not possible.
derived from 3. static int m=100;//static variable
java.lang.Object. 4. void method(){
5. int n=90;//local variable
Note 6. }
7. }//end of class
• Java doesn't support default arguments like C++.
• Java does not support header files like C++. Java
uses the import keyword to include different
classes and methods.
• Multidimensional Array
Java Array
Example of Java Array
Java array is an object which contains elements of
a similar data type. 1. class Testarray{
2. public static void main(String args[]){
A data structure where we store similar elements. 3. int a[]=new int[5];//declaration and instantiation
4. a[0]=10;//initialization
We can store only a fixed set of elements in a Java 5. a[1]=20;
array. 6. a[2]=70;
7. a[3]=40;
Array in java is index-based, the first element of the 8. a[4]=50;
array is stored at the 0 index. 9. //traversing array
10. for(int i=0;i<a.length;i++)//length is the property
of array
11. System.out.println(a[i]);
12. }}

Passing Array to Method in Java


1. class Testarray2{
2. //creating a method which receives an array as a
Advantages parameter
3. static void min(int arr[]){
• Code Optimization: It makes the code 4. int min=arr[0];
optimized, we can retrieve or sort the data 5. for(int i=1;i<arr.length;i++)
efficiently. 6. if(min>arr[i])
• Random access: We can get any data located at 7. min=arr[i];
an index position. 8.
9. System.out.println(min);
Disadvantages 10. }
11.
• Size Limit: We can store only the fixed size of 12. public static void main(String args[]){
elements in the array. It doesn't grow its size at 13. int a[]={33,3,4,5};//declaring and initializing an a
runtime. To solve this problem, collection rray
framework is used in Java which grows 14. min(a);//passing array to method
automatically. 15. }}

Syntax to Declare an Array in Java Addition of 2 Matrices in Java


1. dataType[] arr; (or) 1. class Testarray5{
2. dataType []arr; (or) 2. public static void main(String args[]){
3. dataType arr[]; 3. //creating two matrices
4. int a[][]={{1,3,4},{3,4,5}};
Instantiation of an Array in Java 5. int b[][]={{1,3,4},{3,4,5}};
6.
1. arrayRefVar=new datatype[size]; 7. //creating another matrix to store the sum of two
matrices
8. int c[][]=new int[2][3];
Declaration, Instantiation and 9.
10. //adding and printing addition of 2 matrices
Initialization of Java Array 11. for(int i=0;i<2;i++){
12. for(int j=0;j<3;j++){
1. int a[]={33,3,4,5};//declaration, instantiation and 13. c[i][j]=a[i][j]+b[i][j];
initialization 14. System.out.print(c[i][j]+" ");
15. }
Types of Array in java 16. System.out.println();//new line
17. }
• Single Dimensional Array 18.
19. }} The Boolean data type is used to store only two
possible values: true and false. This data type is used
for simple flags that track true/false conditions.

Data Types in Java Example: Boolean one = false

1. Primitive data types: The primitive data types Byte Data Type
include boolean, char, byte, short, int, long, float
and double. The byte data type is an example of primitive data
2. Non-primitive data types: The non-primitive type. It is an 8-bit signed two's complement integer.
data types include Classes, Interfaces, and
Its value-range lies between -2^7 to 2^7-1
Arrays.
(inclusive). Its default value is 0.

Java Primitive Data Types The byte data type is used to save memory in large
arrays where the memory savings is most required. It
There are 8 types of primitive data types: saves space because a byte is 4 times smaller than an
integer. It can also be used in place of "int" data
• boolean data type type.
• byte data type
• char data type Example: byte a = 10, byte b = -20
• short data type
• int data type
• long data type Short Data Type
• float data type
• double data type The short data type is a 16-bit signed two's
complement integer. Its value-range lies between -
2^15 to 2^15-1 (inclusive). Its default value is 0.
Data Type Default Value Default size
The short data type can also be used to save memory
boolean false 1 bit just like byte data type. A short data type is 2 times
smaller than an integer.
char '\u0000' 2 byte

byte 0 1 byte
Example: short s = 10000, short r = -5000

short 0 2 byte Int Data Type


int 0 4 byte The int data type is a 32-bit signed two's
complement integer. Its value-range lies between -
long 0L 8 byte
2^31 to 2^31 -1 (inclusive). Its default value is 0.
float 0.0f 4 byte
The int data type is generally used as a default data
double 0.0d 8 byte type for integral values unless if there is no problem
about memory.

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

Long Data Type


The long data type is a 64-bit two's complement
integer. Its value-range lies between -2^63 to 2^63 -
1 (inclusive). Its default value is 0. The long data
type is used when you need a range of values more
than those provided by int.

Boolean Data Type Example: long a = 100000L, long b = -200000L


Float Data Type Java Unary Operator Example
class OperatorExample{
The float data type is a single-precision 32-bit IEEE
754 floating point. Its value range is unlimited. It is 1. public static void main(String args[]){
recommended to use a float (instead of double) if 2. int a=10;
you need to save memory in large arrays of floating 3. int b=10;
point numbers. Its default value is 0.0d. 4. System.out.println(a++ + ++a);//10+12=22
5. System.out.println(b++ + b++);//10+11=21
Example: float f1 = 234.5f 6.
7. }}

Double Data Type Java Arithmetic Operator Example


The double data type is a double-precision 64-bit 1. class OperatorExample{
IEEE 754 floating point. Its value range is unlimited. 2. public static void main(String args[]){
The double data type is generally used for decimal 3. int a=10;
values just like float. Its default value is 0.0d. 4. int b=5;
5. System.out.println(a+b);//15
Example: double d1 = 12.3 6. System.out.println(a-b);//5
7. System.out.println(a*b);//50
8. System.out.println(a/b);//2
Char Data Type 9. System.out.println(a%b);//0
10. }}
The char data type is a single 16-bit Unicode
character. Its value-range lies between '\u0000' (or 0) Java Left Shift Operator Example
to '\uffff' (or 65,535 inclusive). The char data type is
used to store characters. 1. class OperatorExample{
2. public static void main(String args[]){
Example: char letterA = 'A' 3. System.out.println(10<<2);//10*2^2=10*4=40
4. System.out.println(10<<3);//10*2^3=10*8=80
5. System.out.println(20<<2);//20*2^2=20*4=80
Java Operator Precedence 6. System.out.println(15<<4);//15*2^4=15*16=240

Operator 7. }}
Category Precedence
Type
postfix expr++ expr-- Java Right Shift Operator Example
Unary ++expr --expr +expr -
prefix expr ~ ! 1. class OperatorExample{
2. public static void main(String args[]){
multiplicative */% 3. System.out.println(10>>2);//10/2^2=10/4=2
Arithmetic
additive +- 4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
Shift shift << >> >>>
6. }}
comparison < > <= >= instanceof
Relational
equality == != Java AND Operator Example: Logical &&
bitwise AND & and Bitwise &
bitwise exclusive
^ The logical && operator doesn't check second
Bitwise OR
condition if first condition is false. It checks second
bitwise inclusive | condition only if first one is true.
OR
logical AND && The bitwise & operator always checks both
Logical
logical OR || conditions whether first condition is true or false.
Ternary ternary ?:
1. class OperatorExample{
= += -= *= /= %= &= 2. public static void main(String args[]){
Assignment assignment ^= |= <<= >>= >>>=
3. int a=10;
4. int b=5; 12. }}
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true =
false CONTROL STATEMENTS
7. System.out.println(a<b&a<c);//false & true = fals
e Java If-else Statement
8. }}
The Java if statement is used to test the condition. It
Java OR Operator Example: Logical || and checks boolean condition: true or false. There are
Bitwise | various types of if statement in java.

The logical || operator doesn't check second • if statement


condition if first condition is true. It checks second • if-else statement
condition only if first one is false. • if-else-if ladder
• nested if statement
The bitwise | operator always checks both conditions
whether first condition is true or false. Java Switch Statement Example
1. class OperatorExample{ 1. public class SwitchExample {
2. public static void main(String args[]){ 2. public static void main(String[] args) {
3. int a=10;
3. //Declaring a variable for switch expression
4. int b=5;
5. int c=20; 4. int number=20;
6. System.out.println(a>b||a<c);//true || true = true 5. //Switch expression
7. System.out.println(a>b|a<c);//true | true = true 6. switch(number){
8. // || vs | 7. //Case statements
9. System.out.println(a>b||a++<c);//true || true = tru 8. case 10: System.out.println("10");
e 9. break;
10. System.out.println(a);//10 because second conditi 10. case 20: System.out.println("20");
on is not checked 11. break;
11. System.out.println(a>b|a++<c);//true | true = true 12. case 30: System.out.println("30");
13. break;
12. System.out.println(a);//11 because second conditi
14. //Default case statement
on is checked
13. }} 15. default:System.out.println("Not in 10, 20 or
30");
16. }
Java Ternary Operator Example
17. }
18. }
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=2; Loops in Java
4. int b=5;
5. int min=(a<b)?a:b; // 2 For Loop Example:
6. System.out.println(min);
7. }}
1. public class ForExample {
2. public static void main(String[] args) {
Java Assignment Operator Example 3. //Code of Java for loop
4. for(int i=1;i<=10;i++){
1. class OperatorExample{ 5. System.out.print(i+” “);
2. public static void main(String[] args){ 6. }
3. int a=10;
7. }
4. a+=3;//10+3
5. System.out.println(a); // 13 8. }
6. a-=4;//13-4
7. System.out.println(a); // 9 For Each Loop Example:
8. a*=2;//9*2
9. System.out.println(a); // 18 1. public class ForEachExample {
10. a/=2;//18/2 2. public static void main(String[] args) {
11. System.out.println(a); // 9 3. //Declaring an array
4. int arr[]={12,23,44,56,78}; 5. }
5. //Printing array using for-each loop 6. }
6. for(int i:arr){ 7. }
7. System.out.print(i+” “);
8. } Do-While Example:
9. }
10. } 1. public class DoWhileExample {
2. public static void main(String[] args) {
Labelled For Loop Example: 3. int i=1;
4. do{
1. public class LabeledForExample { 5. System.out.println(i);
2. public static void main(String[] args) { 6. i++;
3. //Using Label for outer and for loop 7. }while(i<=10);
4. aa: 8. }
5. for(int i=1;i<=3;i++){ 9. }
6. bb:
7. for(int j=1;j<=3;j++){ Infinite Do-While Example:
8. if(i==2&&j==2){
9. break aa; 1. public class DoWhileExample2 {
10. } 2. public static void main(String[] args) {
11. System.out.println(i+" "+j); 3. do{
12. } 4. System.out.println("infinitive do while l
13. } oop");
14. } 5. }while(true);
15. } 6. }
7. }
Infinite For Loop Example:

1. public class ForExample {


Jump Statements
2. public static void main(String[] args) {
Break Example:
3. //Using no condition in for loop
4. for(;;){
1. public class BreakExample {
5. System.out.println("infinitive loop");
2. public static void main(String[] args) {
6. }
3. //using for loop
7. }
4. for(int i=1;i<=10;i++){
8. }
5. if(i==5){
6. //breaking the loop
While Loop Example:
7. break;
8. }
1. public class WhileExample {
9. System.out.println(i);
2. public static void main(String[] args) {
10. }
3. int i=1;
11. }
4. while(i<=10){
12. }
5. System.out.println(i);
6. i++;
Continue Example:
7. }
8. }
1. public class ContinueExample {
9. }
2. public static void main(String[] args) {
3. //for loop
Infinite While Loop Example:
4. for(int i=1;i<=10;i++){
5. if(i==5){
1. public class WhileExample2 {
6. //using continue statement
2. public static void main(String[] args) {
7. continue;//it will skip the rest stateme
3. while(true){
nt
4. System.out.println("infinitive while loo
8. }
p");
9. System.out.println(i);
10. } • Class
11. } • Inheritance
12. } • Polymorphism
• Abstraction
• Encapsulation
Java Comments
Single Line Comment Syntax:

1. //This is single line comment

Multi Line Comment Syntax:

1. /*
2. This
3. is
4. multi line
5. comment
6. */

Document Comment Syntax:


Object
1. /**
Any entity that has state and behavior is known as
2. This
an object. It can be physical or logical.
3. is
4. documentation
5. comment An Object can be defined as an instance of a class.
6. */ An object contains an address and takes up some
space in memory. Objects can communicate without
knowing the details of each other's data or code.
Java Command Line Arguments
1. class CommandLineExample{
Class
2. public static void main(String args[]){
3. System.out.println("Your first argument is: " Collection of objects is called class. It is a logical
+args[0]); entity.
4. }
5. } A class can also be defined as a blueprint from
which you can create an individual object. Class
1. compile by > javac CommandLineExample.j doesn't consume any space.
ava
2. run by > java CommandLineExample sonoo Inheritance
JAVA OOPS CONCEPTS 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
OOPs (Object-Oriented achieve runtime polymorphism.
Programming System)
Polymorphism
Object means a real-world entity such as a pen,
chair, table, computer, watch, etc. Object-Oriented If one task is performed by different ways, it is
Programming is a methodology or paradigm to known as polymorphism. In Java, we use method
design a program using classes and objects. It overloading and method overriding to achieve
simplifies the software development and polymorphism.
maintenance by providing some concepts:

• Object
Abstraction
Hiding internal details and showing functionality is CamelCase in java naming
known as abstraction. For example phone call, we
don't know the internal processing. conventions
In Java, we use abstract class and interface to If name is combined with two words, second word
achieve abstraction. will start with uppercase letter always e.g.
actionPerformed(), firstName, ActionEvent,
ActionListener etc.

Class Declaration Syntax:

1. class <class_name>{
2. Fields;
3. Methods;
Encapsulation 4. Blocks;
5. Constructors;
Binding (or wrapping) code and data together into a 6. Nested Classes;
single unit are known as encapsulation. For example 7. Interfaces;
capsule, it is wrapped with different medicines. 8. }

A java class is the example of encapsulation. Java Instance variable in Java


bean is the fully encapsulated class because all the
data members are private here. A variable which is created inside the class but
outside the method is known as an instance variable.
Instance variable doesn't get memory at compile
Naming Conventions in java time. It gets memory at runtime when an object or
instance is created. That is why it is known as an
By using standard Java naming conventions, you instance variable.
make your code easier to read for yourself and for
other programmers. Readability of Java program is
very important. It indicates that less time is spent to
figure out what the code does. Method in Java

Name Convention In Java, a method is like a function which is used to


expose the behaviour of an object.
should start with uppercase letter and be a
class name noun e.g. String, Color, Button, System, Advantage of Method
Thread etc.
• Code Reusability
should start with uppercase letter and be an • Code Optimization
interface
adjective e.g. Runnable, Remote,
name
ActionListener etc.
new keyword in Java
should start with lowercase letter and be a
method
verb e.g. actionPerformed(), main(), print(),
name The new keyword is used to allocate memory at
println() etc.
runtime. All objects get memory in Heap memory
variable should start with lowercase letter e.g.
area.
name firstName, orderNumber etc.
Examples with Class & Object:
package should be in lowercase letter e.g. java, lang,
name sql, util etc. 1. class Student{
2. //defining fields
constants should be in uppercase letter. e.g. RED, 3. int id;//field or data member or instance vari
name YELLOW, MAX_PRIORITY etc. able
4. String name;
5. //creating main method inside the Student cl
ass
6. public static void main(String args[]){ Output:
7. //Creating an object or instance
8. Student s1=new Student();//creating an obje 101 Sonoo
ct of Student
9. //Printing values of the object 2) Object and Class Example: Initialization through
10. System.out.println(s1.id);//accessing memb method
er through reference variable
11. System.out.println(s1.name); File: TestStudent4.java
12. }
13. } 1. class Student{
2. int rollno;
File: TestStudent1.java 3. String name;
4. void insertRecord(int r, String n){
5. rollno=r;
1. //Java Program to demonstrate having the ma
6. name=n;
in method in 7. }
2. //another class 8. void displayInformation(){System.out.println(ro
3. //Creating Student class. llno+" "+name);}
4. class Student{ 9. }
5. int id; 10. class TestStudent4{
6. String name; 11. public static void main(String args[]){
7. } 12. Student s1=new Student();
8. //Creating another class TestStudent1 which 13. Student s2=new Student();
contains the main method 14. s1.insertRecord(111,"Karan");
9. class TestStudent1{ 15. s2.insertRecord(222,"Aryan");
16. s1.displayInformation();
10. public static void main(String args[]){
17. s2.displayInformation();
11. Student s1=new Student(); 18. }
12. System.out.println(s1.id); 19. }
13. System.out.println(s1.name);
14. } Output:
15. }
111 Karan
3 Ways to initialize object 222 Aryan

3) Object and Class Example: Initialization through


There are 3 ways to initialize object in java.
a constructor
1. By reference variable
2. By method File: TestEmployee.java
3. By constructor
1. class Employee{
1) Object and Class Example: Initialization through 2. int id;
3. String name;
reference
4. float salary;
5. void insert(int i, String n, float s) {
File: TestStudent2.java 6. id=i;
7. name=n;
1. class Student{ 8. salary=s;
2. int id; 9. }
3. String name; 10. void display(){System.out.println(id+" "+nam
4. } e+" "+salary);}
5. class TestStudent2{ 11. }
6. public static void main(String args[]){ 12. public class TestEmployee {
7. Student s1=new Student(); 13. public static void main(String[] args) {
8. s1.id=101; 14. Employee e1=new Employee();
9. s1.name="Sonoo"; 15. Employee e2=new Employee();
10. System.out.println(s1.id+" "+s1.name);//printin 16. Employee e3=new Employee();
g members with a white space 17. e1.insert(101,"ajeet",45000);
11. } 18. e2.insert(102,"irfan",25000);
12. } 19. e3.insert(103,"nakul",55000);
20. e1.display(); 1. Constructor name must be the same as its class
21. e2.display(); name
22. e3.display(); 2. A Constructor must have no explicit return type
23. } 3. A Java constructor cannot be abstract, static,
24. } final, and synchronized

Output: Difference between object and class


101 ajeet 45000.0 Object Class
102 irfan 25000.0
103 nakul 55000.0 Class is a blueprint or
Object is an instance of
template from which
a class.
What are the different ways to objects are created.
create an object in Java? Object is a real world
entity such as pen,
• By new keyword Class is a group of
laptop, mobile, bed,
• By newInstance() method similar objects.
• By clone() method keyboard, mouse, chair
• By deserialization etc.
• By factory method etc.
Object is a physical
Class is a logical entity.
Creating multiple objects by one type only entity.

Initialization of primitive variables: Object is created through


new keyword mainly Class is declared using
1. int a=10, b=20; e.g. class keyword e.g.
Student s1=new class Student{}
Initialization of refernce variables: Student();

1. Rectangle r1=new Rectangle(), r2=new Rectangl Object is created many


e();//creating two objects Class is declared once.
times as per requirement.

Constructors in Java Object allocates Class doesn't allocated


memory when it is memory when it is
A constructor is called when an instance of the created. created.
object is created, and memory is allocated for the
object. It is a special type of method which is used to There are many ways to
initialize the object. create object in java
such as new keyword, There is only one way to
When is a constructor called newInstance() method, define class in java using
clone() method, factory class keyword.
Every time an object is created using new() method and
keyword, at least one constructor is called. It calls a deserialization.
default constructor.

Note: It is called constructor because it constructs


the values at the time of object creation. It is not
Types of Java constructors
necessary to write a constructor for a class. It is
Example of Default Constructor:
because java compiler creates a default constructor if
your class doesn't have any.
1. //Java Program to create and call a default co
Rules for creating Java constructor nstructor
2. class Bike1{
3. //creating a default constructor
There are two rules defined for the constructor.
4. Bike1(){System.out.println("Bike is created"
);}
5. //main method
6. public static void main(String args[]){ 22. s1.display();
7. //calling a default constructor 23. s2.display();
8. Bike1 b=new Bike1(); 24. }
9. } 25. }
10. }
Difference between constructor
Example of Parameterized Constructor:
and method in Java
1. class Student4{
2. int id; Java Constructor Java Method
3. String name; A constructor is used to A method is used to
4. //creating a parameterized constructor initialize the state of an expose the behaviour of
5. Student4(int i,String n){ object. an object.
6. id = i; A constructor must not A method must have a
7. name = n; have a return type. return type.
8. }
9. //method to display the values The constructor is The method is invoked
10. void display(){System.out.println(id+" "+n invoked implicitly. explicitly.
ame);} The Java compiler
11. provides a default The method is not
12. public static void main(String args[]){ constructor if you don't provided by the compiler
13. //creating objects and passing values have any constructor in a in any case.
14. Student4 s1 = new Student4(111,"Karan"); class.
The constructor name The method name may or
15. Student4 s2 = new Student4(222,"Aryan"); must be same as the class may not be same as class
name. name.
16. //calling method to display the values of o
bject
Copy Constructor Example:
17. s1.display(); 1. class ClassName{
18. s2.display(); 2. int id;
19. } 3. String name;
20. } 4. //constructor to initialize integer and string
5. ClassName(int i,String n){
Example of Constructor Overloading 6. id = i;
7. name = n;
1. //Java program to overload constructors in java 8. }
2. class Student5{ 9. //constructor to initialize another object
3. int id; 10. ClassName(ClassName c){
4. String name; 11. id = c.id;
5. int age; 12. name =c.name;
6. //creating two arg constructor 13. }
7. Student5(int i,String n){
8. id = i;
9. name = n;
Java static keyword
10. }
11. //creating three arg constructor The static keyword in Java is used for memory
12. Student5(int i,String n,int a){ management mainly. The static can be:
13. id = i;
14. name = n; 1. Variable (also known as a class variable)
15. age=a; 2. Method (also known as a class method)
16. } 3. Block
17. void display(){System.out.println(id+" "+nam 4. Nested class
e+" "+age);}
18.
19. public static void main(String args[]){ 1) The static variable gets memory only
20. Student5 s1 = new Student5(111,"Karan"); once in the class area at the time of class loading.
21. Student5 s2 = new Student5(222,"Aryan",25);
Advantages of static variable 1) this: to refer current class instance variable
class Student{
It makes your program memory efficient (i.e., it int rollno;
saves memory). Example: String name;
float fee;
static String college ="ITS";//static variable Student(int rollno,String name,float fee){
this.rollno=rollno;
2) Java static method this.name=name;
this.fee=fee;
• A static method belongs to the class rather
}
than the object of a class.
• A static method can be invoked without the
If local variables(formal arguments) and instance
need for creating an instance of a class. variables are different, there is no need to use this
• A static method can access static data keyword like in the following program:
member and can change the value of it.
class Student{
Example: int rollno;
String name;
static void change(){ float fee;
college = "BBDIT"; Student(int r,String n,float f){
rollno=r;
} name=n;
fee=f;
Restrictions for the static method
}
There are two main restrictions for the static method.
They are: 2) this: to invoke current class method
class A{
1. The static method can not use non static data
void m(){System.out.println("hello m");}
member or call non-static method directly.
2. this and super cannot be used in static context.
void n(){
System.out.println("hello n");
this.m();
3) Java static block }}

• Is used to initialize the static data member. 3) this() : to invoke current class constructor
• It is executed before the main method at the time
class A{
of classloading.
A(){System.out.println("hello a");}
A(int x){
Example of static block
this();
System.out.println(x);
1. class A2{
2. static{System.out.println("static block is invoke }}
d");}
3. public static void main(String args[]){ Inheritance in Java
4. System.out.println("Hello main");
5. }
6. } Inheritance is a mechanism in which one object
acquires all the properties and behaviours of a parent
Output: object. The idea behind inheritance in Java is that
static block is invoked you can create new classes that are built upon
Hello main existing classes.

‘this’ keyword in java Why use inheritance in java

this is a reference variable that refers to the current • For Method Overriding (so runtime
object. polymorphism can be achieved).
• For Code Reusability.
Terms used in Inheritance

• Class: A class is a group of objects which have


common properties. It is a template or blueprint
from which objects are created.
• Sub Class/Child Class: Subclass is a class
which inherits the other class. It is also called a
derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the
class from where a subclass inherits the features.
It is also called a base class or a parent class.
• Reusability: As the name specifies, reusability is Note: Multiple inheritance is not supported in
a mechanism which facilitates you to reuse the Java through class
fields and methods of the existing class when you
create a new class. You can use the same fields
and methods already defined in the previous Why multiple inheritance is not
class.
supported in java?
The syntax of Java Inheritance
Consider a scenario where A, B, and C are three
1. class Subclass-name extends Superclass-name classes. The C class inherits A and B classes. If A
2. { and B classes have the same method and you call it
3. //methods and fields from child class object, there will be ambiguity to
4. } call the method of A or B class.

The extends keyword indicates that you are making Single Inheritance Example
a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality. File: TestInheritance.java
1. class Employee{ 1. class Animal{
2. float salary=40000; 2. void eat(){System.out.println("eating...");}
3. } 3. }
4. class Programmer extends Employee{ 4. class Dog extends Animal{
5. int bonus=10000; 5. void bark(){System.out.println("barking...");}
6. public static void main(String args[]){ 6. }
7. Programmer p=new Programmer(); 7. class TestInheritance{
8. System.out.println("Programmer salary is:" 8. public static void main(String args[]){
+p.salary); 9. Dog d=new Dog();
10. d.bark();
9. System.out.println("Bonus of Programmer
11. d.eat();
is:"+p.bonus); 12. }}
10. }
11. }
Multilevel Inheritance Example
Types of inheritance in java File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat(); Java Polymorphism
16. }}
Polymorphisms are classified into:
Hierarchical Inheritance 1. Pure Polymorphism:
1. Method Overloading
Example 2. Method Overriding
2. Adhoc Polymorphism
File: TestInheritance3.java
Method Overloading (Compile
1. class Animal{
2. void eat(){System.out.println("eating...");} time Polymorphism)
3. }
4. class Dog extends Animal{ If a class has multiple methods having same name
5. void bark(){System.out.println("barking...");} but different in parameters, it is known as Method
6. } Overloading.
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");} Different ways to overload the method

9. } 1. By changing number of arguments


10. class TestInheritance3{ 2. By changing the data type
11. public static void main(String args[]){
12. Cat c=new Cat(); Note: In java, Method Overloading is not possible
13. c.meow(); by changing the return type of the method only.
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Method Overloading Example:

1. class Adder{
Forms of Inheritance 2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
Inheritance gets used for a number of purposes in
typical object-oriented programming: 4. }
5. class TestOverloading1{
specialization -- the subclass is a special case of the 6. public static void main(String[] args){
parent class (e.g. Frame and CannonWorld) 7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
specification -- the superclass just specifies which 9. }}
methods should be available but doesn't give code.
This is supported in java by interfaces and abstract Can we overload java main() method?
methods.
Yes, by method overloading. You can have any
construction -- the superclass is just used to provide number of main methods in a class by method
behavior, but instances of the subclass don't really overloading. But JVM calls main() method which
act like the superclass. Violates substitutability. receives string array as arguments only. Let's see the
Exmample: defining Stack as a subclass of Vector. simple example:
This is not clean -- better to define Stack as having a
field that holds a vector. 1. class TestOverloading4{
2. public static void main(String[] args){System.out
extension -- subclass adds new methods, and .println("main with String[]");}
perhaps redefines inherited ones as well. 3. public static void main(String args){System.out.p
rintln("main with String");}
4. public static void main(){System.out.println("mai
limitation -- the subclass restricts the inherited n without args");}
behavior. Violates substitutability. Example: 5. }
defining Queue as a subclass of Dequeue.

combination -- multiple inheritance. Provided in Type Promotion


part by implementing multiple interfaces.
One type is promoted to another implicitly if no matching Static belongs to the class area, and an instance
datatype is found. belongs to the heap area.

Can we override java main method?

No, because the main is a static method.

Ad hoc Polymorphism
We have “+” operator implemented in a
polymorphic way.

String fruits = "Apple" + "Orange";


Method Overriding in Java int a = b + c;
(Runtime Polymorphism)
Difference between method
If subclass (child class) has the same method as overloading and method
declared in the parent class, it is known as method
overriding in Java. overriding in java
Method Overloading Method Overriding
Rules for Java Method Overriding
Method overriding is
1. The method must have the same name as in the used to provide the
parent class Method overloading is
specific implementation
2. The method must have the same parameter as in used to increase the
the parent class. of the method that is
readability of the program.
3. There must be an inheritance. already provided by its
super class.
Method Overriding Example:
Method overriding
1. //Creating a parent class. occurs in two classes
Method overloading is
2. class Vehicle{ that have IS-A
performed within class.
3. //defining a method (inheritance)
4. void run(){System.out.println("Vehicle is ru relationship.
nning");}
5. } In case of method In case of method
6. //Creating a child class overloading, parameter overriding, parameter
7. class Bike2 extends Vehicle{ must be different. must be same.
8. //defining the same method as in the parent
class Method overloading is the Method overriding is
9. void run(){System.out.println("Bike is runn example of compile time the example of run time
ing safely");} polymorphism. polymorphism.
10.
11. public static void main(String args[]){ In java, method
12. Bike2 obj = new Bike2();//creating object overloading can't be
13. obj.run();//calling method Return type must be
performed by changing
14. } same or covariant in
15. } return type of the method
only. Return type can be method overriding.
Can we override static method? same or different in
method overloading. But
No, because the static method is bound with class
whereas instance method is bound with an object.
you must have to change 1. class Animal{
2. Animal(){System.out.println("animal is created")
the parameter.
;}
3. }
4. class Dog extends Animal{
Super Keyword 5. Dog(){
6. super();
The super keyword in Java is a reference variable 7. System.out.println("dog is created");
which is used to refer immediate parent class object. 8. }
9. }
10. class TestSuper3{
Usage of Java super Keyword 11. public static void main(String args[]){
12. Dog d=new Dog();
1) super is used to refer immediate parent 13. }}

class instance variable.


Final Keyword In Java
1. class Animal{
2. String color="white"; The final keyword in java is used to restrict the
3. } user. The java final keyword can be used in many
4. class Dog extends Animal{ context. Final can be:
5. String color="black";
6. void printColor(){ 1. variable
7. System.out.println(color);//prints color of Dog cl 2. method
ass 3. class
8. System.out.println(super.color);//prints color of
Animal class
9. } 1) Example of final variable
10. }
11. class TestSuper1{ If you make any variable as final, you cannot change
12. public static void main(String args[]){ the value of final variable (It will be constant).
13. Dog d=new Dog();
14. d.printColor();
1. class Bike9{
15. }}
2. final int speedlimit=90;//final variable
3. void run(){
2) super can be used to invoke parent 4. speedlimit=400;
5. }
class method 6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
1. class Animal{ 8. obj.run();
2. void eat(){System.out.println("eating...");} 9. }
3. } 10. }//end of class
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
2) Example of final method
6. void bark(){System.out.println("barking...");}
7. void work(){ If you make any method as final, you cannot
8. super.eat(); override it.
9. bark();
10. }
1. class Bike{
11. }
2. final void run(){System.out.println("running");}
12. class TestSuper2{
13. public static void main(String args[]){
3. }
14. Dog d=new Dog();
4.
15. d.work();
5. class Honda extends Bike{
16. }}
6. void run(){System.out.println("running safely
with 100kmph");}
3) super is used to invoke parent class 7.
8. public static void main(String args[]){
constructor. 9. Honda honda= new Honda();
10. honda.run();
11. } Q) What is final parameter?
12. }
If you declare any parameter as final, you cannot
3) Example of final class change the value of it.

If you make any class as final, you cannot extend it. Q) Can we declare a constructor final?

1. final class Bike{} No, because constructor is never inherited.


2. class Honda1 extends Bike{
3. void run(){System.out.println("running safely w
ith 100kmph");}
Binding
4.
5. public static void main(String args[]){ Connecting a method call to the method body is
6. Honda1 honda= new Honda1(); known as binding.
7. honda.run();
8. } There are two types of binding
9. }
1. Static Binding (also known as Early Binding).
Que) Is final method inherited? 2. Dynamic Binding (also known as Late Binding).

Ans) Yes, final method is inherited but you cannot Example of static binding
override it. For Example:
1. class Dog{
1. class Bike{ 2. private void eat(){System.out.println("dog is eati
2. final void run(){System.out.println("running...") ng...");}
;} 3.
3. } 4. public static void main(String args[]){
4. class Honda2 extends Bike{ 5. Dog d1=new Dog(); //static binding
5. public static void main(String args[]){ 6. d1.eat();
6. new Honda2().run(); 7. }
7. } 8. }
8. }
Example of dynamic binding
Que) What is blank or uninitialized final variable?
1. class Animal{
A final variable that is not initialized at the time of 2. void eat(){System.out.println("animal is eating...
declaration is known as blank final variable. ");}
3. }
It can be initialized only in constructor. Ex: 4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");
1. class Student{
}
2. int id;
7.
3. String name;
8. public static void main(String args[]){
4. final String PAN_CARD_NUMBER;
9. Animal a=new Dog(); //dynamic binding
5. ...
10. a.eat();
6. }
11. }
12. }
Que) Can we initialize blank final variable?

Yes, but only in constructor. For example: Java String


1. class Bike10{ 1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. final int speedlimit;//blank final variable 2. String s=new String(ch);
3. Bike10(){
4. speedlimit=70; (or)
5. System.out.println(speedlimit);
6. }
1. String s="javatpoint";
The java.lang.String class implements Serializable, boolean isEmpty() checks if string is empty.
Comparable and CharSequence interfaces.
concatenates the specified
Java String Example String concat(String str)
string.

1. public class StringExample{ String replace(char old, replaces all occurrences of


2. public static void main(String args[]){ char new) the specified char value.
3. String s1="java";//creating string by java string li
teral String
4. char ch[]={'s','t','r','i','n','g','s'}; replaces all occurrences of
replace(CharSequence
5. String s2=new String(ch);//converting char array the specified CharSequence.
old, CharSequence new)
to string
6. String s3=new String("example");//creating java
static String
string by new keyword compares another string. It
7. System.out.println(s1); equalsIgnoreCase(String
doesn't check case.
8. System.out.println(s2); another)
9. System.out.println(s3);
10. }} String[] split(String returns a split string
regex) matching regex.
Java String class methods
String[] split(String returns a split string
Method Description regex, int limit) matching regex and limit.
returns char value for the String intern() returns an interned string.
char charAt(int index)
particular index
returns the specified char
int length() returns string length int indexOf(int ch)
value index.
static String format(String returns the specified char
returns a formatted string.
format, Object... args) int indexOf(int ch, int
value index starting with
fromIndex)
given index.
static String
returns formatted string with
format(Locale l, String int indexOf(String returns the specified
given locale.
format, Object... args) substring) substring index.
String substring(int returns substring for given returns the specified
beginIndex) begin index. int indexOf(String
substring index starting with
substring, int fromIndex)
given index.
String substring(int returns substring for given
beginIndex, int endIndex) begin index and end index. String toLowerCase() returns a string in lowercase.
returns true or false after
boolean String returns a string in lowercase
matching the sequence of toLowerCase(Locale l) using specified locale.
contains(CharSequence s)
char value.
String toUpperCase() returns a string in uppercase.
static String
join(CharSequence String returns a string in uppercase
delimiter, returns a joined string. toUpperCase(Locale l) using specified locale.
CharSequence...
elements) removes beginning and
String trim()
ending spaces of this string.
static String
join(CharSequence converts given type into
delimiter, Iterable<? returns a joined string. static String valueOf(int
string. It is an overloaded
extends CharSequence> value)
method.
elements)

boolean equals(Object checks the equality of string Java String compare


another) with the given object.
By equals() method
By = = operator 2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
By compareTo() method 4. System.out.println(s);//Sachin Tendulkar
5. }
String compare by equals() method 6. }

1. class Teststringcomparison2{ 2) String Concatenation by concat() method


2. public static void main(String args[]){
3. String s1="Sachin"; 1. class TestStringConcatenation3{
4. String s2="SACHIN"; 2. public static void main(String args[]){
5. 3. String s1="Sachin ";
6. System.out.println(s1.equals(s2));//false 4. String s2="Tendulkar";
7. System.out.println(s1.equalsIgnoreCase(s2 5. String s3=s1.concat(s2);
));//true 6. System.out.println(s3);//Sachin Tendulkar
8. } 7. }
9. } 8. }

String compare by == operator Substring in Java


1. class Teststringcomparison3{ 1. public class TestSubstring{
2. public static void main(String args[]){ 2. public static void main(String args[]){
3. String s1="Sachin"; 3. String s="SachinTendulkar";
4. String s2="Sachin"; 4. System.out.println(s.substring(6));//Tendul
5. String s3=new String("Sachin"); kar
6. System.out.println(s1==s2);//true (because 5. System.out.println(s.substring(0,6));//Sachi
both refer to same instance) n
7. System.out.println(s1==s3);//false(because 6. }
s3 refers to instance created in nonpool) 7. }
8. } 8.
9. }
Output:
String compare by compareTo() method Tendulkar
Sachin
1. class Teststringcomparison4{
2. public static void main(String args[]){ Java String toUpperCase() and toLowerCase()
3. String s1="Sachin"; method
4. String s2="Sachin";
5. String s3="Ratan"; 1. String s="Sachin";
6. System.out.println(s1.compareTo(s2));//0 2. System.out.println(s.toUpperCase());//SACH
7. System.out.println(s1.compareTo(s3));//1(b IN
ecause s1>s3) 3. System.out.println(s.toLowerCase());//sachin
8. System.out.println(s3.compareTo(s1));//-
1(because s3 < s1 ) 4. System.out.println(s);//Sachin(no change in o
9. } riginal)
10. }
Java String trim() method
String Concatenation in Java
1. String s=" Sachin ";
2. System.out.println(s);// Sachin
1. By + (string concatenation) operator
3. System.out.println(s.trim());//Sachin
2. By concat() method
Java String charAt() method
1) String Concatenation by + (string
concatenation) operator 1. String s="Sachin";
2. System.out.println(s.charAt(0));//S
1. class TestStringConcatenation1{ 3. System.out.println(s.charAt(3));//h
Java String length() method 4) StringBuffer delete() method

1. String s="Sachin"; 1. class StringBufferExample4{


2. System.out.println(s.length());//6 2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
Java String valueOf() method 4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
1. int a=10; 6. }
2. String s=String.valueOf(a); 7. }
3. System.out.println(s+10); //1010
5) StringBuffer reverse() method
Java String replace() method 1. class StringBufferExample5{
String s1="Java is a programming language. Java is 2. public static void main(String args[]){
a platform. Java is an Island."; 3. StringBuffer sb=new StringBuffer("Hello");
String replaceString=s1.replace("Java","Kava");//rep 4. sb.reverse();
laces all occurrences of "Java" to "Kava" 5. System.out.println(sb);//prints olleH
System.out.println(replaceString); 6. }
7. }
Java StringBuffer class
1) StringBuffer append() method

1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");

4. sb.append("Java");//now original string is ch


anged
5. System.out.println(sb);//prints Hello Java
6. }
7. }

2) StringBuffer insert() method

1. class StringBufferExample2{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");

4. sb.insert(1,"Java");//now original string is ch


anged
5. System.out.println(sb);//prints HJavaello
6. }
7. }

3) StringBuffer replace() method

1. class StringBufferExample3{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
UNIT-2 Interface in Java
PACKAGES & An interface in java is a blueprint of a class. It has
static constants and abstract methods.
INTERFACES
The interface in Java is a mechanism to achieve
Abstraction in Java abstraction. There can be only abstract methods in
the Java interface, not method body.
Abstraction is a process of hiding the
implementation details and showing only Uses:
functionality to the user.
1. to achieve abstraction.
Ways to achieve Abstraction 2. multiple inheritance in Java.
Interface Syntax:
There are two ways to achieve abstraction in java
1. interface <interface_name>{
1. Abstract class (0 to 100%) 2.
2. Interface (100%) 3. // declare constant fields
4. // declare methods that abstract
Abstract class in Java 5. // by default.
6. }
A class which is declared as abstract is known as an
abstract class. The relationship between classes
and interfaces
Rules for Abstract Class:

• 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

1. abstract class A{} Java Interface Example


1. interface printable{
Example of abstract method
2. void print();
3. }
1. abstract void printStatus();//no method body 4. class A6 implements printable{
and abstract 5. public void print(){System.out.println("Hello");}

Example of Abstract class with an abstract 6.


method 7. public static void main(String args[]){
8. A6 obj = new A6();
1. abstract class Bike{ 9. obj.print();
2. abstract void run(); 10. }
3. } 11. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");} Multiple inheritance in Java by
6. public static void main(String args[]){ interface
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }
5. }
6. }

Difference between abstract


class and interface
Abstract class Interface
Example:
Interface can have only
1. interface Printable{ 1) Abstract class can abstract methods. Since
2. void print(); have abstract and non- Java 8, it can have
3. } abstract methods. default and static
4. interface Showable{ methods also.
5. void show(); 2) Abstract class doesn't
Interface supports
6. } support multiple
multiple inheritance.
7. class A7 implements Printable,Showable{ inheritance.
8. public void print(){System.out.println("Hello 3) Abstract class can
");} have final, non-final, Interface has only static
9. public void show(){System.out.println("Wel static and non-static and final variables.
come");} variables.
10.
11. public static void main(String args[]){ 4) Abstract class can
Interface can't provide
12. A7 obj = new A7(); provide the
the implementation of
13. obj.print(); implementation of
abstract class.
14. obj.show(); interface.
15. } 5) The abstract
The interface keyword is
16. } keyword is used to
used to declare interface.
declare abstract class.
Interface inheritance 6) An abstract class can
An interface can extend
extend another Java
another Java interface
A class implements an interface, but one interface class and implement
only.
extends another interface. multiple Java interfaces.
7) An abstract class can An interface class can be
1. interface Printable{ be extended using implemented using
2. void print(); keyword "extends". keyword "implements".
3. }
4. interface Showable extends Printable{ 8) A Java abstract class
Members of a Java
5. void show(); can have class members
interface are public by
6. } like private, protected,
default.
7. class TestInterface4 implements Showable{ etc.
8. public void print(){System.out.println("Hello");} 9)Example:
Example:
public abstract class
9. public void show(){System.out.println("Welcom public interface
Shape{
e");} Drawable{
public abstract void
10. void draw();
11. public static void main(String args[]){ draw();
}
12. TestInterface4 obj = new TestInterface4(); }
13. obj.print();
14. obj.show();
15. } Java Package
16. }
A java package is a group of similar types of
Nested Interface in Java
classes, interfaces and sub-packages.
1. interface printable{ Package in java can be categorized in:
2. void print();
1. built-in package
3. interface MessagePrintable{
2. user-defined package.
4. void msg();
There are many built-in packages such as java, lang, 2. import package.classname;
awt, javax, swing, net, io, util, sql etc.
1. //save by A.java
Advantage of Java Package 2.
3. package pack;
4. public class A{
1) Java package is used to categorize the classes and
5. public void msg(){System.out.println("Hell
interfaces so that they can be easily maintained.
o");}
6. }
2) Java package provides access protection.
1. //save by B.java
3) Java package removes naming collision.
2. package mypack;
3. import pack.A;
Package Example: 4.
package mypack; 5. class B{
public class Simple{ 6. public static void main(String args[]){
public static void main(String args[]){ 7. A obj = new A();
System.out.println("Welcome to package"); 8. obj.msg();
} 9. }
} 10. }

Output:Hello
How to run java package
program 3. fully qualified name.
To Compile: javac -d . Simple.java 1. //save by A.java
To Run: java mypack.Simple 2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hell
How to access package from o");}
another package? 5. }

1. import package.*; 1. //save by B.java


2. package mypack;
1. //save by A.java 3. class B{
2. package pack; 4. public static void main(String args[]){
3. public class A{ 5. pack.A obj = new pack.A();//using fully qu
4. public void msg(){System.out.println("Hell alified name
o");} 6. obj.msg();
5. } 7. }
8. }
1. //save by B.java
Output:Hello
2. package mypack;
3. import pack.*;
Note: Sequence of the program must be
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }

Output:Hello
Subpackage in java
Example of Subpackage

1. package com.javatpoint.core;
2. class Simple{ 1. //save as Simple.java
3. public static void main(String args[]){ 2. package mypack;
4. System.out.println("Hello subpackage"); 3. public class Simple{
5. } 4. public static void main(String args[]){
6. } 5. System.out.println("Welcome to package")
;
To Compile: javac -d . Simple.java 6. }
To Run: java com.javatpoint.core.Simple 7. }

Output:Hello subpackage To Compile:

How to send the class file to e:\sources> javac -d c:\classes Simple.java

another directory or drive? To Run:


To run this program from e:\source directory, you
There is a scenario, I want to put the class file of need to set classpath of the directory where the
A.java source file in classes folder of c: drive. For
class file resides.
example:
e:\sources> set classpath=c:\classes;.;

e:\sources> java mypack.Simple

Access Modifiers in java


The access modifiers specifies scope of a data
member, method, constructor or class.

There are 4 types of java access modifiers:

1. private
2. default
3. protected
4. public
1) private access modifier 5. }
The private access modifier is accessible only within
class. 1. //save by B.java
2. package mypack;
1. class A{ 3. import pack.*;
2. private int data=40; 4.
3. private void msg(){System.out.println("Hello 5. class B extends A{
java");} 6. public static void main(String args[]){
4. } 7. B obj = new B();
5. 8. obj.msg();
6. public class Simple{ 9. }
7. public static void main(String args[]){ 10. }
8. A obj=new A();
9. System.out.println(obj.data);//Compile Tim 4) public access modifier
e Error The public access modifier is accessible
10. obj.msg();//Compile Time Error everywhere. It has the widest scope among all other
11. } modifiers.
12. }

2) default access modifier 1. //save by A.java


If you don't use any modifier, it is treated as default 2.
by default. The default modifier is accessible only 3. package pack;
4. public class A{
within package.
5. public void msg(){System.out.println("Hello
");}
1. //save by A.java
6. }
2. package pack;
3. class A{
1. //save by B.java
4. void msg(){System.out.println("Hello");}
2.
5. }
3. package mypack;
4. import pack.*;
1. //save by B.java
5.
2. package mypack;
6. class B{
3. import pack.*;
7. public static void main(String args[]){
4. class B{
8. A obj = new A();
5. public static void main(String args[]){
9. obj.msg();
6. A obj = new A();//Compile Time Error
10. }
7. obj.msg();//Compile Time Error
11. }
8. }
9. }
Understanding all java access modifiers
outside
3) protected access modifier Access within within package by outside
Modifier class package subclass package
The protected access modifier is accessible within only
package and outside the package but through
inheritance only. Private Y N N N

The protected access modifier can be applied on the Default Y Y N N


data member, method and constructor. It can't be
applied on the class. Protected Y Y Y N

Public Y Y Y Y
1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("He
llo");}
Object class in Java Wrapper class in Java
The Object class is the parent class of all the classes Wrapper class in java provides the mechanism to
in java by default. In other words, it is the topmost convert primitive into object and object into
class of java. primitive.

Java Math class Since J2SE 5.0, autoboxing and unboxing feature
converts primitive into object and object into
primitive automatically. The automatic conversion
1. public class JavaMathExample1
of primitive into object is known as autoboxing and
2. {
vice-versa unboxing.
3. public static void main(String[] args)
4. {
The eight classes of java.lang package are known as
5. double x = 28;
wrapper classes in java. The list of eight wrapper
6. double y = 4;
classes are given below:
7.
8. // return the maximum of two numbers
9. System.out.println("Maximum number Primitive Type Wrapper class
of x and y is: " +Math.max(x, y));
10. boolean Boolean
11. // return the square root of y
12. System.out.println("Square root of y is: char Character
" + Math.sqrt(y));
13. byte Byte
14. //returns 28 power of 4 i.e. 28*28*28*2
short Short
8
15. System.out.println("Power of x and y is:
int Integer
" + Math.pow(x, y));
16. long Long
17. // return the logarithm of given value
float Float
18. System.out.println("Logarithm of x is: "
+ Math.log(x)); double Double
19. System.out.println("Logarithm of y is: "
+ Math.log(y));
20.
21. // return the logarithm of given value wh
Wrapper class Example: Primitive to
en base is 10 Wrapper
22. System.out.println("log10 of x is: " + M
ath.log10(x)); 1. public class WrapperExample1{
23. System.out.println("log10 of y is: " + M 2. public static void main(String args[]){
ath.log10(y)); 3. //Converting int into Integer
24. 4. int a=20;
25. // return the log of x + 1 5. Integer i=Integer.valueOf(a);//converting int
26. System.out.println("log1p of x is: " +Ma into Integer
th.log1p(x)); 6. Integer j=a;//autoboxing, now compiler will
27. write Integer.valueOf(a) internally
28. // return a power of 2 7.
29. System.out.println("exp of a is: " +Math 8. System.out.println(a+" "+i+" "+j);
.exp(x)); 9. }}
30.
31. // return (a power of 2)-1 Wrapper class Example: Wrapper to
32. System.out.println("expm1 of a is: " +M
ath.expm1(x));
Primitive
33. }
1. public class WrapperExample2{
34. }
2. public static void main(String args[]){
3. //Converting Integer to int 4) public void
is used to close the current
4. Integer a=new Integer(3); close()throws
output stream.
5. int i=a.intValue();//converting Integer to int IOException
6. int j=a;//unboxing, now compiler will write a
.intValue() internally OutputStream Hierarchy
7.
8. System.out.println(a+" "+i+" "+j);
9. }}

Java I/O (java.io.*)


Java I/O (Input and Output) is used to process the
input and produce the output.

Stream InputStream class methods


A stream is a sequence of data. In Java, a stream is Method Description
composed of bytes. It's called a stream because it is
1) public abstract int reads the next byte of data from
like a stream of water that continues to flow.
read()throws the input stream. It returns -1 at
IOException the end of the file.
1) System.out: standard output stream
2) public int returns an estimate of the
2) System.in: standard input stream available()throws number of bytes that can be read
IOException from the current input stream.
3) System.err: standard error stream
3) public void
is used to close the current input
close()throws
stream.
IOException

InputStream Hierarchy

OutputStream class
OutputStream class is an abstract class. It is the
superclass of all classes representing an output
stream of bytes.
FileOutputStream class methods
Useful methods of OutputStream
Method Description Method Description

1) public void protected void It is used to clean up the connection


is used to write a byte to the
write(int)throws finalize() with the file output stream.
current output stream.
IOException
It is used to write ary.length bytes
2) public void is used to write an array of void write(byte[]
from the byte array to the file output
write(byte[])throws byte to the current output ary)
stream.
IOException stream.
void write(byte[] It is used to write len bytes from the
3) public void ary, int off, int byte array starting at offset off to the
flushes the current output
flush()throws len) file output stream.
stream.
IOException
It is used to write the specified byte
void write(int b)
to the file output stream.
It is used to closes the file output int read(byte[] b, It is used to read up to len bytes of
void close()
stream. int off, int len) data from the input stream.

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


FileOutputStream Example 1:
write byte FileInputStream example 1:
1. import java.io.FileOutputStream; read single character
2. public class FileOutputStreamExample {
3. public static void main(String args[]){ 1. import java.io.FileInputStream;
4. try{ 2. public class DataStreamExample {
5. FileOutputStream fout=new FileOutputS 3. public static void main(String args[]){
tream("D:\\testout.txt"); 4. try{
6. fout.write(65); 5. FileInputStream fin=new FileInputStream
7. fout.close(); ("D:\\testout.txt");
8. System.out.println("success..."); 6. int i=fin.read();
9. }catch(Exception e){System.out.println(e 7. System.out.print((char)i); //(char)
);} required to convert byte stream into characters
10. } 8. fin.close();
11. } 9. }catch(Exception e){System.out.println(e);
}
10. }
FileOutputStream example 2: 11. }
write string
Java FileInputStream example
1. import java.io.FileOutputStream;
2. public class FileOutputStreamExample { 2: read all characters
3. public static void main(String args[]){
4. try{ 1. package com.javatpoint;
5. FileOutputStream fout=new FileOutputS 2.
tream("D:\\testout.txt"); 3. import java.io.FileInputStream;
6. String s="Welcome to javaTpoint."; 4. public class DataStreamExample {
7. byte b[]=s.getBytes();//converting string 5. public static void main(String args[]){
into byte array 6. try{
8. fout.write(b); 7. FileInputStream fin=new FileInputStream
9. fout.close(); ("D:\\testout.txt");
10. System.out.println("success..."); 8. int i=0;
11. }catch(Exception e){System.out.println(e 9. while((i=fin.read())!=-1){
);} 10. System.out.print((char)i);
12. } 11. }
13. } 12. fin.close();
13. }catch(Exception e){System.out.println(e);
}
FileInputStream class methods 14. }
15. }
Method Description

It is used to return the estimated BufferedOutputStream class


int available() number of bytes that can be read methods
from the input stream.

It is used to read the byte of data


Method Description
int read()
from the input stream.
It writes the specified byte to the
void write(int b)
It is used to read up to b.length bytes buffered output stream.
int read(byte[] b)
of data from the input stream.
It write the bytes from the 7. FileInputStream fin=new FileInputStream("D:\
void write(byte[] \testout.txt");
specified byte-input stream into a
b, int off, int 8. BufferedInputStream bin=new BufferedInputS
specified byte array, starting with tream(fin);
len)
the given offset 9. int i;
10. while((i=bin.read())!=-1){
It flushes the buffered output 11. System.out.print((char)i);
void flush()
stream. 12. }
13. bin.close();
14. fin.close();
15. }catch(Exception e){System.out.println(e);}
BufferedOutputStream class 16. }
Example: 17. }

1. package com.javatpoint; ByteArrayOutputStream class


2. import java.io.*;
3. public class BufferedOutputStreamExample{ methods
4. public static void main(String args[])throws Exce
ption{ Method Description
5. FileOutputStream fout=new FileOutputStrea
m("D:\\testout.txt"); It is used to returns the current
6. BufferedOutputStream bout=new BufferedOu int size()
size of a buffer.
tputStream(fout);
7. String s="Welcome to javaTpoint."; It is used for writing the byte
8. byte b[]=s.getBytes(); void write(int b) specified to the byte array output
9. bout.write(b);
stream.
10. bout.flush();
11. bout.close();
It is used for writing len bytes
12. fout.close();
13. System.out.println("success"); void write(byte[] b, int from specified byte array
14. } off, int len starting from the offset off to the
15. } byte array output stream.

It is used for writing the


BufferedInputStream class void
complete content of a byte array
writeTo(OutputStream
methods out)
output stream to the specified
output stream.
Method Description It is used to close the
void close()
It read the next byte of data ByteArrayOutputStream.
int read()
from the input stream.
It read the bytes from the
int read(byte[] b, specified byte-input stream Example of
int off, int ln) into a specified byte array, ByteArrayOutputStream
starting with the given offset.
It closes the input stream and 1. package com.javatpoint;
releases any of the system 2. import java.io.*;
void close()
resources associated with the 3. public class DataStreamExample {
stream. 4. public static void main(String args[])throws Exce
ption{
5. FileOutputStream fout1=new FileOutputStrea
BufferedInputStream Example: m("D:\\f1.txt");
6. FileOutputStream fout2=new FileOutputStrea
m("D:\\f2.txt");
1. package com.javatpoint; 7.
2. 8. ByteArrayOutputStream bout=new ByteArra
3. import java.io.*; yOutputStream();
4. public class BufferedInputStreamExample{ 9. bout.write(65);
5. public static void main(String args[]){ 10. bout.writeTo(fout1);
6. try{ 11. bout.writeTo(fout2);
12. It is used to write the specified byte
13. bout.flush(); void write(int b)
to the underlying output stream.
14. bout.close();//has no effect
15. System.out.println("Success..."); void write(byte[] b, It is used to write len bytes of data
16. } int off, int len) to the output stream.
17. }
void
It is used to write Boolean to the
ByteArrayInputStream class writeBoolean(boole
output stream as a 1-byte value.
an v)
methods
void writeChar(int It is used to write char to the output
Methods Description v) stream as a 2-byte value.

It is used to read the next byte of void It is used to write string to the
int read()
data from the input stream. writeChars(String output stream as a sequence of
s) characters.
int read(byte[] It is used to read up to len bytes of
ary, int off, int data from an array of bytes in the void writeByte(int It is used to write a byte to the
len) input stream. v) output stream as a 1-byte value.

It is used for closing a void It is used to write string to the


void close()
ByteArrayInputStream. writeBytes(String output stream as a sequence of
s) bytes.

Example of It is used to write an int to the


void writeInt(int v)
output stream
ByteArrayInputStream
void writeShort(int It is used to write a short to the
1. package com.javatpoint; v) output stream.
2. import java.io.*;
3. public class ReadExample { void writeShort(int It is used to write a short to the
4. public static void main(String[] args) throws IO v) output stream.
Exception {
5. byte[] buf = { 35, 36, 37, 38 }; void It is used to write a long to the
6. // Create the new byte array input stream writeLong(long v) output stream.
7. ByteArrayInputStream byt = new ByteArrayIn
putStream(buf); void It is used to write a string to the
8. int k = 0; writeUTF(String output stream using UTF-8
9. while ((k = byt.read()) != -1) { str) encoding in portable manner.
10. //Conversion of a byte into character
11. char ch = (char) k; It is used to flushes the data output
12. System.out.println("ASCII value of Character void flush()
stream.
is:" + k + "; Special character is: " + ch);
13. }
14. } Example of DataOutputStream
15. }
class
DataOutputStream class 1. package com.javatpoint;
methods 2.
3. import java.io.*;
4. public class OutputExample {
Method Description 5. public static void main(String[] args) throws I
OException {
It is used to return the number of 6. FileOutputStream file = new FileOutputStre
int size() bytes written to the data output am(D:\\testout.txt);
stream. 7. DataOutputStream data = new DataOutputSt
ream(file);
8. data.writeInt(65);
9. data.flush();
10. data.close(); 14. }
11. System.out.println("Succcess..."); 15. }
12. }
13. }
Console class methods
DataInputStream class Methods Method Description

Method Description It is used to read a single line


String readLine()
of text from the console.
It is used to read the number of
int read(byte[] b)
bytes from the input stream. String It provides a formatted
readLine(String fmt, prompt then reads the single
int read(byte[] b, It is used to read len bytes of data Object... args) line of text from the console.
int off, int len) from the input stream.
Console It is used to write a formatted
It is used to read input bytes and format(String fmt, string to the console output
int readInt()
return an int value. Object... args) stream.

It is used to read and return the Console


byte readByte() It is used to write a string to
one input byte. printf(String format,
the console output stream.
Object... args)
It is used to read two input bytes
char readChar()
and returns a char value. It is used to flushes the
void flush()
console.
double It is used to read eight input bytes
readDouble() and returns a double value.

It is used to read one input byte Console Example


boolean
and return true if byte is non zero,
readBoolean() 1. import java.io.Console;
false if byte is zero.
2. class ReadStringTest{
It is used to read a string that has 3. public static void main(String args[]){
4. Console c=System.console();
String readUTF() been encoded using the UTF-8
5. System.out.println("Enter your name: ");
format.
6. String n=c.readLine();
7. System.out.println("Welcome "+n);
8. }
Example of DataInputStream 9. }
class
BufferedWriter Class methods
In this example, we are reading the data from the file
testout.txt file. Method Description
void It is used to add a new line by
1. package com.javatpoint; newLine() writing a line separator.
2. import java.io.*;
3. public class DataStreamExample { void write(int
It is used to write a single character.
4. public static void main(String[] args) throws IO c)
Exception { void flush() It is used to flushes the input stream.
5. InputStream input = new FileInputStream("D:\
\testout.txt"); void close() It is used to closes the input stream
6. DataInputStream inst = new DataInputStream(
input);
7. int count = input.available(); Example of BufferedWriter
8. byte[] ary = new byte[count];
9. inst.read(ary); 1. package com.javatpoint;
10. for (byte bt : ary) { 2. import java.io.*;
11. char k = (char) bt; 3. public class BufferedWriterExample {
12. System.out.print(k+"-"); 4. public static void main(String[] args) throws Exc
13. } eption {
5. FileWriter writer = new FileWriter("D:\\testout It tests whether the application
.txt"); boolean canWrite() can modify the file denoted by
6. BufferedWriter buffer = new BufferedWriter( this abstract pathname.String[]
writer);
7. buffer.write("Welcome to javaTpoint."); It tests whether the application
8. buffer.close(); boolean canExecute() can execute the file denoted by
9. System.out.println("Success");
this abstract pathname.
10. }
11. }
It tests whether the application
boolean canRead() can read the file denoted by this
BufferedReader class methods abstract pathname.

Method Description It tests whether this abstract


boolean isAbsolute()
pathname is absolute.
It is used for reading a single
int read() It tests whether the file denoted
character.
boolean isDirectory() by this abstract pathname is a
String readLine() It is used for reading a line of text. directory.

It closes the input stream and It tests whether the file denoted
void close() releases any of the system resources boolean isFile() by this abstract pathname is a
associated with the stream. normal file.

It returns the name of the file or


String getName() directory denoted by this
BufferedReader Example abstract pathname.
1. package com.javatpoint; It returns the pathname string of
2. import java.io.*; this abstract pathname's parent,
3. public class BufferedReaderExample { String getParent()
or null if this pathname does not
4. public static void main(String args[])throws Ex
name a parent directory.
ception{
5. FileReader fr=new FileReader("D:\\testout.
It returns an array of abstract
txt");
6. BufferedReader br=new BufferedReader(fr pathnames denoting the files in
File[] listFiles()
); the directory denoted by this
7. abstract pathname
8. int i;
9. while((i=br.read())!=-1){ It creates the directory named by
boolean mkdir()
10. System.out.print((char)i); this abstract pathname.
11. }
12. br.close();
13. fr.close(); File Example
14. }
15. }
1. import java.io.*;
2. public class FileDemo2 {
File Class Methods 3. public static void main(String[] args) {
Modifie 4.
5. String path = "";
r and Method Description
6. boolean bool = false;
Type 7. try {
8. // createing new files
It atomically creates a new, 9. File file = new File("testFile1.txt");
empty file named by this 10. file.createNewFile();
createNewFi
boolean abstract pathname if and only if 11. System.out.println(file);
le()
a file with this name does not 12. // createing new canonical from file objec
yet exist. t
13. File file2 = file.getCanonicalFile();
14. // returns true if the file exists
15. System.out.println(file2);
16. bool = file2.exists(); 11. e.printStackTrace();
17. // returns absolute pathname 12. }
18. path = file2.getAbsolutePath(); 13. }
19. System.out.println(bool); 14. private static byte[] readFromFile(String filePa
20. // if file exists th, int position, int size)
21. if (bool) { 15. throws IOException {
22. // prints 16. RandomAccessFile file = new RandomAcce
23. System.out.print(path + " Exists? " + b ssFile(filePath, "r");
ool); 17. file.seek(position);
24. } 18. byte[] bytes = new byte[size];
25. } catch (Exception e) { 19. file.read(bytes);
26. // if any error occurs 20. file.close();
27. e.printStackTrace(); 21. return bytes;
28. } 22. }
29. } 23. private static void writeToFile(String filePath,
30. } String data, int position)
24. throws IOException {
25. RandomAccessFile file = new RandomAcce
RandomAccessFile Methods ssFile(filePath, "rw");
Modifier 26. file.seek(position);
Method Method 27. file.write(data.getBytes());
and Type
28. file.close();
It closes this random 29. }
access file stream and 30. }
void close() releases any system
resources associated Scanner Class Methods
with the stream.
Modifier
It reads a signed 32-bit Method Description
int readInt() & Type
integer from this file.
void close() It is used to close this scanner.
It reads in a string from
String readUTF()
this file.
It returns true if this scanner
boolean hasNext()
has another token in its input.
It writes the specified
void write(int b)
byte to this file.
It is used to check if the next
token in this scanner's input
It reads a byte of data
int read() hasNextBig can be interpreted as a
from this file. boolean
Decimal() BigDecimal using the
It returns the length of nextBigDecimal() method or
long length() not.
this file.
It is used to check if the next
token in this scanner's input
hasNextBigI can be interpreted as a
RandomAccessFile Example boolean
nteger() BigDecimal using the
nextBigDecimal() method or
1. import java.io.IOException; not.
2. import java.io.RandomAccessFile;
3. It is used to check if the next
4. public class RandomAccessFileExample { token in this scanner's input
5. static final String FILEPATH ="myFile.TXT"; hasNextBool
boolean can be interpreted as a
ean()
Boolean using the
6. public static void main(String[] args) {
7. try { nextBoolean() method or not.
8. System.out.println(new String(readFromF
ile(FILEPATH, 0, 18))); hasNextByte It is used to check if the next
boolean token in this scanner's input
9. writeToFile(FILEPATH, "I love my coun ()
try and my people", 31); can be interpreted as a Byte
10. } catch (IOException e) {
using the nextBigDecimal() It scans the next token of the
int nextInt()
method or not. input as an Int.

It is used to check if the next It is used to get the input string


token in this scanner's input String nextLine() that was skipped of the
hasNextDou
boolean can be interpreted as a Scanner object.
ble()
BigDecimal using the
nextByte() method or not. It scans the next token of the
long nextLong()
input as a long.
It is used to check if the next
token in this scanner's input It scans the next token of the
hasNextFloat short nextShort()
boolean can be interpreted as a Float input as a short.
()
using the nextFloat() method
or not.
Scanner Class Example
It is used to check if the next
token in this scanner's input 1. import java.util.*;
boolean hasNextInt() can be interpreted as an int 2. public class ScannerClassExample1 {
using the nextInt() method or 3. public static void main(String args[]){
not.
4. String s = "Hello, This is JavaTpoint.";
It is used to check if there is 5. //Create scanner Object and pass string in it
hasNextLine
boolean another line in the input of this
()
scanner or not. 6. Scanner scan = new Scanner(s);
7. //Check if the scanner has a token
It is used to check if the next 8. System.out.println("Boolean Result: " + sc
token in this scanner's input an.hasNext());
hasNextLong 9. //Print the string
boolean can be interpreted as a Long
() 10. System.out.println("String: " +scan.nextLi
using the nextLong() method
ne());
or not.
11. scan.close();
12. System.out.println("--------
It is used to check if the next
Enter Your Details-------- ");
token in this scanner's input
hasNextShor 13. Scanner in = new Scanner(System.in);
boolean can be interpreted as a Short 14. System.out.print("Enter your name: ");
t()
using the nextShort() method 15. String name = in.next();
or not. 16. System.out.println("Name: " + name);

It is used to get the 17. System.out.print("Enter your age: ");


IOExcepti ioException(
IOException last thrown by 18. int i = in.nextInt();
on )
this Scanner's readable. 19. System.out.println("Age: " + i);
20. System.out.print("Enter your salary: ");
It is used to get the next 21. double d = in.nextDouble();
String next() complete token from the 22. System.out.println("Salary: " + d);
scanner which is in use. 23. in.close();
24. }
It scans the next token of the 25. }
nextBoolean(
boolean input into a boolean value and
)
returns that value. Serialization and Deserialization
byte nextByte()
It scans the next token of the in Java
input as a byte.
Serialization in Java is a mechanism of writing the
It scans the next token of the
double nextDouble() state of an object into a byte stream.
input as a double.

It scans the next token of the Advantages of Java Serialization


float nextFloat()
input as a float.
It is mainly used to travel object's state on the
network (which is known as marshaling).
Example of Enum

1. class EnumExample1{
2. public enum Season { WINTER, SPRING, SUM
MER, FALL }
3. public static void main(String[] args) {
4. for (Season s : Season.values())
5. System.out.println(s);
6.
7. }}

java.io.Serializable interface
Example
1. import java.io.Serializable;
2. public class Student implements Serializable
{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }

In the above example, Student class implements


Serializable interface. Now its objects can be
converted into stream.

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

Enumeration
Enum in java is a data type that contains fixed set
of constants.

Points to remember for Enum


• enum improves type safety
• enum can be easily used in switch
• enum can be traversed
• enum can have fields, constructors and methods
• enum may implement many interfaces but cannot
extend any class because it internally extends
Enum class
UNIT-3
EXCEPTION HANDLING
& MULTITHREADING
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 ClassNotFound, IO, SQL,
Remote etc.
Difference between Checked and
Advantage of Exception Unchecked Exceptions
Handling
1) Checked Exception
The core advantage of exception handling is to
maintain the normal flow of the application. The classes which directly inherit Throwable class
except RuntimeException and Error are known as
1. statement 1; checked exceptions e.g. IOException,
2. statement 2;//exception occurs SQLException etc. Checked exceptions are checked
3. statement 3; at compile-time.

2) Unchecked Exception
Types of Java Exceptions
The classes which inherit RuntimeException are
There are mainly two types of exceptions: checked known as unchecked exceptions e.g.
and unchecked. Here, an error is considered as the ArithmeticException, NullPointerException,
unchecked exception. According to Oracle, there are ArrayIndexOutOfBoundsException etc. Unchecked
three types of exceptions: exceptions are not checked at compile-time, but they
are checked at runtime.
1. Checked Exception
2. Unchecked Exception
3) Error
3. Error

Error is irrecoverable e.g. OutOfMemoryError,


Hierarchy of Exception classes VirtualMachineError, AssertionError etc.

Exception Keywords
There are 5 keywords which are used in handling
exceptions in Java.
Keyword Description

The "try" keyword is used to specify a block


where we should place exception code. The
try
try block must be followed by either catch or
finally. It means, we can't use try block alone.

The "catch" block is used to handle the


exception. It must be preceded by try block
catch
which means we can't use catch block alone.
It can be followed by finally block later.

The "finally" block is used to execute the


finally important code of the program. It is executed
whether an exception is handled or not.
Multi Catch block example
The "throw" keyword is used to throw an
throw 1. public class TestMultipleCatchBlock{
exception.
2. public static void main(String args[]){
The "throws" keyword is used to declare 3. try{
exceptions. It doesn't throw an exception. It 4. int a[]=new int[5];
5. a[5]=30/0;
throws specifies that there may occur an exception in
6. }
the method. It is always used with method
7. catch(ArithmeticException e){System.out.print
signature. ln("task1 is completed");}
8. catch(ArrayIndexOutOfBoundsException e){S
ystem.out.println("task 2 completed");}
Exception Handling Example 9. catch(Exception e){System.out.println("commo
n task completed");}
using Try-Catch: 10.
11. System.out.println("rest of the code...");
1. public class JavaExceptionExample{ 12. }
2. public static void main(String args[]){ 13. }
3. try{
4. //code that may raise exception Rule: At a time only one Exception is occured
5. int data=100/0; and at a time only one catch block is executed.
6. }catch(ArithmeticException e){System.out.prin
tln(e);}
Rule: All catch blocks must be ordered from
7. //rest code of the program
8. System.out.println("rest of the code..."); most specific to most general i.e. catch for
9. } ArithmeticException must come before catch for
10. } Exception .

Internal working of java try- Nested try example


catch block 1. class Excep6{
2. public static void main(String args[]){
If exception is handled by the application programmer, 3. try{
normal flow of the application is maintained i.e. rest of 4. try{
the code is executed. 5. System.out.println("going to divide");
6. int b =39/0;
7. }catch(ArithmeticException e){System.out.pri
ntln(e);}
8.
9. try{
10. int a[]=new int[5];
11. a[5]=4;
12. }catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);}
13.
14. System.out.println("other statement); by causing a fatal error that causes the process to
15. }catch(Exception e){System.out.println("handel abort).
ed");}
16.
17. System.out.println("normal flow.."); Throw example
18. }
19. } 1. public class TestThrow1{
2. static void validate(int age){
3. if(age<18)
Finally Block 4. throw new ArithmeticException("not valid");

5. else
6. System.out.println("welcome to vote");
7. }
8. public static void main(String args[]){
9. validate(13);
10. System.out.println("rest of the code...");
11. }
12. }

throws keyword
The Java throws keyword is used to declare an
exception. It gives an information to the programmer
that there may occur an exception so it is better for
the programmer to provide the exception handling
code so that normal flow can be maintained.

throws example
1. import java.io.IOException;
2. class Testthrows1{
Note: If you don't handle exception, before 3. void m()throws IOException{
terminating the program, JVM executes finally 4. throw new IOException("device error");//chec
block(if any). ked exception
5. }
6. void n()throws IOException{
Finally example: 7. m();
8. }
1. class TestFinallyBlock{ 9. void p(){
2. public static void main(String args[]){ 10. try{
3. try{ 11. n();
4. int data=25/5; 12. }catch(Exception e){System.out.println("excep
5. System.out.println(data); tion handled");}
6. } 13. }
7. catch(NullPointerException e){System.out.print 14. public static void main(String args[]){
ln(e);} 15. Testthrows1 obj=new Testthrows1();
8. finally{System.out.println("finally block is alwa 16. obj.p();
ys executed");} 17. System.out.println("normal flow...");
9. System.out.println("rest of the code..."); 18. }
10. } 19. }
11. }

Rule: For each try block there can be zero or Difference between throw and
more catch blocks, but only one finally block. throws in Java
throw throws
Note: The finally block will not be executed if
program exits(either by calling System.exit() or
Java throw keyword is
Java throws keyword is used Java finalize example
used to explicitly throw
to declare an exception.
an exception. 1. class FinalizeExample{
2. public void finalize(){System.out.println("finaliz
Checked exception e called");}
Checked exception can be
cannot be propagated 3. public static void main(String[] args){
propagated with throws.
using throw only. 4. FinalizeExample f1=new FinalizeExample();
5. FinalizeExample f2=new FinalizeExample();
Throw is followed by an 6. f1=null;
Throws is followed by class.
instance. 7. f2=null;
8. System.gc();
Throw is used within Throws is used with the 9. }}
the method. method signature.

You can declare multiple Java Custom/user defined


You cannot throw exceptions e.g. Exception example
multiple exceptions. public void method()throws
IOException, SQLException.
1. class TestCustomException1{
2.
3. static void validate(int age)throws InvalidA
Difference between final, finally geException{
and finalize 4. if(age<18)
5. throw new InvalidAgeException("not val
final finally finalize
id");
Final is used to apply 6. else
Finally is used Finalize is 7. System.out.println("welcome to vote");
restrictions on class,
to place used to 8. }
method and variable.
important perform clean 9.
Final class can't be
code, it will be up processing 10. public static void main(String args[]){
inherited, final method
executed just before 11. try{
can't be overridden
whether object is 12. validate(13);
and final variable
exception is garbage 13. }catch(Exception m){System.out.println(
value can't be
handled or not. collected. "Exception occured: "+m);}
changed.
14.
Finally is a Finalize is a 15. System.out.println("rest of the code...");
Final is a keyword.
block. method. 16. }
17. }

Java final example Multithreading in Java


1. class FinalExample{ A process of executing multiple threads
2. public static void main(String[] args){ simultaneously.
3. final int x=100;
4. x=200;//Compile Time Error
5. }} A thread is a lightweight sub-process, the smallest
unit of processing. Multiprocessing and
multithreading, both are used to achieve
Java finally example multitasking.

1. class FinallyExample{ However, we use multithreading than


2. public static void main(String[] args){ multiprocessing because threads use a shared
3. try{
memory area. They don't allocate separate memory
4. int x=300;
area so saves memory, and context-switching
5. }catch(Exception e){System.out.println(e);}
6. finally{System.out.println("finally block is execu between the threads takes less time than process.
ted");}
7. }} 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.

Multitasking
Multitasking is a process of executing multiple tasks There can be multiple processes inside the OS, and
simultaneously. We use multitasking to utilize the one process can have multiple threads.
CPU. Multitasking can be achieved in two ways:
Note: At a time one thread is executed only.
• Process-based Multitasking (Multiprocessing)
• Thread-based Multitasking (Multithreading)
How to create thread
1) Process-based Multitasking (Multiprocessing)
There are two ways to create a thread:
• Each process has an address in memory. In other
words, each process allocates a separate memory 1. By extending Thread class
area. 2. By implementing Runnable interface.
• A process is heavyweight.
• Cost of communication between the process is
high.
• Switching from one process to another requires
Thread class:
some time for saving and loading registers, Thread class provide constructors and methods to create
memory maps, updating lists, etc. and perform operations on a thread.Thread class extends
Object class and implements Runnable interface.
2) Thread-based Multitasking (Multithreading)
Methods of Thread class:
• Threads share the same address space. 1. public void run(): is used to perform action for
• A thread is lightweight. a thread.
• Cost of communication between the thread is 2. public void start(): starts the execution of the
low. thread.JVM calls the run() method on the
thread.
Note: At least one process is required for each 3. public void join(): waits for a thread to die.
thread. 4. public int getPriority(): returns the priority of
the thread.
5. public int setPriority(int priority): changes
What is Thread in java the priority of the thread.
6. public String getName(): returns the name of
A thread is a lightweight subprocess, the smallest the thread.
unit of processing. It is a separate path of execution. 7. public void setName(String name): changes
the name of the thread.
Threads are independent. If there occurs exception 8. public Thread currentThread(): returns the
reference of currently executing thread.
in one thread, it doesn't affect other threads. It uses a
9. public int getId(): returns the id of the thread.
shared memory area.
10. public Thread.State getState(): returns the 2) Java Thread Example by implementing
state of the thread. Runnable interface
11. public void yield(): causes the currently
executing thread object to temporarily pause and 1. class Multi3 implements Runnable{
allow other threads to execute. 2. public void run(){
12. public void suspend(): is used to suspend the 3. System.out.println("thread is running...");
thread(depricated). 4. }
13. public void resume(): is used to resume the 5. public static void main(String args[]){
suspended thread(depricated). 6. Multi3 m1=new Multi3();
14. public void stop(): is used to stop the 7. Thread t1 =new Thread(m1);
thread(depricated). 8. t1.start();
15. public boolean isDaemon(): tests if the thread 9. }
is a daemon thread. 10. }
16. public void setDaemon(boolean b): marks the
thread as daemon or user thread.
17. public void interrupt(): interrupts the thread. Priority of a Thread (Thread
18. public boolean isInterrupted(): tests if the
thread has been interrupted. Priority):
19. public static boolean interrupted(): tests if the
current thread has been interrupted. 3 constants defined in Thread class:
1. public static int MIN_PRIORITY
Runnable interface: 2. public static int NORM_PRIORITY
The Runnable interface should be implemented by 3. public static int MAX_PRIORITY
any class whose instances are intended to be
executed by a thread. Runnable interface have only Default priority of a thread is 5 (NORM_PRIORITY).
one method named run(). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
1. public void run(): is used to perform action for Example of priority of a Thread:
a thread.
1. class TestMultiPriority1 extends Thread{
2. public void run(){
Starting a thread: 3. System.out.println("running thread name is:"+
Thread.currentThread().getName());
start() method of Thread class is used to start a 4. System.out.println("running thread priority is:"
newly created thread. It performs following tasks: +Thread.currentThread().getPriority());
5.
• A new thread starts(with new callstack). 6. }
• The thread moves from New state to the 7. public static void main(String args[]){
Runnable state. 8. TestMultiPriority1 m1=new TestMultiPriority1(
);
• When the thread gets a chance to execute,
9. TestMultiPriority1 m2=new TestMultiPriority1(
its target run() method will run.
);
10. m1.setPriority(Thread.MIN_PRIORITY);
11. m2.setPriority(Thread.MAX_PRIORITY);
1) Java Thread Example by extending Thread 12. m1.start();
class 13. m2.start();

Output:running thread name is:Thread-0


1. class Multi extends Thread{ running thread priority is:10
2. public void run(){ running thread name is:Thread-1
3. System.out.println("thread is running..."); running thread priority is:1
4. }
5. public static void main(String args[]){ Synchronization in Java
6. Multi t1=new Multi();
7. t1.start(); Synchronization in java is the capability to control
8. } the access of multiple threads to any shared
9. } resource.
Java Synchronization is better option where we want 16. this.t=t;
to allow only one thread to access the shared 17. }
resource. 18. public void run(){
19. t.printTable(5);
20. }
21.
Why use Synchronization 22. }
23. class MyThread2 extends Thread{
24. Table t;
The synchronization is mainly used to
25. MyThread2(Table t){
26. this.t=t;
1. To prevent thread interference. 27. }
2. To prevent consistency problem. 28. public void run(){
29. t.printTable(100);
30. }
Types of Synchronization 31. }
32.
There are two types of synchronization 33. class TestSynchronization1{
34. public static void main(String args[]){
1. Process Synchronization 35. Table obj = new Table();//only one object
2. Thread Synchronization 36. MyThread1 t1=new MyThread1(obj);
37. MyThread2 t2=new MyThread2(obj);
38. t1.start();
Here, we will discuss only thread synchronization. 39. t2.start();
40. }
41. }
Thread Synchronization
Output: 5
100
There are two types of thread synchronization 10
mutual exclusive and inter-thread communication. 200
15
300
1. Mutual Exclusive
20
1. Synchronized method. 400
2. Synchronized block. 25
3. static synchronization. 500
2. Cooperation (Inter-thread communication in
java) Java synchronized method
Understanding the problem without If you declare any method as synchronized, it is
Synchronization known as synchronized method.

In this example, there is no synchronization, so Synchronized method is used to lock an object for
output is inconsistent. Let's see the example: any shared resource.
1. class Table{ When a thread invokes a synchronized method, it
2. void printTable(int n){//method not synchronized
automatically acquires the lock for that object and
3. for(int i=1;i<=5;i++){ releases it when the thread completes its task.
4. System.out.println(n*i);
5. try{ 1. //example of java synchronized method
6. Thread.sleep(400); 2. class Table{
7. }catch(Exception e){System.out.println(e);} 3. synchronized void printTable(int n){//synchroni
8. } zed method
9. 4. for(int i=1;i<=5;i++){
10. } 5. System.out.println(n*i);
11. } 6. try{
12. 7. Thread.sleep(400);
13. class MyThread1 extends Thread{ 8. }catch(Exception e){System.out.println(e);}
14. Table t; 9. }
15. MyThread1(Table t){ 10.
11. } • notify()
12. } • notifyAll()
13.
14. class MyThread1 extends Thread{
15. Table t;
1) wait() method
16. MyThread1(Table t){
17. this.t=t;
18. } Causes current thread to release the lock and wait
19. public void run(){ until either another thread invokes the notify()
20. t.printTable(5); method or the notifyAll() method for this object, or a
21. } specified amount of time has elapsed.
22.
23. } The current thread must own this object's monitor,
24. class MyThread2 extends Thread{ so it must be called from the synchronized method
25. Table t; only otherwise it will throw exception.
26. MyThread2(Table t){
27. this.t=t;
28. } Method Description
29. public void run(){
30. t.printTable(100); public final void wait()throws waits until object is
31. } InterruptedException notified.
32. }
33. public final void wait(long waits for the
34. public class TestSynchronization2{ timeout)throws specified amount of
35. public static void main(String args[]){ InterruptedException time.
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start(); 2) notify() method
40. t2.start();
41. } Wakes up a single thread that is waiting on this
42. } object's monitor. If any threads are waiting on this
object, one of them is chosen to be awakened. The
Output: 5 choice is arbitrary and occurs at the discretion of the
10 implementation. Syntax:
15
20
25 public final void notify()
100
200
300
400 3) notifyAll() method
500
Wakes up all threads that are waiting on this object's
monitor. Syntax:
Inter-thread communication in
Java public final void notifyAll()

Inter-thread communication or Co-operation is


all about allowing synchronized threads to Understanding the process of inter-thread
communicate with each other. communication

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()
The point to point explanation of the above diagram 16. System.out.println("going to deposit...");
is as follows: 17. this.amount+=amount;
18. System.out.println("deposit completed... ");
1. Threads enter to acquire lock. 19. notify();
2. Lock is acquired by on thread. 20. }
3. Now thread goes to waiting state if you call 21. }
wait() method on the object. Otherwise it releases 22.
the lock and exits. 23. class Test{
4. If you call notify() or notifyAll() method, thread 24. public static void main(String args[]){
moves to the notified state (runnable state). 25. final Customer c=new Customer();
5. Now thread is available to acquire lock. 26. new Thread(){
6. After completion of the task, thread releases the 27. public void run(){c.withdraw(15000);}
lock and exits the monitor state of the object. 28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
Why wait(), notify() and notifyAll() methods are 32.
defined in Object class not Thread class? 33. }}

It is because they are related to lock and object has a Output: going to withdraw...
lock. Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
Difference between wait and sleep?
wait() sleep()

wait() method releases the sleep() method doesn't


lock release the lock.

is the method of Object is the method of Thread


class class

is the non-static method is the static method

is the non-static method is the static method

should be notified by
after the specified amount
notify() or notifyAll()
of time, sleep is completed.
methods

Example of inter thread communication in java

1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for dep
osit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
UNIT-4
COLLECTIONS

Collections
The Collection in Java is a framework that provides
an architecture to store and manipulate the group of
objects.

All the operations that you perform on a data such as


searching, sorting, insertion, manipulation, deletion,
etc. can be achieved by Java Collections.

Java Collection means a single unit of objects. Java Methods of Collection interface
Collection framework provides many interfaces and Method Description
classes.
public boolean is used to insert an element
What is a framework in Java add(Object element) in this collection.

• It provides readymade architecture. is used to insert the specified


public boolean
• It represents a set of classes and interfaces. collection elements in the
addAll(Collection c)
• It is optional. invoking collection.

public boolean is used to delete an element


What is Collection framework remove(Object element) from this collection.

The Collection framework represents a unified is used to delete all the


architecture for storing and manipulating a group of public boolean elements of specified
objects. It has: removeAll(Collection c) collection from the invoking
collection.
1. Interfaces and its implementations, i.e., classes
2. Algorithm is used to delete all the
public boolean elements of invoking
retainAll(Collection c) collection except the
Hierarchy of Collection specified collection.
Framework
return the total number of
public int size()
elements in the collection.
Let us see the hierarchy of Collection framework.
The java.util package contains all the classes and removes the total no. of
interfaces for Collection framework. public void clear()
elements from the collection.

public boolean
is used to search an element.
contains(Object element)

is used to search the


public boolean
specified collection in this
containsAll(Collection c)
collection.

public Iterator iterator() returns an iterator.

converts collection into


public Object[] toArray()
array.
public boolean isEmpty() checks if collection is empty. It is used to insert the specified
void add(int index,
element at the specified position
public boolean Object element)
matches two collections. index in a list.
equals(Object element)
It is used to append all of the
returns the hash code number boolean elements in the specified collection
public int hashCode()
of the collection. addAll(Collection to the end of this list, in the order
c) that they are returned by the
specified collection's iterator.
Collection Classes
It is used to remove all of the
void clear()
elements from this list.
Java ArrayList class
It is used to return the index in this
int
Java ArrayList class uses a dynamic array for storing list of the last occurrence of the
lastIndexOf(Object
the elements. It inherits AbstractList class and specified element, or -1 if the list
o)
implements List interface. does not contain this element.

The important points about Java ArrayList class are: It is used to return an array
Object[] toArray() containing all of the elements in this
• Java ArrayList class can contain duplicate list in the correct order.
elements.
• Java ArrayList class maintains insertion order. Object[] It is used to return an array
• Java ArrayList class is non synchronized. toArray(Object[] containing all of the elements in this
• Java ArrayList allows random access because a) list in the correct order.
array works at the index basis.
• In Java ArrayList class, manipulation is slow boolean It is used to append the specified
because a lot of shifting needs to be occurred if add(Object o) element to the end of a list.
any element is removed from the array list.
It is used to insert all of the
boolean addAll(int
Hierarchy of ArrayList class elements in the specified collection
index, Collection
into this list, starting at the specified
c)
position.

It is used to return a shallow copy of


Object clone()
an ArrayList.

It is used to return the index in this


int indexOf(Object list of the first occurrence of the
o) specified element, or -1 if the List
does not contain this element.

It is used to trim the capacity of this


void trimToSize() ArrayList instance to be the list's
current size.

Java ArrayList Example

1. import java.util.*;
2. class TestCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>(
);//Creating arraylist
Methods of Java ArrayList 5. list.add("Ravi");//Adding object in arraylist
Method Description 6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. } Methods of Java LinkedList
15. } Method Description

Java LinkedList class void add(int index,


It is used to insert the specified
element at the specified position
Object element)
index in a list.

void It is used to insert the given element


addFirst(Object o) at the beginning of a list.

void It is used to append the given


addLast(Object o) element to the end of a list.

It is used to return the number of


int size()
elements in a list

boolean It is used to append the specified


add(Object o) element to the end of a list.

boolean It is used to return true if the list


contains(Object o) contains a specified element.

It is used to remove the first


boolean
occurence of the specified element
remove(Object o)
in a list.

It is used to return the first element


Object getFirst()
in a list.
Java LinkedList class uses doubly linked list to store
the elements. It provides a linked-list data structure. It is used to return the last element
Object getLast()
It inherits the AbstractList class and implements List in a list.
and Deque interfaces.
It is used to return the index in a list
The important points about Java LinkedList are: int indexOf(Object of the first occurrence of the
o) specified element, or -1 if the list
• Java LinkedList class can contain duplicate does not contain any element.
elements.
• Java LinkedList class maintains insertion order. It is used to return the index in a list
int
• Java LinkedList class is non synchronized. of the last occurrence of the
lastIndexOf(Object
• In Java LinkedList class, manipulation is fast o)
specified element, or -1 if the list
because no shifting needs to be occurred. does not contain any element.
• Java LinkedList class can be used as list, stack or
queue.
Java LinkedList Example
Hierarchy of LinkedList class
1. import java.util.*;
As shown in above diagram, Java LinkedList class 2. public class TestCollection7{
extends AbstractSequentialList class and 3. public static void main(String args[]){
implements List and Deque interfaces. 4.
5. LinkedList<String> al=new LinkedList<String>
();
Doubly Linked List 6. al.add("Ravi");
7. al.add("Vijay");
In case of doubly linked list, we can add or remove 8. al.add("Ravi");
elements from both side. 9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Difference between ArrayList


and LinkedList
ArrayList LinkedList

1) ArrayList internally LinkedList internally uses


uses dynamic array to doubly linked list to
store the elements. store the elements.

2) Manipulation with Manipulation with


ArrayList is slow because LinkedList is faster than
it internally uses array. If ArrayList because it uses
any element is removed doubly linked list so no
from the array, all the bits bit shifting is required in
are shifted in memory. memory. Methods of Java HashSet class
LinkedList class can act
3) ArrayList class can act Type Method Description
as a list and queue both
as a list only because it
because it implements
implements List only. It is used to adds the
List and Deque interfaces.
specified element to this
boolean add(Object o)
set if it is not already
4) ArrayList is better for
LinkedList is better for present.
storing and accessing
manipulating data.
data.
It is used to remove all of
void clear()
the elements from this set.

Java HashSet class It is used to return a


shallow copy of this
object clone() HashSet instance: the
Java HashSet class is used to create a collection that elements themselves are
uses a hash table for storage. It inherits the not cloned.
AbstractSet class and implements Set interface.
It is used to return true if
contains(Object
The important points about Java HashSet class are: boolean this set contains the
o)
specified element.
• HashSet stores the elements by using a
mechanism called hashing. It is used to return true if
• HashSet contains unique elements only. boolean isEmpty() this set contains no
elements.
Difference between List and Set It is used to return an
Iterator<E
iterator() iterator over the elements
List can contain duplicate elements whereas Set >
in this set.
contains unique elements only.
It is used to remove the
Hierarchy of HashSet class boolean remove(Object o) specified element from
this set if it is present.
The HashSet class extends AbstractSet class which
implements Set interface. The Set interface inherits
Collection and Iterable interfaces in hierarchical
order.
It is used to return the Hierarchy of TreeSet class
int size() number of elements in
this set.

It is used to create a late-


Spliterato binding and fail-fast
spliterator()
r<E> Spliterator over the
elements in this set.

Java HashSet Example

1. import java.util.*;
2. class TestCollection9{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. } Methods of Java TreeSet class
Method Description
Java TreeSet class
It is used to add all of the
boolean
• Contains unique elements only like HashSet. elements in the specified
addAll(Collection c)
• Access and retrieval times are quiet fast. collection to this set.
• Maintains ascending order.
boolean It is used to return true if this set
contains(Object o) contains the specified element.

It is used to return true if this set


boolean isEmpty()
contains no elements.

It is used to remove the specified


boolean
element from this set if it is
remove(Object o)
present.

It is used to add the specified


void add(Object o) element to this set if it is not
already present.

It is used to remove all of the


void clear()
elements from this set.

It is used to return a shallow copy


Object clone()
of this TreeSet instance.

It is used to return the first


Object first() (lowest) element currently in this
sorted set.
It is used to return the last PriorityQueue class
Object last() (highest) element currently in this
sorted set.
The PriorityQueue class provides the facility of
It is used to return the number of using queue. But it does not orders the elements in
int size() FIFO manner. It inherits AbstractQueue class.
elements in this set.

Java TreeSet Example Java PriorityQueue Example

1. import java.util.*; 1. import java.util.*;


2. class TestCollection11{ 2. class TestCollection12{
3. public static void main(String args[]){ 3. public static void main(String args[]){
4. //Creating and adding elements 4. PriorityQueue<String> queue=new PriorityQueu
5. TreeSet<String> al=new TreeSet<String>(); e<String>();
6. al.add("Ravi"); 5. queue.add("Amit");
7. al.add("Vijay"); 6. queue.add("Vijay");
8. al.add("Ravi"); 7. queue.add("Karan");
9. al.add("Ajay"); 8. queue.add("Jai");
10. //Traversing elements 9. queue.add("Rahul");
11. Iterator<String> itr=al.iterator(); 10. System.out.println("head:"+queue.element());
12. while(itr.hasNext()){ 11. System.out.println("head:"+queue.peek());
13. System.out.println(itr.next()); 12. System.out.println("iterating the queue elements:
14. } ");
15. } 13. Iterator itr=queue.iterator();
16. } 14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
Java Queue Interface 17. queue.remove();
18. queue.poll();
Java Queue interface orders the element in 19. System.out.println("after removing two elements:
");
FIFO(First In First Out) manner. In FIFO, first
20. Iterator<String> itr2=queue.iterator();
element is removed first and last element is removed 21. while(itr2.hasNext()){
at last. 22. System.out.println(itr2.next());
23. }
Methods of Java Queue Interface 24. }
Method Description 25. }

It is used to insert the specified element


boolean
into this queue and return true upon
Java Deque Interface
add(object)
success.
Java Deque Interface is a linear collection that
boolean It is used to insert the specified element supports element insertion and removal at both ends.
offer(object) into this queue. Deque is an acronym for "double ended queue".

Object It is used to retrieves and removes the Methods of Java Deque Interface
remove() head of this queue. Method Description

It is used to retrieves and removes the It is used to insert the specified element
Object poll() head of this queue, or returns null if this boolean
into this deque and return true upon
queue is empty. add(object)
success.

Object It is used to retrieves, but does not boolean It is used to insert the specified element
element() remove, the head of this queue. offer(object) into this deque.

It is used to retrieves, but does not Object It is used to retrieves and removes the
Object peek() remove, the head of this queue, or remove() head of this deque.
returns null if this queue is empty.
It is used to retrieves and removes the Java ArrayDeque Example
Object poll() head of this deque, or returns null if this
deque is empty. 1. import java.util.*;
2. public class ArrayDequeExample {
Object It is used to retrieves, but does not 3. public static void main(String[] args) {
element() remove, the head of this deque. 4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<Stri
It is used to retrieves, but does not ng>();
Object peek() remove, the head of this deque, or 6. deque.add("Ravi");
7. deque.add("Vijay");
returns null if this deque is empty.
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
ArrayDeque class 14. }

• Unlike Queue, we can add or remove elements


from both sides. Iterator interface
• Null elements are not allowed in the Iterator interface provides the facility of iterating the
ArrayDeque. elements in a forward direction only.
• ArrayDeque is not thread safe, in the absence of
external synchronization.
• ArrayDeque has no capacity restrictions. Methods of Iterator interface
• ArrayDeque is faster than LinkedList and Stack.
Method Description
ArrayDeque Hierarchy
public boolean It returns true if the iterator has more
The hierarchy of ArrayDeque class is given in the hasNext() elements otherwise it returns false.
figure displayed at the right side of the page.
public Object It returns the element and moves the
next() cursor pointer to the next element.

public void It removes the last elements returned


remove() by the iterator. It is less used.

Java ListIterator Interface


ListIterator Interface is used to traverse the element
in backward and forward direction.

Methods of Java ListIterator Interface:


Method Description

This method return true if the list


boolean iterator has more elements when
hasNext() traversing the list in the forward
direction.

This method return the next element in


Object next() the list and advances the cursor
position.

boolean This method return true if this list


hasPrevious() iterator has more elements when
traversing the list in the reverse Advantage of for-each loop:
direction.
• It makes the code more readable.
This method return the previous
Object • It elimnates the possibility of programming
element in the list and moves the cursor errors.
previous()
position backwards.
Simple Example of for-each loop for traversing
Example of ListIterator Interface
the array elements:
1. import java.util.*;
1.
2. public class TestCollection8{
2. class ForEachExample1{
3. public static void main(String args[]){
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
4. int arr[]={12,13,14,44};
5. al.add("Amit");
5.
6. al.add("Vijay");
6. for(int i:arr){
7. al.add("Kumar");
7. System.out.println(i);
8. al.add(1,"Sachin");
8. }
9. System.out.println("element at 2nd position: "+al
9.
.get(2));
10. }
10. ListIterator<String> itr=al.listIterator();
11. }
11. System.out.println("traversing elements in forwar
d direction...");
12. while(itr.hasNext()){ Simple Example of for-each loop for traversing
13. System.out.println(itr.next()); the collection elements:
14. }
15. System.out.println("traversing elements in backw 1. import java.util.*;
ard direction..."); 2. class ForEachExample2{
16. while(itr.hasPrevious()){ 3. public static void main(String args[]){
17. System.out.println(itr.previous()); 4. ArrayList<String> list=new ArrayList<String>
18. } ();
19. } 5. list.add("vimal");
20. } 6. list.add("sonoo");
7. list.add("ratan");
Differences between Iterator and ListIterator: 8.
9. for(String s:list){
1. With iterator you can move only forward, but 10. System.out.println(s);
with ListIterator you can move backword also 11. }
12.
while reading the elements.
13. }
2. With ListIterator you can obtain the index at 14. }
any point while traversing, which is not
possible with iterators.
3. With iterator you can check only for next Java Map Interface
element available or not, but in listiterator you
can check previous and next elements. A map contains values on the basis of key i.e. key
4. With listiterator you can add new element at and value pair. Each key and value pair is known as
any point of time, while traversing. Not an entry. Map contains only unique keys.
possible with iterator.
5. With listiterator you can modify an element Map is useful if you have to search, update or delete
while traversing, which is not possible with elements on the basis of key.
iterator.

Java Map Hierarchy


For-each loop (Advanced or
Enhanced For loop):
The for-each loop introduced in Java5. It is mainly
used to traverse array or collection elements.
It is used to return the Set view
Set keySet()
containing all the keys.

It is used to return the Set view


Set entrySet()
containing all the keys and values.

Map.Entry Interface
Entry is the sub interface of Map. So we will be
accessed it by Map.Entry name. It provides methods
to get key and value.

Methods of Map.Entry interface


Method Description

Object getKey() It is used to obtain key.

Map doesn't allow duplicate keys, but you can have Object getValue() It is used to obtain value.
duplicate values. HashMap and LinkedHashMap
allows null keys and values but TreeMap doesn't Java Map Example: Generic (New Style)
allow any null key or value.
1. import java.util.*;
Map can't be traversed so you need to convert it into 2. class MapInterfaceExample{
Set using keySet() or entrySet() method. 3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Inte
ger,String>();
Class Description
5. map.put(100,"Amit");
6. map.put(101,"Vijay");
HashMap is the implementation of
HashMap 7. map.put(102,"Rahul");
Map but it doesn't maintain any order.
8. for(Map.Entry m:map.entrySet()){
9. System.out.println(m.getKey()+" "+m.getValue
LinkedHashMap is the implementation
());
LinkedHashMap of Map, it inherits HashMap class. It 10. }
maintains insertion order. 11. }
12. }
TreeMap is the implementation of
TreeMap Map and SortedMap, it maintains Java Map Example: Non-Generic (Old Style)
ascending order.
1. //Non-generic
Useful methods of Map interface 2. import java.util.*;
Method Description 3. public class MapExample1 {
4. public static void main(String[] args) {
Object put(Object It is used to insert an entry in this 5. Map map=new HashMap();
key, Object value) map. 6. //Adding elements to map
7. map.put(1,"Amit");
void putAll(Map It is used to insert the specified 8. map.put(5,"Rahul");
map) map in this map. 9. map.put(2,"Jai");
10. map.put(6,"Amit");
Object It is used to delete an entry for the 11. //Traversing Map
remove(Object key) specified key. 12. Set set=map.entrySet();//Converting to Set so t
hat we can traverse
Object get(Object It is used to return the value for 13. Iterator itr=set.iterator();
key) the specified key. 14. while(itr.hasNext()){
15. //Converting to Map.Entry so that we can ge
boolean t key and value separately
It is used to search the specified 16. Map.Entry entry=(Map.Entry)itr.next();
containsKey(Object
key from this map. 17. System.out.println(entry.getKey()+" "+entry
key)
.getValue());
18. } It is used to associate the
19. } Object put(Object
specified value with the
20. } key, Object value)
specified key in this map.

Java HashMap class It is used to return the number


int size() of key-value mappings in this
map.
• A HashMap contains values based on the key.
• It contains only unique elements.
It is used to return a collection
• It may have one null key and multiple null
values. Collection values() view of the values contained in
• It maintains no order. this map.

Hierarchy of HashMap class Java HashMap Example

1. import java.util.*;
2. class TestCollection13{
3. public static void main(String args[]){
4. HashMap<Integer,String> hm=new HashMap<I
nteger,String>();
5. hm.put(100,"Amit");
6. hm.put(101,"Vijay");
7. hm.put(102,"Rahul");
8. for(Map.Entry m:hm.entrySet()){
9. System.out.println(m.getKey()+" "+m.getValue
());
10. }
Methods of Java HashMap class 11. }
Method Description 12. }

It is used to remove all of the


void clear()
mappings from this map. Java LinkedHashMap class
boolean It is used to return true if this
containsKey(Object map contains a mapping for the • A LinkedHashMap contains values based on the
key) specified key. key.
• It contains only unique elements.
boolean It is used to return true if this • It may have one null key and multiple null
containsValue(Object map maps one or more keys to values.
value) the specified value. • It is same as HashMap instead maintains

It is used to return true if this


boolean isEmpty() map contains no key-value
mappings.

It is used to return a shallow


copy of this HashMap instance:
Object clone()
the keys and values themselves
are not cloned.

It is used to return a collection


Set entrySet() view of the mappings contained
in this map.

It is used to return a set view of


Set keySet()
the keys contained in this map. insertion order.

Methods of Java LinkedHashMap class


Method Description
It is used to return the value to Methods of Java TreeMap class
Object get(Object
which this map maps the Method Description
key)
specified key.
boolean It is used to return true if this map
It is used to remove all mappings containsKey contains a mapping for the specified
void clear()
from this map. (Object key) key.

boolean It is used to return true if this map boolean It is used to return true if this map
containsKey(Object maps one or more keys to the containsValue maps one or more keys to the
key) specified value. (Object value) specified value.

Java LinkedHashMap Example It is used to return the first (lowest)


Object firstKey()
key currently in this sorted map.
1. import java.util.*;
2. class TestCollection14{ Object get(Object It is used to return the value to which
3. public static void main(String args[]){ key) this map maps the specified key.
4.
5. LinkedHashMap<Integer,String> hm=new Link It is used to return the last (highest)
edHashMap<Integer,String>(); Object lastKey()
key currently in this sorted map.
6.
7. hm.put(100,"Amit"); Object It is used to remove the mapping for
8. hm.put(101,"Vijay"); remove(Object this key from this TreeMap if
9. hm.put(102,"Rahul"); key) present.
10.
11. for(Map.Entry m:hm.entrySet()){ void putAll(Map It is used to copy all of the mappings
12. System.out.println(m.getKey()+" "+m.getValue map) from the specified map to this map.
());
13. } It is used to return a set view of the
14. } Set entrySet()
mappings contained in this map.
15. }
It is used to return the number of
int size()
Java TreeMap class key-value mappings in this map.

• A TreeMap contains values based on the key. It Collection It is used to return a collection view
implements the NavigableMap interface and values() of the values contained in this map.
extends AbstractMap class.
• It contains only unique elements. Java TreeMap Example:
• It cannot have null key but can have multiple null
values. 1. import java.util.*;
• It is same as HashMap instead maintains 2. class TestCollection15{
ascending order. 3. public static void main(String args[]){
4. TreeMap<Integer,String> hm=new TreeMap<In
teger,String>();
5. hm.put(100,"Amit");
6. hm.put(102,"Ravi");
7. hm.put(101,"Vijay");
8. hm.put(103,"Rahul");
9. for(Map.Entry m:hm.entrySet()){
10. System.out.println(m.getKey()+" "+m.getValue
());
11. }
12. }
13. }
1. import java.util.*;
Java Comparable interface 2. class AgeComparator implements Comparator<S
tudent>{
This interface is found in java.lang package and 3. public int compare(Student s1,Student s2){
contains only one method named 4. if(s1.age==s2.age)
compareTo(Object). 5. return 0;
6. else if(s1.age>s2.age)
public int compareTo(Object obj): is used to 7. return 1;
8. else
compare the current object with the specified object.
9. return -1;
10. }
Java Comparable Example 11. }

1. class Student implements Comparable<Student> NameComparator.java


{
2. int rollno; This class provides comparison logic based on the
3. String name; name. In such case, we are using the compareTo()
4. int age; method of String class, which internally provides the
5. Student(int rollno,String name,int age){ comparison logic.
6. this.rollno=rollno;
7. this.name=name;
1. import java.util.*;
8. this.age=age;
2. class NameComparator implements Comparator<
9. }
Student>{
10.
3. public int compare(Student s1,Student s2){
11. public int compareTo(Student st){
4. return s1.name.compareTo(s2.name);
12. if(age==st.age)
5. }
13. return 0;
6. }
14. else if(age>st.age)
15. return 1;
16. else Simple.java
17. return -1;
18. } In this class, we are printing the objects values by
19. } sorting on the basis of name and age.

1. import java.util.*;
Java Comparator interface 2. import java.io.*;
3. class Simple{
Java Comparator interface is used to order the 4. public static void main(String args[]){
objects of user-defined class. 5.
6. ArrayList<Student> al=new ArrayList<Student>
This interface is found in java.util package and ();
contains 2 methods compare(Object obj1,Object 7. al.add(new Student(101,"Vijay",23));
8. al.add(new Student(106,"Ajay",27));
obj2) and equals(Object element).
9. al.add(new Student(105,"Jai",21));
10.
Java Comparator Example 11. System.out.println("Sorting by Name...");
12.
Student.java 13. Collections.sort(al,new NameComparator());
14. for(Student st: al){
15. System.out.println(st.rollno+" "+st.name+" "+st.a
1. class Student{
ge);
2. int rollno;
16. }
3. String name;
17.
4. int age;
18. System.out.println("sorting by age...");
5. Student(int rollno,String name,int age){
19.
6. this.rollno=rollno;
20. Collections.sort(al,new AgeComparator());
7. this.name=name;
21. for(Student st: al){
8. this.age=age;
22. System.out.println(st.rollno+" "+st.name+" "+st.a
9. }
ge);
10. }
23. }
24.
AgeComparator.java
25. } Returns the maximum element in c as determined
26. } by natural ordering. The collection need not be
sorted.
Output:Sorting by Name...
106 Ajay 27 static Object min(Collection c)
105 Jai 21
101 Vijay 23 Returns the minimum element in c as determined
by natural ordering.
Sorting by age...
105 Jai 21 static void reverse(List list)
101 Vijay 23
106 Ajay 27
Reverses the sequence in list.
static Comparator reverseOrder( )
Difference between Comparable
and Comparator Returns a reverse comparator.
Comparable Comparator static void rotate(List list, int n)

The Comparator provides Rotates list by n places to the right. To rotate left,
1) Comparable provides a
multiple sorting use a negative value for n.
single sorting sequence. In
sequences. In other words, static void shuffle(List list)
other words, we can sort
we can sort the collection
the collection on the basis
on the basis of multiple Shuffles (i.e., randomizes) the elements in list.
of a single element such as
elements such as id, name,
id or name or price, etc. static Set singleton(Object obj)
and price, etc.

2) Comparable affects the Comparator doesn't affect Returns obj as an immutable set. This is an easy
original class, i.e., the the original class, i.e., way to convert a single object into a set.
actual class is modified. actual class is not modified. static void sort(List list)

3) Comparable provides Comparator provides Sorts the elements of the list as determined by their
compareTo() method to compare() method to sort natural ordering.
sort elements. elements.
static void swap(List list, int idx1, int idx2)
4) Comparable is found in A Comparator is found in
java.lang package. the java.util package. Exchanges the elements in the list at the indices
specified by idx1 and idx2.
5) We can sort the list We can sort the list static Collection
elements of Comparable elements of Comparator synchronizedCollection(Collection c)
type by type by
Collections.sort(List) Collections.sort(List, Returns a thread-safe collection backed by c.
method. Comparator) method.
static List synchronizedList(List list)

Returns a thread-safe list backed by list.


Collections Algorithms
static Map synchronizedMap(Map m)
Method & Description
static void copy(List list1, List list2) Returns a thread-safe map backed by m.
static Set synchronizedSet(Set s)
Copies the elements of list2 to list1.
static Enumeration enumeration(Collection c) Returns a thread-safe set backed by s.

Returns an enumeration over c.


Java.util.Dictionary Class
static void fill(List list, Object obj)
• In this class every key and every value is an
Assigns obj to each element of the list. object.
static Object max(Collection c) • In his class object every key is associated
with at most one value.
Dictionary Class methods boolean
This method return true if some
value equal to the value exists
containsValue
within the hash table, else return
Method & Description (Object value)
false.
abstract Enumeration<V> elements()
boolean This method return true if some
containsKey(Object key equal to the key exists within
This method returns an enumeration of the values in key) the hash table, else return false.
this dictionary.
abstract V get(Object key) This method return true if the
boolean isEmpty() hash table is empty; returns false
This method returns the value to which the key is if it contains at least one key.
mapped in this dictionary.
This method return the object that
abstract boolean isEmpty() Object get(Object
contains the value associated with
key)
the key.
This method tests if this dictionary maps no keys to
value. Object It is used to remove the key and
abstract Enumeration<K> keys() remove(Object its value. This method return the
key) value associated with the key.
This method returns an enumeration of the keys in
this dictionary. This method return the number of
int size()
entries in the hash table.
abstract V put(K key, V value)
Java Hashtable Example
This method maps the specified key to the specified
value in this dictionary.
1. import java.util.*;
abstract V remove(Object key) 2. class TestCollection16{
3. public static void main(String args[]){
This method removes the key (and its 4. Hashtable<Integer,String> hm=new Hashtable<
corresponding value) from this dictionary. Integer,String>();
5.
abstract int size()
6. hm.put(100,"Amit");
7. hm.put(102,"Ravi");
This method returns the number of entries (distinct 8. hm.put(101,"Vijay");
keys) in this dictionary. 9. hm.put(103,"Rahul");
10.
11. for(Map.Entry m:hm.entrySet()){
Java Hashtable class 12. System.out.println(m.getKey()+" "+m.getValue
());
• A Hashtable is an array of list. Each list is known 13. }
as a bucket. The position of bucket is identified 14. }
by calling the hashcode() method. A Hashtable 15. }
contains values based on the key.
• It contains only unique elements.
• It may have not have any null key or value. Properties class in Java
• It is synchronized.
The properties object contains key and value pair
Methods of Java Hashtable class both as a string. The java.util.Properties class is the
Method Description subclass of Hashtable.

void clear() It is used to reset the hash table. It can be used to get property value based on the
property key. The Properties class provides methods
This method return true if some to get data from properties file and store data into
boolean
value equal to the value exist properties file. Moreover, it can be used to get
contains(Object
within the hash table, else return properties of system.
value)
false.
Advantage of properties file Now, lets create the java class to read the data from
the properties file.
Recompilation is not required, if information is
changed from properties file: If any information is Test.java
changed from the properties file, you don't need to
recompile the java class. It is used to store 1. import java.util.*;
information which is to be changed frequently. 2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exce
Methods of Properties class
ption{
5. FileReader reader=new FileReader("db.propert
The commonly used methods of Properties class are ies");
given below. 6.
7. Properties p=new Properties();
Method Description 8. p.load(reader);
9.
public void load(Reader loads data from the Reader 10. System.out.println(p.getProperty("user"));
r) object. 11. System.out.println(p.getProperty("password"))
;
public void loads data from the 12. }
load(InputStream is) InputStream object 13. }

public String returns value based on the Output:system


oracle
getProperty(String key) key.

public void Now if you change the value of the properties file,
sets the property in the you don't need to compile the java class again. That
setProperty(String
properties object. means no maintenance problem.
key,String value)

public void store(Writer writers the properties in the Stack


w, String comment) writer object.

public void
The stack is the subclass of Vector. It implements
writes the properties in the the last-in-first-out data structure, i.e., Stack. The
store(OutputStream os,
OutputStream object. stack contains all of the methods of Vector class and
String comment)
also provides its own methods like boolean push(),
writers the properties in the boolean peek(), boolean push(object o), which
storeToXML(OutputStrea defines its properties.
writer object for generating
m os, String comment)
xml document.
Stack Example:
public void writers the properties in the
storeToXML(Writer w, writer object for generating 1. import java.util.*;
String comment, String xml document with 2. public class TestJavaCollection4{
encoding) specified encoding. 3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
Example of Properties class to get information 7. stack.push("Amit");
from properties file 8. stack.push("Ashish");
9. stack.push("Garima");
To get information from the properties file, create 10. stack.pop();
11. Iterator<String> itr=stack.iterator();
the properties file first. 12. while(itr.hasNext()){
13. System.out.println(itr.next());
db.properties 14. }
15. }
1. user=system 16. }
2. password=oracle

Vector
Vector uses a dynamic array to store the data Java BitSet Class
elements. It is similar to ArrayList. However, It is
synchronized and contains many methods that are
not the part of Collection framework. Each component of bit set contains at least one
Boolean value. The contents of one BitSet may be
Vector example changed by other BitSet using logical AND, logical
OR and logical exclusive OR operations. The index
1. import java.util.*; of bits of BitSet class is represented by positive
2. public class TestJavaCollection3{ integers.
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>(); Each element of bits contains either true or false
5. v.add("Ayush"); value. Initially, all bits of a set have the false value.
6. v.add("Amit"); A BitSet is not safe for multithreaded use without
7. v.add("Ashish"); using external synchronization.
8. v.add("Garima");
9. Iterator<String> itr=v.iterator();
10. while(itr.hasNext()){ Java BitSet Methods
11. System.out.println(itr.next());
12. } Type Method Description
13. }
14. } This method is used to perform a
and(BitSet logical AND operation of this
void
More Utility Classes set) target bit set with the specified
argument.

StringTokenizer in Java This method is used to clear the


andNot entire bit in this BitSet whose
Public method Description void
(BitSet set) corresponding bit is set in the
boolean checks if there is more tokens specified BitSet.
hasMoreTokens() available.
returns the next token from the This method set false to all bits in
String nextToken() void clear()
StringTokenizer object. this BitSet.
String This method makes the clone of
returns the next token based on
nextToken(String Object clone() this BitSet to new BitSet which is
the delimeter.
delim) equal to it.
boolean same as hasMoreTokens()
hasMoreElements() method. equals This method is used to compare the
boolea
Object same as nextToken() but its (Object current object with the specified
n
nextElement() return type is Object. obj) object.

returns the total number of boolea get(int This method returns the bit value of
int countTokens()
tokens. n bitIndex) the specified index.
Example of StringTokenizer class
This method returns true if the
boolea
1. import java.util.StringTokenizer; isEmpty() current BitSet does not contain any
n
2. public class Simple{ bit which is set to true.
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my This method returns the "logical
int length()
name is khan"," "); size" of this BitSet.
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken()); This method is used to perform a
or(BitSet
7. } void logical OR operation of this target
set)
8. } bit set with the specified argument.
9. }
set(int This method sets true to bit value at
void
bitIndex) the specified index.
This method returns the number of java.util.Date Methods
int size() bit space actually in use by this
BitSet to represent bit values.
Method Description
This method is used to perform a
tests if current date is after the
xor(BitSet logical XOR operation of this bit boolean after(Date date)
void given date.
set) set with the specified bit set
argument.
boolean before(Date tests if current date is before
date) the given date.

returns the clone object of


Object clone()
current date.
BitSet AND Example
int compareTo(Date compares current date with
1. import java.util.BitSet; date) given date.
2. public class BitSetAndExample1 {
3. public static void main(String[] args) { boolean equals(Date compares current date with
4. // create 2 bitsets date) given date for equality.
5. BitSet bitset1 = new BitSet();
6. BitSet bitset2 = new BitSet(); static Date from(Instant returns an instance of Date
7. instant) object from Instant date.
8. // assign values to bitset1
9. bitset1.set(0); returns the time represented by
10. bitset1.set(1); long getTime()
this date object.
11. bitset1.set(2);
12. bitset1.set(3); returns the hash code value for
13. bitset1.set(4); int hashCode()
this date object.
14.
15. // assign values to bitset2 changes the current date and
16. bitset2.set(2); void setTime(long time)
time to given time.
17. bitset2.set(4);
18. bitset2.set(6); converts current date into
19. bitset2.set(8); Instant toInstant()
Instant object.
20. bitset2.set(10);
21.
converts this date into Instant
22. // print the sets String toString()
23. System.out.println("bitset1: " + bitset1); object.
24. System.out.println("bitset2: " + bitset2);
25.
26. // perform and operation between two bitse java.util.Date Example
ts
27. bitset1.and(bitset2); 1st way:
28. // print the new bitset1
29. System.out.println("result bitset: " + bitset
1. java.util.Date date=new java.util.Date();
1);
2. System.out.println(date);
30. }
31. }
Output:
Output:
Wed Mar 27 08:22:02 IST 2015
bitset1: {0, 1, 2, 3, 4}
bitset2: {2, 4, 6, 8, 10} 2nd way:
result bitset: {2, 4}
1. long millis=System.currentTimeMillis();
2. java.util.Date date=new java.util.Date(millis);
java.util.Date 3. System.out.println(date);

The java.util.Date class represents date and time in Output:


java. It provides constructors and methods to deal
with date and time in java. Wed Mar 27 08:22:02 IST 2015
Java Calendar Class public TimeZone
This method gets the TimeZone
of calendar object and Returns a
getTimeZone()
TimeZone object.
Java Calendar class is an abstract class that provides
methods for converting date between a specific
instant in time and a set of calendar fields such as
MONTH, YEAR, HOUR, etc. Calendar Class Example
1. import java.util.Calendar;
Method Description
2. public class CalendarExample1 {
3. public static void main(String[] args) {
Adds the specified (signed)
public void add(int 4. Calendar calendar = Calendar.getInstance();
amount of time to the given 5. System.out.println("The current date is : " + cal
field, int amount)
calendar field. endar.getTime());
6. calendar.add(Calendar.DATE, -15);
The method Returns true if the 7. System.out.println("15 days ago: " + calendar.g
public boolean after time represented by this etTime());
(Object when) Calendar is after the time 8. calendar.add(Calendar.MONTH, 4);
represented by when Object. 9. System.out.println("4 months later: " + calenda
r.getTime());
The method Returns true if the 10. calendar.add(Calendar.YEAR, 2);
public boolean time represented by this 11. System.out.println("2 years later: " + calendar.g
before(Object when) Calendar is before the time etTime());
represented by when Object. 12. }
13. }
Set the given calendar field
public final void
value and the time value of this Output:
clear(int field)
Calendar undefined.
The current date is : Thu Jan 19 18:47:02 IST 2017
The equals() method compares 15 days ago: Wed Jan 04 18:47:02 IST 2017
public boolean 4 months later: Thu May 04 18:47:02 IST 2017
two objects for equality and
equals(Object object) 2 years later: Sat May 04 18:47:02 IST 2019
Returns true if they are equal.
Java String Format Specifiers
In get() method fields of the
Format
calendar are passed as the Data Type Output
public int get(int Specifier
parameter, and this method
field)
Returns the value of fields %c character Unicode character
passed as the parameter.
%f floating point decimal number
public int
Returns the first day of the week
getFirstDayOfWeek( integer (incl. byte, short,
in integer form. %o Octal number
) int, long, bigint)

This method is used with %s any type String value


public static calendar object to get the
Calendar instance of calendar according integer (incl. byte, short,
%d Decimal Integer
getInstance() to current time zone set by java int, long, bigint)
runtime environment

This method gets the time value


public final Date
of calendar object and Returns
String format() Example
getTime()
date.
1. public class FormatExample2 {
2. public static void main(String[] args) {
Returns the current time in
public long 3. String str1 = String.format("%d", 101);
millisecond. This method has // Integer value
getTimeInMillis()
long as return type. 4. String str2 = String.format("%s", "Amar Sin
gh"); // String value
5. String str3 = String.format("%f", 101.00);
// Float value
6. String str4 = String.format("%x", 101);
// Hexadecimal value
7. String str5 = String.format("%c", 'c'); /
/ Char value
8. System.out.println(str1);
9. System.out.println(str2);
10. System.out.println(str3);
11. System.out.println(str4);
12. System.out.println(str5);
13. }
14.
15. }

Output:
101
Amar Singh
101.000000
65
c
Window
UNIT-5
GUI PROGRAMMING The window is the container that have no borders
and menu bars. You must use frame, dialog or
WITH SWING & EVENT another window for creating a window.
HANDLING
Java AWT Tutorial Panel

Java AWT (Abstract Window Toolkit) is an API to The Panel is the container that doesn't contain title
develop GUI or window-based applications in java. bar and menu bars. It can have other components
like button, textfield etc.
Java AWT components are platform-dependent i.e.
components are displayed according to the view of
operating system. AWT is heavyweight i.e. its Frame
components are using the resources of OS.
The Frame is the container that contain title bar and
The java.awt package provides classes for AWT api can have menu bars. It can have other components
such as TextField, Label, TextArea, RadioButton, like button, textfield etc.
CheckBox, Choice, List etc.

Useful Methods of Component class


Java AWT Hierarchy Method Description

public void inserts a component on this


add(Component c) component.

public void setSize(int sets the size (width and


width,int height) height) of the component.

public void setLayout defines the layout manager


(LayoutManager m) for the component.

public void
changes the visibility of the
setVisible(boolean
component, by default false.
status)

Java AWT Example

To create simple awt example, you need a frame.


There are two ways to create a frame in AWT.

• By extending Frame class (inheritance)


• By creating the object of Frame class
(association)

Container

The Container is a component in AWT that can AWT Example by Inheritance


contain another components like buttons, textfields,
labels etc. The classes that extends Container class Let's see a simple example of AWT where we are
are known as container such as Frame, Dialog and inheriting Frame class. Here, we are showing Button
Panel. component on the Frame.

1. import java.awt.*;
2. class First extends Frame{ Third, the use of heavyweight components caused
3. First(){ some frustrating restrictions.
4. Button b=new Button("click me");
5. b.setBounds(30,100,80,30);// setting button positi Due to these limitations Swing came and was
on
integrated to java.
6. add(b);//adding button into frame
7. setSize(300,300);//frame size 300 width and 300
height Swing is built on the AWT.
8. setLayout(null);//no layout manager Two key Swing features are:
9. setVisible(true);//now frame will be visible, by d Swing components are light weight,
efault not visible Swing supports a pluggable look and feel.
10. }
11. public static void main(String args[]){
12. First f=new First();
The MVC Connection:
13. }} In general, a visual component is a composite of
three distinct aspects:
1. The way that the component looks when
AWT Example by Association rendered on the screen
2. The way that the component reacts to the
1. import java.awt.*; user
2. class First2{
3. The state information associated with the
3. First2(){
component.
4. Frame f=new Frame();
5. Button b=new Button("click me"); The Model-View-Controller architecture is
6. b.setBounds(30,50,80,30); successful for all these.
7. f.add(b);
8. f.setSize(300,300); Components and Containers:
9. f.setLayout(null); A component is an independent visual control, such
10. f.setVisible(true); as a push button. A container holds a group of
11. } components. Furthermore, in order for a component
12. public static void main(String args[]){ to be displayed must be held with in a container.
13. First2 f=new First2();
14. }} Swing components are derived from JComponent
class. Note that all component classes begin with the
Limitations of AWT, MVC letter J. For example, a label is JLabel, a button is
JButton etc.
Architecture, Components &
Containers Swing defines two types of containers. The first are
top level containers: JFrame, JApplet, JWindow, and
Limitations of AWT: JDialog. These containers do not inherit
The AWT defines a basic set of controls, windows, JComponent. They do, however inherit the AWT
and dialog boxes that support a classes Container and Component. Unlike Swing’s
usable, but limited graphical interface. One reason other components which are heavy weight, the top
for the limited nature of the AWT is level containers are heavy weight. The
that it translates its various visual components into
their corresponding, platform-specific equivalents or second type of containers are light weight inherit
peers. This means that the look and feel of a from JComponent. Example- Jpanel.
component is defined by the platform, not by java.
Because the AWT components use native code
resources, they are referred to as heavy weight. Java FlowLayout
The use of native peers led to several problems. The FlowLayout is used to arrange the components
First, because of variations between operating in a line, one after another (in a flow). It is the
systems, a component might look, or even act, default layout of applet or panel.
differently on different platforms. This variability
threatened java’s philosophy: write once, run Fields of FlowLayout class
anywhere. Second, the look and feel of each
component was fixed and could not be changed. 1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER 22. }
4. public static final int LEADING 23. public static void main(String[] args) {
5. public static final int TRAILING 24. new MyFlowLayout();
25. }
Constructors of FlowLayout class 26. }

1. FlowLayout(): creates a flow layout with BorderLayout


centered alignment and a default 5 unit horizontal
and vertical gap.
2. FlowLayout(int align): creates a flow layout Java LayoutManagers
with the given alignment and a default 5 unit
horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): The LayoutManagers are used to arrange
creates a flow layout with the given alignment components in a particular manner. LayoutManager
and the given horizontal and vertical gap. is an interface that is implemented by all the classes
of layout managers. There are following classes that
represents the layout managers:
Example of FlowLayout class
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

Java BorderLayout

The BorderLayout is used to arrange the components


in five regions: north, south, east, west and center.
Each region (area) may contain one component only.
It is the default layout of frame or window. The
BorderLayout provides five constants for each
region:
1. import java.awt.*;
2. import javax.swing.*; 1. public static final int NORTH
3. 2. public static final int SOUTH
4. public class MyFlowLayout{ 3. public static final int EAST
5. JFrame f; 4. public static final int WEST
6. MyFlowLayout(){ 5. public static final int CENTER
7. f=new JFrame();
8. Constructors of BorderLayout class:
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2"); • BorderLayout(): creates a border layout but
11. JButton b3=new JButton("3"); with no gaps between the components.
12. JButton b4=new JButton("4"); • JBorderLayout(int hgap, int vgap): creates a
13. JButton b5=new JButton("5"); border layout with the given horizontal and
14. vertical gaps between the components.
15. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b
5);
16.
17. f.setLayout(new FlowLayout(FlowLayout.RIG
HT));
18. //setting flow layout of right alignment
19.
20. f.setSize(300,300);
21. f.setVisible(true);
Example of BorderLayout class: 2. GridLayout(int rows, int columns): creates a
grid layout with the given rows and columns but
no gaps between the components.
3. GridLayout(int rows, int columns, int hgap,
int vgap): creates a grid layout with the given
rows and columns alongwith given horizontal
and vertical gaps.

Example of GridLayout class

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border {
5. JFrame f;
6. Border(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("NORTH");;
10. JButton b2=new JButton("SOUTH");;
11. JButton b3=new JButton("EAST");; 1. import java.awt.*;
12. JButton b4=new JButton("WEST");; 2. import javax.swing.*;
13. JButton b5=new JButton("CENTER");; 3.
14. 4. public class MyGridLayout{
15. f.add(b1,BorderLayout.NORTH); 5. JFrame f;
16. f.add(b2,BorderLayout.SOUTH); 6. MyGridLayout(){
17. f.add(b3,BorderLayout.EAST); 7. f=new JFrame();
18. f.add(b4,BorderLayout.WEST); 8.
19. f.add(b5,BorderLayout.CENTER); 9. JButton b1=new JButton("1");
20. 10. JButton b2=new JButton("2");
21. f.setSize(300,300); 11. JButton b3=new JButton("3");
22. f.setVisible(true); 12. JButton b4=new JButton("4");
23. } 13. JButton b5=new JButton("5");
24. public static void main(String[] args) { 14. JButton b6=new JButton("6");
25. new Border(); 15. JButton b7=new JButton("7");
26. } 16. JButton b8=new JButton("8");
27. } 17. JButton b9=new JButton("9");
18.
19. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b
Java GridLayout 5);
20. f.add(b6);f.add(b7);f.add(b8);f.add(b9);
The GridLayout is used to arrange the components 21.
22. f.setLayout(new GridLayout(3,3));
in rectangular grid. One component is displayed in
23. //setting grid layout of 3 rows and 3 columns
each rectangle. 24.
25. f.setSize(300,300);
Constructors of GridLayout class 26. f.setVisible(true);
27. }
1. GridLayout(): creates a grid layout with one 28. public static void main(String[] args) {
column per component in a row. 29. new MyGridLayout();
30. } 5.
31. } 6. public class CardLayoutExample extends JFrame
implements ActionListener{
7. CardLayout card;
Java CardLayout 8. JButton b1,b2,b3;
9. Container c;
The CardLayout class manages the components in 10. CardLayoutExample(){
such a manner that only one component is visible at 11.
a time. It treats each component as a card that is why 12. c=getContentPane();
it is known as CardLayout. 13. card=new CardLayout(40,30);
14. //create CardLayout object with 40 hor space and
30 ver space
Constructors of CardLayout class 15. c.setLayout(card);
16.
1. CardLayout(): creates a card layout with zero 17. b1=new JButton("Apple");
horizontal and vertical gap. 18. b2=new JButton("Boy");
2. CardLayout(int hgap, int vgap): creates a card 19. b3=new JButton("Cat");
layout with the given horizontal and vertical gap. 20. b1.addActionListener(this);
21. b2.addActionListener(this);
Commonly used methods of CardLayout class 22. b3.addActionListener(this);
23.
• public void next(Container parent): is used to 24. c.add("a",b1);c.add("b",b2);c.add("c",b3);
flip to the next card of the given container. 25.
• public void previous(Container parent): is 26. }
used to flip to the previous card of the given 27. public void actionPerformed(ActionEvent e) {
container.
• public void first(Container parent): is used to 28. card.next(c);
flip to the first card of the given container. 29. }
• public void last(Container parent): is used to 30.
flip to the last card of the given container. 31. public static void main(String[] args) {
• public void show(Container parent, String 32. CardLayoutExample cl=new CardLayoutEx
name): is used to flip to the specified card with ample();
the given name. 33. cl.setSize(400,400);
34. cl.setVisible(true);
35. cl.setDefaultCloseOperation(EXIT_ON_CL
OSE);
Example of CardLayout class 36. }
37. }

Java GridBagLayout
The Java GridBagLayout class is used to align
components vertically, horizontally or along their
baseline.

The components may not be of same size. Each


GridBagLayout object maintains a dynamic,
rectangular grid of cells. Each component occupies
one or more cells known as its display area. Each
component associates an instance of
GridBagConstraints. With the help of constraints
object we arrange component's display area on the
grid. The GridBagLayout manages each
component's minimum and preferred sizes in order
to determine component's size.
1. import java.awt.*;
2. import java.awt.event.*;
3.
4. import javax.swing.*;
Following steps are required to perform event
handling:

1. Register the component with the Listener

Registration Methods
• Button
o public void
addActionListener(ActionListener a){}
• MenuItem
o public void
addActionListener(ActionListener a){}
• TextField
o public void
addActionListener(ActionListener a){}
Event and Listener (Java Event o public void
addTextListener(TextListener a){}
Handling) • TextArea
o public void
Changing the state of an object is known as an
addTextListener(TextListener a){}
event. For example, click on button, dragging • Checkbox
mouse etc. The java.awt.event package provides o public void
many event classes and Listener interfaces for event addItemListener(ItemListener a){}
handling. • Choice
o public void
addItemListener(ItemListener a){}
• List
Java Event classes and Listener o public void
interfaces addActionListener(ActionListener a){}
o public void
addItemListener(ItemListener a){}
Event Classes Listener Interfaces

ActionEvent ActionListener
Java Event Handling Code
MouseListener and
MouseEvent We can put the event handling code into one of the
MouseMotionListener
following places:
MouseWheelEvent MouseWheelListener
1. Within class
KeyEvent KeyListener 2. Other class
3. Anonymous class
ItemEvent ItemListener
Java event handling by implementing
TextEvent TextListener ActionListener
AdjustmentEvent AdjustmentListener
1. import java.awt.*;
2. import java.awt.event.*;
WindowEvent WindowListener
3. class AEvent extends Frame implements ActionL
istener{
ComponentEvent ComponentListener
4. TextField tf;
5. AEvent(){
ContainerEvent ContainerListener
6.
7. //create components
FocusEvent FocusListener 8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10. Button b=new Button("click me");
Steps to perform Event Handling 11. b.setBounds(100,120,80,30);
12.
13. //register listener 10. }
14. b.addActionListener(this);//passing current instan
ce
15.
3) Java event handling by anonymous class
16. //add components and set size, layout and visibili
ty
17. add(b);add(tf); 1. import java.awt.*;
18. setSize(300,300); 2. import java.awt.event.*;
19. setLayout(null); 3. class AEvent3 extends Frame{
20. setVisible(true); 4. TextField tf;
21. } 5. AEvent3(){
22. public void actionPerformed(ActionEvent e){ 6. tf=new TextField();
23. tf.setText("Welcome"); 7. tf.setBounds(60,50,170,20);
24. } 8. Button b=new Button("click me");
25. public static void main(String args[]){ 9. b.setBounds(50,120,80,30);
26. new AEvent(); 10.
27. } 11. b.addActionListener(new ActionListener(){
28. } 12. public void actionPerformed(){
13. tf.setText("hello");
14. }
public void setBounds(int xaxis, int yaxis, int 15. });
width, int height); have been used in the above 16. add(b);add(tf);
example that sets the position of the component it 17. setSize(300,300);
may be button, textfield etc. 18. setLayout(null);
19. setVisible(true);
2) Java event handling by outer class 20. }
21. public static void main(String args[]){
1. import java.awt.*; 22. new AEvent3();
2. import java.awt.event.*; 23. }
3. class AEvent2 extends Frame{ 24. }
4. TextField tf;
5. AEvent2(){ Java AWT Button
6. //create components
7. tf=new TextField();
8. tf.setBounds(60,50,170,20); The button class is used to create a labeled button
9. Button b=new Button("click me"); that has platform independent implementation. The
10. b.setBounds(100,120,80,30); application result in some action when the button is
11. //register listener pushed.
12. Outer o=new Outer(this);
13. b.addActionListener(o);//passing outer class insta
nce
Java AWT Button Example
14. //add components and set size, layout and visibili
ty 1. import java.awt.*;
15. add(b);add(tf); 2. public class ButtonExample {
16. setSize(300,300); 3. public static void main(String[] args) {
17. setLayout(null); 4. Frame f=new Frame("Button Example");
18. setVisible(true); 5. Button b=new Button("Click Here");
19. } 6. b.setBounds(50,100,80,30);
20. public static void main(String args[]){ 7. f.add(b);
21. new AEvent2(); 8. f.setSize(400,400);
22. } 9. f.setLayout(null);
23. } 10. f.setVisible(true);
11. }
1. import java.awt.event.*; 12. }
2. class Outer implements ActionListener{
3. AEvent2 obj; Output:
4. Outer(AEvent2 obj){
5. this.obj=obj;
6. }
7. public void actionPerformed(ActionEvent e){
8. obj.tf.setText("welcome");
9. }
1. import java.awt.*;
2. class LabelExample{
3. public static void main(String args[]){
4. Frame f= new Frame("Label Example");
5. Label l1,l2;
6. l1=new Label("First Label.");
7. l1.setBounds(50,100, 100,30);
8. l2=new Label("Second Label.");
9. l2.setBounds(50,150, 100,30);
10. f.add(l1); f.add(l2);
11. f.setSize(400,400);
12. f.setLayout(null);
13. f.setVisible(true);
Java AWT Button Example with 14. }
15. }
ActionListener
Output:
1. import java.awt.*;
2. import java.awt.event.*;
3. public class ButtonExample {
4. public static void main(String[] args) {
5. Frame f=new Frame("Button Example");
6. final TextField tf=new TextField();
7. tf.setBounds(50,50, 150,20);
8. Button b=new Button("Click Here");
9. b.setBounds(50,100,60,30);
10. b.addActionListener(new ActionListener(){
11. public void actionPerformed(ActionEvent e){
12. tf.setText("Welcome to Javatpoint.");
13. }
14. });
15. f.add(b);f.add(tf);
16. f.setSize(400,400);
17. f.setLayout(null);
18. f.setVisible(true);
19. }
Java AWT Label Example with
20. } ActionListener
Output: 1. import java.awt.*;
2. import java.awt.event.*;
3. public class LabelExample extends Frame imple
ments ActionListener{
4. TextField tf; Label l; Button b;
5. LabelExample(){
6. tf=new TextField();
7. tf.setBounds(50,50, 150,20);
8. l=new Label();
9. l.setBounds(50,100, 250,20);
10. b=new Button("Find IP");
11. b.setBounds(50,150,60,30);
12. b.addActionListener(this);
13. add(b);add(tf);add(l);
Java AWT Label 14. setSize(400,400);
15. setLayout(null);
The object of Label class is a component for placing 16. setVisible(true);
text in a container. It is used to display a single line 17. }
of read only text. The text can be changed by an 18. public void actionPerformed(ActionEvent e) {
application but a user cannot edit it directly.
19. try{
20. String host=tf.getText();
Java Label Example
21. String ip=java.net.InetAddress.getByName(
host).getHostAddress();
22. l.setText("IP of "+host+" is: "+ip);
23. }catch(Exception ex){System.out.println(ex
);}
24. }
25. public static void main(String[] args) {
26. new LabelExample();
27. }
28. }

Output:

Java AWT TextField Example


with ActionListener
1. import java.awt.*;
2. import java.awt.event.*;
3. public class TextFieldExample extends Frame im
plements ActionListener{
4. TextField tf1,tf2,tf3;
5. Button b1,b2;
6. TextFieldExample(){
Java AWT TextField 7. tf1=new TextField();
8. tf1.setBounds(50,50,150,20);
The object of a TextField class is a text component 9. tf2=new TextField();
that allows the editing of a single line text. It inherits 10. tf2.setBounds(50,100,150,20);
TextComponent class. 11. tf3=new TextField();
12. tf3.setBounds(50,150,150,20);
13. tf3.setEditable(false);
Java AWT TextField Example 14. b1=new Button("+");
15. b1.setBounds(50,200,50,50);
1. import java.awt.*; 16. b2=new Button("-");
2. class TextFieldExample{ 17. b2.setBounds(120,200,50,50);
3. public static void main(String args[]){ 18. b1.addActionListener(this);
4. Frame f= new Frame("TextField Example"); 19. b2.addActionListener(this);
5. TextField t1,t2; 20. add(tf1);add(tf2);add(tf3);add(b1);add(b2);
6. t1=new TextField("Welcome to Javatpoint."); 21. setSize(300,300);
7. t1.setBounds(50,100, 200,30); 22. setLayout(null);
8. t2=new TextField("AWT Tutorial"); 23. setVisible(true);
9. t2.setBounds(50,150, 200,30); 24. }
10. f.add(t1); f.add(t2); 25. public void actionPerformed(ActionEvent e) {
11. f.setSize(400,400);
12. f.setLayout(null); 26. String s1=tf1.getText();
13. f.setVisible(true); 27. String s2=tf2.getText();
14. } 28. int a=Integer.parseInt(s1);
15. } 29. int b=Integer.parseInt(s2);
30. int c=0;
31. if(e.getSource()==b1){
Output:
32. c=a+b;
33. }else if(e.getSource()==b2){
34. c=a-b;
35. }
36. String result=String.valueOf(c);
37. tf3.setText(result);
38. }
39. public static void main(String[] args) {
40. new TextFieldExample();
41. }
42. }

Output:

Java AWT TextArea Example


with ActionListener
Java AWT TextArea
1. import java.awt.*;
The object of a TextArea class is a multi line region 2. import java.awt.event.*;
that displays text. It allows the editing of multiple 3. public class TextAreaExample extends Frame im
line text. It inherits TextComponent class. plements ActionListener{
4. Label l1,l2;
5. TextArea area;
Java AWT TextArea Example 6. Button b;
7. TextAreaExample(){
1. import java.awt.*; 8. l1=new Label();
2. public class TextAreaExample 9. l1.setBounds(50,50,100,30);
3. { 10. l2=new Label();
4. TextAreaExample(){ 11. l2.setBounds(160,50,100,30);
5. Frame f= new Frame(); 12. area=new TextArea();
6. TextArea area=new TextArea("Welcome 13. area.setBounds(20,100,300,300);
to javatpoint"); 14. b=new Button("Count Words");
7. area.setBounds(10,30, 300,300); 15. b.setBounds(100,400,100,30);
8. f.add(area); 16. b.addActionListener(this);
9. f.setSize(400,400); 17. add(l1);add(l2);add(area);add(b);
10. f.setLayout(null); 18. setSize(400,450);
11. f.setVisible(true); 19. setLayout(null);
12. } 20. setVisible(true);
13. public static void main(String args[]) 21. }
14. { 22. public void actionPerformed(ActionEvent e){
15. new TextAreaExample(); 23. String text=area.getText();
16. } 24. String words[]=text.split("\\s");
17. } 25. l1.setText("Words: "+words.length);
26. l2.setText("Characters: "+text.length());
Output: 27. }
28. public static void main(String[] args) {
29. new TextAreaExample();
30. }
31. }

Output:
Java AWT Checkbox Example
with ItemListener
1. import java.awt.*;
Java AWT Checkbox 2. import java.awt.event.*;
3. public class CheckboxExample
The Checkbox class is used to create a checkbox. It 4. {
is used to turn an option on (true) or off (false). 5. CheckboxExample(){
Clicking on a Checkbox changes its state from "on" 6. Frame f= new Frame("CheckBox Example"
to "off" or from "off" to "on". );
7. final Label label = new Label();
8. label.setAlignment(Label.CENTER);
Java AWT Checkbox Example 9. label.setSize(400,100);
10. Checkbox checkbox1 = new Checkbox("C+
1. import java.awt.*; +");
2. public class CheckboxExample 11. checkbox1.setBounds(100,100, 50,50);
3. { 12. Checkbox checkbox2 = new Checkbox("Jav
4. CheckboxExample(){ a");
5. Frame f= new Frame("Checkbox Example"); 13. checkbox2.setBounds(100,150, 50,50);
14. f.add(checkbox1); f.add(checkbox2); f.add(l
6. Checkbox checkbox1 = new Checkbox("C+ abel);
+"); 15. checkbox1.addItemListener(new ItemListen
7. checkbox1.setBounds(100,100, 50,50); er() {
8. Checkbox checkbox2 = new Checkbox("Jav 16. public void itemStateChanged(ItemEvent
a", true); e) {
9. checkbox2.setBounds(100,150, 50,50); 17. label.setText("C++ Checkbox: "
10. f.add(checkbox1); 18. + (e.getStateChange()==1?"checked":"
11. f.add(checkbox2); unchecked"));
12. f.setSize(400,400); 19. }
13. f.setLayout(null); 20. });
14. f.setVisible(true); 21. checkbox2.addItemListener(new ItemListen
15. } er() {
16. public static void main(String args[]) 22. public void itemStateChanged(ItemEvent
17. { e) {
18. new CheckboxExample(); 23. label.setText("Java Checkbox: "
19. } 24. + (e.getStateChange()==1?"checked":"
20. } unchecked"));
25. }
Output: 26. });
27. f.setSize(400,400);
28. f.setLayout(null);
29. f.setVisible(true);
30. } 6. CheckboxGroup cbg = new CheckboxGroup
31. public static void main(String args[]) ();
32. { 7. Checkbox checkBox1 = new Checkbox("C+
33. new CheckboxExample(); +", cbg, false);
34. } 8. checkBox1.setBounds(100,100, 50,50);
35. } 9. Checkbox checkBox2 = new Checkbox("Jav
a", cbg, true);
Output: 10. checkBox2.setBounds(100,150, 50,50);
11. f.add(checkBox1);
12. f.add(checkBox2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String args[])
18. {
19. new CheckboxGroupExample();
20. }
21. }

Output:

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.

Java AWT CheckboxGroup


Java AWT CheckboxGroup
The object of CheckboxGroup class is used to group
together a set of Checkbox. At a time only one check
Example with ItemListener
box button is allowed to be in "on" state and
1. import java.awt.*;
remaining check box button in "off" state. It inherits 2. import java.awt.event.*;
the object class. 3. public class CheckboxGroupExample
4. {
Note: CheckboxGroup enables you to create 5. CheckboxGroupExample(){
radio buttons in AWT. There is no special control 6. Frame f= new Frame("CheckboxGroup Exa
for creating radio buttons in AWT. mple");
7. final Label label = new Label();
8. label.setAlignment(Label.CENTER);
Java AWT CheckboxGroup 9. label.setSize(400,100);
Example 10. CheckboxGroup cbg = new CheckboxGroup
();
11. Checkbox checkBox1 = new Checkbox("C+
1. import java.awt.*;
+", cbg, false);
2. public class CheckboxGroupExample
12. checkBox1.setBounds(100,100, 50,50);
3. {
13. Checkbox checkBox2 = new Checkbox("Jav
4. CheckboxGroupExample(){
a", cbg, false);
5. Frame f= new Frame("CheckboxGroup Exa
14. checkBox2.setBounds(100,150, 50,50);
mple");
15. f.add(checkBox1); f.add(checkBox2); f.add( 7. c.setBounds(100,100, 75,75);
label); 8. c.add("Item 1");
16. f.setSize(400,400); 9. c.add("Item 2");
17. f.setLayout(null); 10. c.add("Item 3");
18. f.setVisible(true); 11. c.add("Item 4");
19. checkBox1.addItemListener(new ItemListen 12. c.add("Item 5");
er() { 13. f.add(c);
20. public void itemStateChanged(ItemEvent 14. f.setSize(400,400);
e) { 15. f.setLayout(null);
21. label.setText("C++ checkbox: Checked 16. f.setVisible(true);
"); 17. }
22. } 18. public static void main(String args[])
23. }); 19. {
24. checkBox2.addItemListener(new ItemListen 20. new ChoiceExample();
er() { 21. }
25. public void itemStateChanged(ItemEvent 22. }
e) {
26. label.setText("Java checkbox: Checked Output:
");
27. }
28. });
29. }
30. public static void main(String args[])
31. {
32. new CheckboxGroupExample();
33. }
34. }

Output:

Java AWT Choice Example with


ActionListener
1. import java.awt.*;
2. import java.awt.event.*;
3. public class ChoiceExample
4. {
5. ChoiceExample(){
6. Frame f= new Frame();
Java AWT Choice 7. final Label label = new Label();
8. label.setAlignment(Label.CENTER);
The object of Choice class is used to show popup 9. label.setSize(400,100);
menu of choices. Choice selected by user is shown 10. Button b=new Button("Show");
on the top of a menu. It inherits Component class. 11. b.setBounds(200,100,50,20);
12. final Choice c=new Choice();
13. c.setBounds(100,100, 75,75);
Java AWT Choice Example 14. c.add("C");
15. c.add("C++");
1. import java.awt.*; 16. c.add("Java");
2. public class ChoiceExample 17. c.add("PHP");
3. { 18. c.add("Android");
4. ChoiceExample(){ 19. f.add(c);f.add(label); f.add(b);
5. Frame f= new Frame(); 20. f.setSize(400,400);
6. Choice c=new Choice(); 21. f.setLayout(null);
22. f.setVisible(true); 20. new ListExample();
23. b.addActionListener(new ActionListener() { 21. }
22. }
24. public void actionPerformed(ActionEvent
e) { Output:
25. String data = "Programming language Selec
ted: "+ c.getItem(c.getSelectedIndex());
26. label.setText(data);
27. }
28. });
29. }
30. public static void main(String args[])
31. {
32. new ChoiceExample();
33. }
34. }

Output:

Java AWT List Example with


ActionListener
1. import java.awt.*;
2. import java.awt.event.*;
3. public class ListExample
4. {
5. ListExample(){
6. Frame f= new Frame();
Java AWT List 7. final Label label = new Label();
8. label.setAlignment(Label.CENTER);
9. label.setSize(500,100);
The object of List class represents a list of text 10. Button b=new Button("Show");
items. By the help of list, user can choose either one 11. b.setBounds(200,150,80,30);
item or multiple items. It inherits Component class. 12. final List l1=new List(4, false);
13. l1.setBounds(100,100, 70,70);
Java AWT List Example 14. l1.add("C");
15. l1.add("C++");
16. l1.add("Java");
1. import java.awt.*; 17. l1.add("PHP");
2. public class ListExample 18. final List l2=new List(4, true);
3. { 19. l2.setBounds(100,200, 70,70);
4. ListExample(){ 20. l2.add("Turbo C++");
5. Frame f= new Frame(); 21. l2.add("Spring");
6. List l1=new List(5); 22. l2.add("Hibernate");
7. l1.setBounds(100,100, 75,75); 23. l2.add("CodeIgniter");
8. l1.add("Item 1"); 24. f.add(l1); f.add(l2); f.add(label); f.add(b);
9. l1.add("Item 2"); 25. f.setSize(450,450);
10. l1.add("Item 3"); 26. f.setLayout(null);
11. l1.add("Item 4"); 27. f.setVisible(true);
12. l1.add("Item 5"); 28. b.addActionListener(new ActionListener() {
13. f.add(l1);
14. f.setSize(400,400); 29. public void actionPerformed(ActionEvent e
15. f.setLayout(null); ){
16. f.setVisible(true); 30. String data = "Programming language Sele
17. } cted: "+l1.getItem(l1.getSelectedIndex());
18. public static void main(String args[]) 31. data += ", Framework Selected:";
19. { 32. for(String frame:l2.getSelectedItems()){
33. data += frame + " ";
34. }
35. label.setText(data);
36. }
37. });
38. }
39. public static void main(String args[])
40. {
41. new ListExample();
42. }
43. }

Output:

Java AWT Scrollbar Example


with AdjustmentListener
1. import java.awt.*;
2. import java.awt.event.*;
3. class ScrollbarExample{
4. ScrollbarExample(){
Java AWT Scrollbar 5.
");
Frame f= new Frame("Scrollbar Example

6. final Label label = new Label();


The object of Scrollbar class is used to add 7. label.setAlignment(Label.CENTER);
horizontal and vertical scrollbar. Scrollbar is a GUI 8. label.setSize(400,100);
component allows us to see invisible number of 9. final Scrollbar s=new Scrollbar();
rows and columns. 10. s.setBounds(100,100, 50,100);
11. f.add(s);f.add(label);
12. f.setSize(400,400);
Java AWT Scrollbar Example 13. f.setLayout(null);
14. f.setVisible(true);
1. import java.awt.*; 15. s.addAdjustmentListener(new Adjustmen
2. class ScrollbarExample{ tListener() {
3. ScrollbarExample(){ 16. public void adjustmentValueChanged(
4. Frame f= new Frame("Scrollbar Example AdjustmentEvent e) {
"); 17. label.setText("Vertical Scrollbar valu
5. Scrollbar s=new Scrollbar(); e is:"+ s.getValue());
6. s.setBounds(100,100, 50,100); 18. }
7. f.add(s); 19. });
8. f.setSize(400,400); 20. }
9. f.setLayout(null); 21. public static void main(String args[]){
10. f.setVisible(true); 22. new ScrollbarExample();
11. } 23. }
12. public static void main(String args[]){ 24. }
13. new ScrollbarExample();
14. } Output:
15. }

Output:
29. }
30. }

Output:

Java AWT MenuItem and Menu


The object of MenuItem class adds a simple labeled
menu item on menu. The items used in a menu must Java AWT PopupMenu
belong to the MenuItem or any of its subclass.
PopupMenu can be dynamically popped up at
The object of Menu class is a pull down menu specific position within a component. It inherits the
component which is displayed on the menu bar. It Menu class.
inherits the MenuItem class.

Java AWT PopupMenu


Java AWT MenuItem and Menu
Example
Example
1. import java.awt.*;
1. import java.awt.*; 2. import java.awt.event.*;
2. class MenuExample 3. class PopupMenuExample
3. { 4. {
4. MenuExample(){ 5. PopupMenuExample(){
5. Frame f= new Frame("Menu and MenuItem 6. final Frame f= new Frame("PopupMenu Ex
Example"); ample");
6. MenuBar mb=new MenuBar(); 7. final PopupMenu popupmenu = new Popup
7. Menu menu=new Menu("Menu"); Menu("Edit");
8. Menu submenu=new Menu("Sub Menu"); 8. MenuItem cut = new MenuItem("Cut");
9. MenuItem i1=new MenuItem("Item 1"); 9. cut.setActionCommand("Cut");
10. MenuItem i2=new MenuItem("Item 2"); 10. MenuItem copy = new MenuItem("Copy");
11. MenuItem i3=new MenuItem("Item 3");
12. MenuItem i4=new MenuItem("Item 4"); 11. copy.setActionCommand("Copy");
13. MenuItem i5=new MenuItem("Item 5"); 12. MenuItem paste = new MenuItem("Paste");
14. menu.add(i1);
15. menu.add(i2); 13. paste.setActionCommand("Paste");
16. menu.add(i3); 14. popupmenu.add(cut);
17. submenu.add(i4); 15. popupmenu.add(copy);
18. submenu.add(i5); 16. popupmenu.add(paste);
19. menu.add(submenu); 17. f.addMouseListener(new MouseAdapter() {
20. mb.add(menu);
21. f.setMenuBar(mb); 18. public void mouseClicked(MouseEvent e)
22. f.setSize(400,400); {
23. f.setLayout(null); 19. popupmenu.show(f , e.getX(), e.getY()
24. f.setVisible(true); );
25. } 20. }
26. public static void main(String args[]) 21. });
27. { 22. f.add(popupmenu);
28. new MenuExample(); 23. f.setSize(400,400);
24. f.setLayout(null); 12. Button b2=new Button("Button 2");
25. f.setVisible(true); 13. b2.setBounds(100,100,80,30);
26. } 14. b2.setBackground(Color.green);
27. public static void main(String args[]) 15. panel.add(b1); panel.add(b2);
28. { 16. f.add(panel);
29. new PopupMenuExample(); 17. f.setSize(400,400);
30. } 18. f.setLayout(null);
31. } 19. f.setVisible(true);
20. }
Output: 21. public static void main(String args[])
22. {
23. new PanelExample();
24. }
25. }

Output:

Java AWT Dialog


Java AWT Panel The Dialog control represents a top level window
with a border and a title used to take some form of
The Panel is a simplest container class. It provides input from the user. It inherits the Window class.
space in which an application can attach any other
component. It inherits the Container class. Unlike Frame, it doesn't have maximize and
minimize buttons.
It doesn't have title bar.
Frame vs Dialog
Java AWT Panel Example
Frame and Dialog both inherits Window class.
1. import java.awt.*; Frame has maximize and minimize buttons but
2. public class PanelExample { Dialog doesn't have.
3. PanelExample()
4. {
5. Frame f= new Frame("Panel Example"); Java AWT Dialog Example
6. Panel panel=new Panel();
7. panel.setBounds(40,80,200,200); 1. import java.awt.*;
8. panel.setBackground(Color.gray); 2. import java.awt.event.*;
9. Button b1=new Button("Button 1"); 3. public class DialogExample {
10. b1.setBounds(50,100,80,30); 4. private static Dialog d;
11. b1.setBackground(Color.yellow); 5. DialogExample() {
6. Frame f= new Frame(); 7. System.out.println("Screen width = " + d.wid
7. d = new Dialog(f , "Dialog Example", true); th);
8. System.out.println("Screen height = " + d.hei
8. d.setLayout( new FlowLayout() ); ght);
9. Button b = new Button ("OK"); 9. }
10. b.addActionListener ( new ActionListener() 10. }

11. { Output:
12. public void actionPerformed( ActionEven
te) Screen resolution = 96
13. { Screen width = 1366
14. DialogExample.d.setVisible(false); Screen height = 768
15. }
16. });
17. d.add( new Label ("Click button to continue.
")); Java AWT Toolkit Example:
18.
19.
d.add(b);
d.setSize(300,300);
beep()
20. d.setVisible(true);
21. } 1. import java.awt.event.*;
22. public static void main(String args[]) 2. public class ToolkitExample {
23. { 3. public static void main(String[] args) {
24. new DialogExample(); 4. Frame f=new Frame("ToolkitExample");
25. } 5. Button b=new Button("beep");
26. } 6. b.setBounds(50,100,60,30);
7. f.add(b);
8. f.setSize(300,300);
Output: 9. f.setLayout(null);
10. f.setVisible(true);
11. b.addActionListener(new ActionListener(){
12. public void actionPerformed(ActionEvent e)
{
13. Toolkit.getDefaultToolkit().beep();
14. }
15. });
16. }
17. }

Output:

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.

Java AWT Toolkit Example


1. import java.awt.*;
2. public class ToolkitExample {
3. public static void main(String[] args) {
4. Toolkit t = Toolkit.getDefaultToolkit(); Java AWT Toolkit Example:
5. System.out.println("Screen resolution = " + t.
getScreenResolution()); Change TitleBar Icon
6. Dimension d = t.getScreenSize();
1. import java.awt.*;
2. class ToolkitExample { 5. Frame f=new Frame("ActionListener Example
3. ToolkitExample(){ ");
4. Frame f=new Frame(); 6. final TextField tf=new TextField();
5. Image icon = Toolkit.getDefaultToolkit().getIma 7. tf.setBounds(50,50, 150,20);
ge("D:\\icon.png"); 8. Button b=new Button("Click Here");
6. f.setIconImage(icon); 9. b.setBounds(50,100,60,30);
7. f.setLayout(null); 10.
8. f.setSize(400,400); 11. b.addActionListener(new ActionListener(){
9. f.setVisible(true); 12. public void actionPerformed(ActionEvent e){
10. } 13. tf.setText("Welcome to Javatpoint.");
11. public static void main(String args[]){ 14. }
12. new ToolkitExample(); 15. });
13. } 16. f.add(b);f.add(tf);
14. } 17. f.setSize(400,400);
18. f.setLayout(null);
Output: 19. f.setVisible(true);
20. }
21. }

Output:

Java MouseListener Interface


Java ActionListener Interface
The Java MouseListener is notified whenever you
The Java ActionListener is notified whenever you change the state of mouse. It is notified against
click on the button or menu item. It is notified MouseEvent. The MouseListener interface is found
against ActionEvent. The ActionListener interface is in java.awt.event package. It has five methods.
found in java.awt.event package. It has only one
method: actionPerformed().
Methods of MouseListener
actionPerformed() method interface
The actionPerformed() method is invoked The signature of 5 methods found in MouseListener
automatically whenever you click on the registered interface are given below:
component.
1. public abstract void mouseClicked(MouseEvent
e);
1. public abstract void actionPerformed(ActionEven
2. public abstract void mouseEntered(MouseEvent
t e);
e);
3. public abstract void mouseExited(MouseEvent e)
Java ActionListener Example: ;
4. public abstract void mousePressed(MouseEvent e
On Button click );
5. public abstract void mouseReleased(MouseEvent
1. import java.awt.*; e);
2. import java.awt.event.*;
3. public class ActionListenerExample {
4. public static void main(String[] args) { Java MouseListener Example
1. import java.awt.*;
2. import java.awt.event.*;
Java MouseMotionListener
3. public class MouseListenerExample extends Fra Interface
me implements MouseListener{
4. Label l;
5. MouseListenerExample(){ The Java MouseMotionListener is notified whenever
6. addMouseListener(this); you move or drag mouse. It is notified against
7. MouseEvent. The MouseMotionListener interface is
8. l=new Label(); found in java.awt.event package. It has two methods.
9. l.setBounds(20,50,100,20);
10. add(l);
11. setSize(300,300); Methods of
12. setLayout(null); MouseMotionListener interface
13. setVisible(true);
14. }
1. public abstract void mouseDragged(MouseEvent
15. public void mouseClicked(MouseEvent e) {
e);
16. l.setText("Mouse Clicked");
2. public abstract void mouseMoved(MouseEvent e
17. }
);
18. public void mouseEntered(MouseEvent e) {
19. l.setText("Mouse Entered");
20. } Java MouseMotionListener
21. public void mouseExited(MouseEvent e) {
22. l.setText("Mouse Exited"); Example
23. }
24. public void mousePressed(MouseEvent e) { 1. import java.awt.*;
25. l.setText("Mouse Pressed"); 2. import java.awt.event.*;
26. } 3. public class MouseMotionListenerExample exten
27. public void mouseReleased(MouseEvent e) { ds Frame implements MouseMotionListener{
28. l.setText("Mouse Released"); 4. MouseMotionListenerExample(){
29. } 5. addMouseMotionListener(this);
30. public static void main(String[] args) { 6.
31. new MouseListenerExample(); 7. setSize(300,300);
32. } 8. setLayout(null);
33. } 9. setVisible(true);
10. }
Output: 11. public void mouseDragged(MouseEvent e) {
12. Graphics g=getGraphics();
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),20,20);
15. }
16. public void mouseMoved(MouseEvent e) {}
17.
18. public static void main(String[] args) {
19. new MouseMotionListenerExample();
20. }
21. }

Output:
17. checkBox2.addItemListener(this);
18. f.setSize(400,400);
19. f.setLayout(null);
20. f.setVisible(true);
21. }
22. public void itemStateChanged(ItemEvent e) {

23. if(e.getSource()==checkBox1)
24. label.setText("C++ Checkbox: "
25. + (e.getStateChange()==1?"checked":"un
checked"));
26. if(e.getSource()==checkBox2)
27. label.setText("Java Checkbox: "
28. + (e.getStateChange()==1?"checked":"unch
ecked"));
29. }
30. public static void main(String args[])
31. {
32. new ItemListenerExample();
33. }
Java ItemListener Interface 34. }

The Java ItemListener is notified whenever you Output:


click on the checkbox. It is notified against
ItemEvent. The ItemListener interface is found in
java.awt.event package. It has only one method:
itemStateChanged().

itemStateChanged() method
The itemStateChanged() method is invoked
automatically whenever you click or unclick on the
registered checkbox component.

1. public abstract void itemStateChanged(ItemEven


t e);

Java ItemListener Example


1. import java.awt.*;
2. import java.awt.event.*;
3. public class ItemListenerExample implements Ite
mListener{
Java KeyListener Interface
4. Checkbox checkBox1,checkBox2;
5. Label label; The Java KeyListener is notified whenever you
6. ItemListenerExample(){ change the state of key. It is notified against
7. Frame f= new Frame("CheckBox Example" KeyEvent. The KeyListener interface is found in
); java.awt.event package. It has three methods.
8. label = new Label();
9. label.setAlignment(Label.CENTER);
10. label.setSize(400,100); Methods of KeyListener
11. checkBox1 = new Checkbox("C++"); interface
12. checkBox1.setBounds(100,100, 50,50);
13. checkBox2 = new Checkbox("Java");
14. checkBox2.setBounds(100,150, 50,50); The signature of 3 methods found in KeyListener
15. f.add(checkBox1); f.add(checkBox2); f.add( interface are given below:
label);
16. checkBox1.addItemListener(this); 1. public abstract void keyPressed(KeyEvent e);
2. public abstract void keyReleased(KeyEvent e);
3. public abstract void keyTyped(KeyEvent e);
Java WindowListener Interface
Java KeyListener Example The Java WindowListener is notified whenever you
change the state of window. It is notified against
1. import java.awt.*; WindowEvent. The WindowListener interface is
2. import java.awt.event.*; found in java.awt.event package. It has three
3. public class KeyListenerExample extends Frame
methods.
implements KeyListener{
4. Label l;
5. TextArea area; Methods of WindowListener
6. KeyListenerExample(){
7. interface
8. l=new Label();
9. l.setBounds(20,50,100,20); The signature of 7 methods found in
10. area=new TextArea(); WindowListener interface are given below:
11. area.setBounds(20,80,300, 300);
12. area.addKeyListener(this); 1. public abstract void windowActivated(WindowE
13. vent e);
14. add(l);add(area); 2. public abstract void windowClosed(WindowEve
15. setSize(400,400); nt e);
16. setLayout(null); 3. public abstract void windowClosing(WindowEve
17. setVisible(true); nt e);
18. } 4. public abstract void windowDeactivated(Window
19. public void keyPressed(KeyEvent e) { Event e);
20. l.setText("Key Pressed"); 5. public abstract void windowDeiconified(Window
21. } Event e);
22. public void keyReleased(KeyEvent e) { 6. public abstract void windowIconified(WindowEv
23. l.setText("Key Released"); ent e);
24. } 7. public abstract void windowOpened(WindowEve
25. public void keyTyped(KeyEvent e) { nt e);
26. l.setText("Key Typed");
27. }
28. Java WindowListener Example
29. public static void main(String[] args) {
30. new KeyListenerExample(); 1. import java.awt.*;
31. } 2. import java.awt.event.WindowEvent;
32. } 3. import java.awt.event.WindowListener;
4. public class WindowExample extends Frame imp
Output: lements WindowListener{
5. WindowExample(){
6. addWindowListener(this);
7.
8. setSize(400,400);
9. setLayout(null);
10. setVisible(true);
11. }
12.
13. public static void main(String[] args) {
14. new WindowExample();
15. }
16. public void windowActivated(WindowEvent arg
0) {
17. System.out.println("activated");
18. }
19. public void windowClosed(WindowEvent arg0)
{
20. System.out.println("closed");
21. }
22. public void windowClosing(WindowEvent arg0)
{
23. System.out.println("closing");
24. dispose();
25. }
java.awt.event Adapter classes
26. public void windowDeactivated(WindowEvent ar
g0) { Adapter class Listener interface
27. System.out.println("deactivated");
28. } WindowAdapter WindowListener
29. public void windowDeiconified(WindowEvent ar
g0) { KeyAdapter KeyListener
30. System.out.println("deiconified");
31. } MouseAdapter MouseListener
32. public void windowIconified(WindowEvent arg0
){ MouseMotionAdapter MouseMotionListener
33. System.out.println("iconified");
34. } FocusAdapter FocusListener
35. public void windowOpened(WindowEvent arg0)
{ ComponentAdapter ComponentListener
36. System.out.println("opened");
37. } ContainerAdapter ContainerListener
38. }
HierarchyBoundsAdapter HierarchyBoundsListener
Output:

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


1. import java.awt.*;
Java Adapter Classes 2. import java.awt.event.*;
3. public class AdapterExample{
Java adapter classes provide the default 4. Frame f;
implementation of listener interfaces. If you inherit 5. AdapterExample(){
the adapter class, you will not be forced to provide 6. f=new Frame("Window Adapter");
7. f.addWindowListener(new WindowAdapter
the implementation of all the methods of listener
(){
interfaces. So it saves code. 8. public void windowClosing(WindowEve
nt e) {
The adapter classes are found in java.awt.event, 9. f.dispose();
java.awt.dnd and javax.swing.event packages. The 10. }
Adapter classes with their corresponding listener 11. });
interfaces are given below. 12.
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new AdapterExample();
19. }
20. }

Output:

Java MouseMotionAdapter
Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseMotionAdapterExample exten
Java MouseAdapter Example ds MouseMotionAdapter{
4. Frame f;
1. import java.awt.*; 5. MouseMotionAdapterExample(){
2. import java.awt.event.*; 6. f=new Frame("Mouse Motion Adapter");
3. public class MouseAdapterExample extends Mou 7. f.addMouseMotionListener(this);
seAdapter{ 8.
4. Frame f; 9. f.setSize(300,300);
5. MouseAdapterExample(){ 10. f.setLayout(null);
6. f=new Frame("Mouse Adapter"); 11. f.setVisible(true);
7. f.addMouseListener(this); 12. }
8. 13. public void mouseDragged(MouseEvent e) {
9. f.setSize(300,300); 14. Graphics g=f.getGraphics();
10. f.setLayout(null); 15. g.setColor(Color.ORANGE);
11. f.setVisible(true); 16. g.fillOval(e.getX(),e.getY(),20,20);
12. } 17. }
13. public void mouseClicked(MouseEvent e) { 18. public static void main(String[] args) {
14. Graphics g=f.getGraphics(); 19. new MouseMotionAdapterExample();
15. g.setColor(Color.BLUE); 20. }
16. g.fillOval(e.getX(),e.getY(),30,30); 21. }
17. }
18. Output:
19. public static void main(String[] args) {
20. new MouseAdapterExample();
21. }
22. }

Output:
Java KeyAdapter Example
1. import java.awt.*; How to close AWT Window in
2. import java.awt.event.*;
3. public class KeyAdapterExample extends KeyAd Java
apter{
4. Label l; We can close the AWT Window or Frame by calling
5. TextArea area; dispose() or System.exit() inside windowClosing()
6. Frame f;
method. The windowClosing() method is found in
7. KeyAdapterExample(){
8. f=new Frame("Key Adapter"); WindowListener interface and WindowAdapter
9. l=new Label(); class.
10. l.setBounds(20,50,200,20);
11. area=new TextArea(); The WindowAdapter class implements
12. area.setBounds(20,80,300, 300); WindowListener interfaces. It provides the default
13. area.addKeyListener(this); implementation of all the 7 methods of
14. WindowListener interface. To override the
15. f.add(l);f.add(area); windowClosing() method, you can either use
16. f.setSize(400,400); WindowAdapter class or WindowListener interface.
17. f.setLayout(null);
18. f.setVisible(true);
19. } If you implement the WindowListener interface, you
20. public void keyReleased(KeyEvent e) { will be forced to override all the 7 methods of
21. String text=area.getText(); WindowListener interface. So it is better to use
22. String words[]=text.split("\\s"); WindowAdapter class.
23. l.setText("Words: "+words.length+" Charact
ers:"+text.length());
24. }
Different ways to override
25. windowClosing() method
26. public static void main(String[] args) {
27. new KeyAdapterExample(); There are many ways to override windowClosing()
28. }
method:
29. }
• By anonymous class
Output: • By inheriting WindowAdapter class
• By implementing WindowListener interface

Close AWT Window Example 1:


Anonymous class
1. import java.awt.*;
2. import java.awt.event.WindowEvent; 15. }
3. import java.awt.event.WindowListener; 16. public static void main(String[] args) {
4. public class WindowExample extends Frame{ 17. new AdapterExample();
5. WindowExample(){ 18. }
6. addWindowListener(new WindowAdapter() 19. }
{
7. public void windowClosing(WindowEve
nt e) { Close AWT Window Example 3:
8. dispose(); implementing WindowListener
9. }
10. });
1. import java.awt.*;
11. setSize(400,400);
2. import java.awt.event.WindowEvent;
12. setLayout(null);
3. import java.awt.event.WindowListener;
13. setVisible(true);
4. public class WindowExample extends Frame imp
14. }
lements WindowListener{
15. public static void main(String[] args) {
5. WindowExample(){
16. new WindowExample();
6. addWindowListener(this);
17. }
7.
8. setSize(400,400);
Output: 9. setLayout(null);
10. setVisible(true);
11. }
12.
13. public static void main(String[] args) {
14. new WindowExample();
15. }
16. public void windowActivated(WindowEvent e) {
}
17. public void windowClosed(WindowEvent e) {}
18. public void windowClosing(WindowEvent e) {
19. dispose();
20. }
21. public void windowDeactivated(WindowEvent e)
{}
22. public void windowDeiconified(WindowEvent e)
{}
23. public void windowIconified(WindowEvent e) {
}
24. public void windowOpened(WindowEvent arg0)
{}
25. }

Close AWT Window Example 2:


extending WindowAdapter
1. import java.awt.*;
2. import java.awt.event.*;
3. public class AdapterExample extends WindowA
dapter{
4. Frame f;
5. AdapterExample(){
6. f=new Frame();
7. f.addWindowListener(this);
8.
9. f.setSize(400,400);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13. public void windowClosing(WindowEvent e) {
14. f.dispose();
Java Swing
Java Swing tutorial is a part of Java Foundation
Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in
java.

Unlike AWT, Java Swing provides platform-


independent and lightweight components.

The javax.swing package provides classes for java


swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser
etc.
Commonly used Methods of Component class
Method Description
Difference between AWT and Swing
Java AWT Java Swing public void add a component on
add(Component c) another component.
AWT components are Java swing components are
platform-dependent. platform-independent. public void setSize(int sets size of the
width,int height) component.
AWT components are Swing components are
heavyweight. lightweight. public void setLayout sets the layout manager
(LayoutManager m) for the component.
AWT doesn't support
Swing supports pluggable sets the visibility of the
pluggable look and public void
look and feel. component. It is by
feel. setVisible(boolean b)
default false.
Swing provides more
AWT provides less powerful components
components than such as tables, lists, Java Swing Examples
Swing. scrollpanes, colorchooser,
tabbedpane etc. There are two ways to create a frame:
AWT doesn't follows • By creating the object of Frame class
MVC(Model View (association)
Controller) where • By extending Frame class (inheritance)
model represents data,
view represents Swing follows MVC. We can write the code of swing inside the main(),
presentation and constructor or any other method.
controller acts as an
interface between
model and view.
Simple Java Swing Example
Hierarchy of Java Swing classes
Let's see a simple swing example where we are
The hierarchy of java swing API is given below. creating one button and adding it on the JFrame
object inside the main() method.

File: FirstSwingExample.java

1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFr 11.
ame 12. f.setSize(400,500);//400 width and 500 height
5. 13. f.setLayout(null);//using no layout managers
6. JButton b=new JButton("click");//creating instan 14. f.setVisible(true);//making the frame visible
ce of JButton 15. }
7. b.setBounds(130,100,100, 40);//x axis, y axis, wi 16.
dth, height 17. public static void main(String[] args) {
8. 18. new Simple();
9. f.add(b);//adding button in JFrame 19. }
10. 20. }
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers The setBounds(int xaxis, int yaxis, int width, int
13. f.setVisible(true);//making the frame visible height)is used in the above example that sets the
14. } position of the button.
15. }

Simple example of Swing by inheritance

We can also inherit the JFrame class, so there is no


need to create the instance of JFrame class
explicitly.

File: Simple2.java

1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting
JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,100,100, 40);
7.
8. add(b);//adding button on frame
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. }
13. public static void main(String[] args) {
14. new Simple2();
15. }}
Example of Swing by Association inside
constructor
Java Applet
We can also write all the codes of creating JFrame,
JButton and method call inside the java constructor. Applet is a special type of program that is embedded
in the webpage to generate the dynamic content. It
File: Simple.java runs inside the browser and works at client side.

1. import javax.swing.*; Advantage of Applet


2. public class Simple {
3. JFrame f;
There are many advantages of applet. They are as
4. Simple(){
5. f=new JFrame();//creating instance of JFrame
follows:
6.
7. JButton b=new JButton("click");//creating instan • It works at client side so less response time.
ce of JButton • Secured
8. b.setBounds(130,100,100, 40); • It can be executed by browsers running under
9. many plateforms, including Linux, Windows,
10. f.add(b);//adding button in JFrame Mac Os etc.
Drawback of Applet How to run an Applet?

• Plugin is required at client browser to execute There are two ways to run an applet
applet.
1. By html file.
Hierarchy of Applet 2. 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.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }

Note: class must be public because its object is


created by Java Plugin software that resides on
the browser.

myapplet.html

ava.applet.Applet class 1. <html>


2. <body>
3. <applet code="First.class" width="300" height="
For creating any applet java.applet.Applet class must 300">
be inherited. It provides 4 life cycle methods of 4. </applet>
applet. 5. </body>
6. </html>
1. public void init(): is used to initialized the
Applet. It is invoked only once.
2. public void start(): is invoked after the init() Parameter in Applet
method or browser is maximized. It is used to
start the Applet. We can get any information from the HTML file as
3. public void stop(): is used to stop the Applet. It a parameter. For this purpose, Applet class provides
is invoked when Applet is stop or browser is a method named getParameter(). Syntax:
minimized.
4. public void destroy(): is used to destroy the
1. public String getParameter(String parameterNam
Applet. It is invoked only once.
e)
java.awt.Component class
Example of using parameter in
The Component class provides 1 life cycle method Applet:
of applet.

1. public void paint(Graphics g): is used to paint


the Applet. It provides Graphics class object that
1. import java.applet.Applet;
can be used for drawing oval, rectangle, arc etc.
2. import java.awt.Graphics;
3. 3. <applet code="MouseDrag.class" width="300" h
4. public class UseParam extends Applet{ eight="300">
5. 4. </applet>
6. public void paint(Graphics g){ 5. </body>
7. String str=getParameter("msg"); 6. </html>
8. g.drawString(str,50, 50);
9. }
10. Java JLabel
11. }
The object of JLabel class is a component for
myapplet.html placing text in a container. It is used to display a
single line of read only text. The text can be changed
1. <html> by an application but a user cannot edit it directly. It
2. <body> inherits JComponent class.
3. <applet code="UseParam.class" width="300" hei
ght="300"> Commonly used Constructors:
4. <param name="msg" value="Welcome to applet"
Constructor Description
>
5. </applet>
Creates a JLabel instance with no
6. </body>
7. </html> JLabel() image and with an empty string
for the title.

Painting in Applet JLabel(String s)


Creates a JLabel instance with the
We can perform painting operation in applet by the specified text.
mouseDragged() method of MouseMotionListener.
Creates a JLabel instance with the
JLabel(Icon i)
specified image.

Example of Painting in Applet: JLabel(String s, Icon Creates a JLabel instance with the
i, int specified text, image, and
1. import java.awt.*; horizontalAlignment) horizontal alignment.
2. import java.awt.event.*;
3. import java.applet.*;
4. public class MouseDrag extends Applet impleme
nts MouseMotionListener{ Commonly used Methods:
5. Methods Description
6. public void init(){
7. addMouseMotionListener(this); t returns the text string that a
8. setBackground(Color.red); String getText()
label displays.
9. }
10. void setText(String It defines the single line of text
11. public void mouseDragged(MouseEvent me){ text) this component will display.
12. Graphics g=getGraphics();
13. g.setColor(Color.white); void
14. g.fillOval(me.getX(),me.getY(),5,5); It sets the alignment of the
setHorizontalAlignme
15. } label's contents along the X axis.
16. public void mouseMoved(MouseEvent me){} nt (int alignment)
17.
18. } It returns the graphic image that
Icon getIcon()
the label displays.
In the above example, getX() and getY() method of int getHorizontal It returns the alignment of the
MouseEvent is used to get the current x-axis and y-axis. Alignment() label's contents along the X axis.
The getGraphics() method of Component class returns
the object of Graphics.
myapplet.html Java JLabel Example
1. <html> 1. import javax.swing.*;
2. <body> 2. class LabelExample
3. {
4. public static void main(String args[]) 20. try{
5. { 21. String host=tf.getText();
6. JFrame f= new JFrame("Label Example"); 22. String ip=java.net.InetAddress.getByName(
7. JLabel l1,l2; host).getHostAddress();
8. l1=new JLabel("First Label."); 23. l.setText("IP of "+host+" is: "+ip);
9. l1.setBounds(50,50, 100,30); 24. }catch(Exception ex){System.out.println(ex
10. l2=new JLabel("Second Label."); );}
11. l2.setBounds(50,100, 100,30); 25. }
12. f.add(l1); f.add(l2); 26. public static void main(String[] args) {
13. f.setSize(300,300); 27. new LabelExample();
14. f.setLayout(null); 28. }}
15. f.setVisible(true);
16. } Output:
17. }

Output:

Java JTextField
The object of a JTextField class is a text component
that allows the editing of a single line text. It inherits
JTextComponent class.
Java JLabel Example with
ActionListener Commonly used Methods:
1. import javax.swing.*; Methods Description
2. import java.awt.*;
3. import java.awt.event.*; void It is used to add the specified
4. public class LabelExample extends Frame imple addActionListener action listener to receive action
ments ActionListener{ (ActionListener l) events from this textfield.
5. JTextField tf; JLabel l; JButton b;
6. LabelExample(){ It returns the currently set Action
7. tf=new JTextField(); Action getAction() for this ActionEvent source, or
8. tf.setBounds(50,50, 150,20); null if no Action is set.
9. l=new JLabel();
10. l.setBounds(50,100, 250,20); void setFont(Font f) It is used to set the current font.
11. b=new JButton("Find IP");
12. b.setBounds(50,150,95,30); It is used to remove the specified
13. b.addActionListener(this); void
action listener so that it no longer
14. add(b);add(tf);add(l); removeActionListener
receives action events from this
15. setSize(400,400); (ActionListener l)
textfield.
16. setLayout(null);
17. setVisible(true);
18. }
19. public void actionPerformed(ActionEvent e) {
Java JTextField Example
1. import javax.swing.*; 15. b1=new JButton("+");
2. class TextFieldExample 16. b1.setBounds(50,200,50,50);
3. { 17. b2=new JButton("-");
4. public static void main(String args[]) 18. b2.setBounds(120,200,50,50);
5. { 19. b1.addActionListener(this);
6. JFrame f= new JFrame("TextField Example"); 20. b2.addActionListener(this);
21. f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.ad
7. JTextField t1,t2; d(b2);
8. t1=new JTextField("Welcome to Javatpoint."); 22. f.setSize(300,300);
23. f.setLayout(null);
9. t1.setBounds(50,100, 200,30); 24. f.setVisible(true);
10. t2=new JTextField("AWT Tutorial"); 25. }
11. t2.setBounds(50,150, 200,30); 26. public void actionPerformed(ActionEvent e) {
12. f.add(t1); f.add(t2);
13. f.setSize(400,400); 27. String s1=tf1.getText();
14. f.setLayout(null); 28. String s2=tf2.getText();
15. f.setVisible(true); 29. int a=Integer.parseInt(s1);
16. } 30. int b=Integer.parseInt(s2);
17. } 31. int c=0;
32. if(e.getSource()==b1){
Output: 33. c=a+b;
34. }else if(e.getSource()==b2){
35. c=a-b;
36. }
37. String result=String.valueOf(c);
38. tf3.setText(result);
39. }
40. public static void main(String[] args) {
41. new TextFieldExample();
42. } }

Output:

Java JTextField Example with


ActionListener
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class TextFieldExample implements Actio
nListener{
4. JTextField tf1,tf2,tf3;
5. JButton b1,b2;
6. TextFieldExample(){ Java JButton
7. JFrame f= new JFrame();
8. tf1=new JTextField();
9. tf1.setBounds(50,50,150,20); The JButton class is used to create a labeled button
10. tf2=new JTextField(); that has platform independent implementation. The
11. tf2.setBounds(50,100,150,20); application result in some action when the button is
12. tf3=new JTextField(); pushed. It inherits AbstractButton class.
13. tf3.setBounds(50,150,150,20);
14. tf3.setEditable(false);
8. f.setSize(400,400);
JButton class declaration 9. f.setLayout(null);
10. f.setVisible(true);
Let's see the declaration for javax.swing.JButton 11. }
class. 12. }

1. public class JButton extends AbstractButton impl Output:


ements Accessible

Commonly used Constructors:


Constructor Description

It creates a button with no


JButton()
text and icon.

It creates a button with the


JButton(String s)
specified text.

It creates a button with the


JButton(Icon i)
specified icon object.

Commonly used Methods of AbstractButton


class:
Methods Description

void setText(String s)
It is used to set specified Java JButton Example with
text on button
ActionListener
It is used to return the text
String getText() 1. import java.awt.event.*;
of the button.
2. import javax.swing.*;
3. public class ButtonExample {
void setEnabled(boolean It is used to enable or
4. public static void main(String[] args) {
b) disable the button.
5. JFrame f=new JFrame("Button Example");
6. final JTextField tf=new JTextField();
It is used to set the
7. tf.setBounds(50,50, 150,20);
void setIcon(Icon b) specified Icon on the 8. JButton b=new JButton("Click Here");
button. 9. b.setBounds(50,100,95,30);
10. b.addActionListener(new ActionListener(){
It is used to get the Icon of 11. public void actionPerformed(ActionEvent e){
Icon getIcon()
the button. 12. tf.setText("Welcome to Javatpoint.");
13. }
It is used to set the 14. });
void setMnemonic(int a)
mnemonic on the button. 15. f.add(b);f.add(tf);
16. f.setSize(400,400);
void addActionListener It is used to add the action 17. f.setLayout(null);
(ActionListener a) listener to this object. 18. f.setVisible(true);
19. }
20. }
Java JButton Example Output:
1. import javax.swing.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton("Click Here");
6. b.setBounds(50,100,95,30);
7. f.add(b);
Java JToggleButton
JToggleButton is used to create toggle button, it is
two-states button to switch on or off.

Nested Classes
Type Class Description

protect This class implements


JToggleButton.Acce
ed accessibility support for
ssibleJToggleButton
class the JToggleButton class.

static JToggleButton.Togg The ToggleButton


class leButtonModel model

Methods
Example of displaying image on Modifier
Method Description
and Type
the button:
getAccessi It gets the AccessibleContext
1. import javax.swing.*; Accessible
bleContext( associated with this
2. public class ButtonExample{ Context
) JToggleButton.
3. ButtonExample(){
4. JFrame f=new JFrame("Button Example");
It returns a string that
5. JButton b=new JButton(new ImageIcon("D:\\ico getUIClassI specifies the name of the l&f
String
n.png")); D() class that renders this
6. b.setBounds(100,100,100, 40); component.
7. f.add(b);
8. f.setSize(300,400); It returns a string
protected paramStrin
9. f.setLayout(null); representation of this
String g()
10. f.setVisible(true); JToggleButton.
11. f.setDefaultCloseOperation(JFrame.EXIT_ON_C
LOSE); It resets the UI property to a
12. } void updateUI() value from the current look
13. public static void main(String[] args) { and feel.
14. new ButtonExample();
15. }
16. }

Output: JToggleButton Example


1. import java.awt.FlowLayout;
2. import java.awt.event.ItemEvent;
3. import java.awt.event.ItemListener;
4. import javax.swing.JFrame;
5. import javax.swing.JToggleButton;
6.
7. public class JToggleButtonExample extends JFra
me implements ItemListener {
8. public static void main(String[] args) {
9. new JToggleButtonExample();
10. }
11. private JToggleButton button;
12. JToggleButtonExample() {
13. setTitle("JToggleButton with ItemListener
Example");
14. setLayout(new FlowLayout());
15. setJToggleButton();
16. setAction();
17. setSize(200, 200);
18. setVisible(true);
Java JCheckBox Example
19. setDefaultCloseOperation(JFrame.EXIT_O
N_CLOSE); 1. import javax.swing.*;
20. } 2. public class CheckBoxExample
21. private void setJToggleButton() { 3. {
22. button = new JToggleButton("ON"); 4. CheckBoxExample(){
23. add(button); 5. JFrame f= new JFrame("CheckBox Exampl
24. } e");
25. private void setAction() { 6. JCheckBox checkBox1 = new JCheckBox("
26. button.addItemListener(this); C++");
27. } 7. checkBox1.setBounds(100,100, 50,50);
28. public void itemStateChanged(ItemEvent eve) 8. JCheckBox checkBox2 = new JCheckBox("
{ Java", true);
29. if (button.isSelected()) 9. checkBox2.setBounds(100,150, 50,50);
30. button.setText("OFF"); 10. f.add(checkBox1);
31. else 11. f.add(checkBox2);
32. button.setText("ON"); 12. f.setSize(400,400);
33. } 13. f.setLayout(null);
34. } 14. f.setVisible(true);
15. }
16. public static void main(String args[])
Output
17. {
18. new CheckBoxExample();
19. }}

Output:

Java JCheckBox
The JCheckBox class is used to create a checkbox. It
is used to turn an option on (true) or off (false).
Clicking on a CheckBox changes its state from "on"
to "off" or from "off" to "on ".It inherits
JToggleButton class.

Commonly used Methods:


Methods Description
Java JRadioButton
It is used to get the
AccessibleContext
AccessibleContext associated The JRadioButton class is used to create a radio
getAccessibleContext()
with this JCheckBox. button. It is used to choose one option from multiple
options. It is widely used in exam systems or quiz.
It returns a string
protected String
representation of this It should be added in ButtonGroup to select one
paramString()
JCheckBox. radio button only.
Commonly used Methods:
Methods Description

void setText(String It is used to set specified text


s) on button.

It is used to return the text of


String getText()
the button.

void
It is used to enable or disable
setEnabled(boolean
the button.
b)

It is used to set the specified


void setIcon(Icon b)
Icon on the button.

It is used to get the Icon of the


Icon getIcon()
button. Java JTabbedPane
void It is used to set the mnemonic The JTabbedPane class is used to switch between a
setMnemonic(int a) on the button. group of components by clicking on a tab with a
given title or icon. It inherits JComponent class.
void
It is used to add the action
addActionListener
listener to this object.
(ActionListener a)

Java JTabbedPane Example


Java JRadioButton Example 1. import javax.swing.*;
2. public class TabbedPaneExample {
3. JFrame f;
1. import javax.swing.*;
4. TabbedPaneExample(){
2. public class RadioButtonExample {
5. f=new JFrame();
3. JFrame f;
6. JTextArea ta=new JTextArea(200,200);
4. RadioButtonExample(){
7. JPanel p1=new JPanel();
5. f=new JFrame();
8. p1.add(ta);
6. JRadioButton r1=new JRadioButton("A) Male");
9. JPanel p2=new JPanel();
10. JPanel p3=new JPanel();
7. JRadioButton r2=new JRadioButton("B) Female"
11. JTabbedPane tp=new JTabbedPane();
);
12. tp.setBounds(50,50,200,200);
8. r1.setBounds(75,50,100,30);
13. tp.add("main",p1);
9. r2.setBounds(75,100,100,30);
14. tp.add("visit",p2);
10. ButtonGroup bg=new ButtonGroup();
15. tp.add("help",p3);
11. bg.add(r1);bg.add(r2);
16. f.add(tp);
12. f.add(r1);f.add(r2);
17. f.setSize(400,400);
13. f.setSize(300,300);
18. f.setLayout(null);
14. f.setLayout(null);
19. f.setVisible(true);
15. f.setVisible(true);
20. }
16. }
21. public static void main(String[] args) {
17. public static void main(String[] args) {
22. new TabbedPaneExample();
18. new RadioButtonExample();
23. }}
19. }
20. }
Output:
Output:
JScrollPane Example
1. import java.awt.FlowLayout;
2. import javax.swing.JFrame;
3. import javax.swing.JScrollPane;
4. import javax.swing.JtextArea;
5.
6. public class JScrollPaneExample {
7. private static final long serialVersionUID = 1L
;
8.
9. private static void createAndShowGUI() {
10.
11. // Create and set up the window.
12. final JFrame frame = new JFrame("Scroll Pa
ne Example");
13.
Java JScrollPane 14. // Display the window.
15. frame.setSize(500, 500);
16. frame.setVisible(true);
A JscrollPane is used to make scrollable view of a
17. frame.setDefaultCloseOperation(JFrame.EX
component. When screen size is limited, we use a IT_ON_CLOSE);
scroll pane to display a large component or a 18.
component whose size can change dynamically. 19. // set flow layout for the frame
20. frame.getContentPane().setLayout(new Flo
Useful Methods wLayout());
Type Method Description 21.
22. JTextArea textArea = new JTextArea(20, 20
setColumnHead );
It sets the column header for 23. JScrollPane scrollableTextArea = new JScro
void erView(Compon
the scroll pane. llPane(textArea);
ent)
24.
25. scrollableTextArea.setHorizontalScrollBarP
setRowHeaderV It sets the row header for the
void olicy(JScrollPane.HORIZONTAL_SCROLLBA
iew(Component) scroll pane.
R_ALWAYS);
26. scrollableTextArea.setVerticalScrollBarPoli
setCorner(String It sets or gets the specified
void cy(JScrollPane.VERTICAL_SCROLLBAR_AL
, Component) corner. The int parameter WAYS);
specifies which corner and 27.
must be one of the following 28. frame.getContentPane().add(scrollableText
constants defined in Area);
ScrollPaneConstants: 29. }
UPPER_LEFT_CORNER, 30. public static void main(String[] args) {
UPPER_RIGHT_CORNER, 31.
LOWER_LEFT_CORNER, 32.
LOWER_RIGHT_CORNER, 33. javax.swing.SwingUtilities.invokeLater(new
getCorner(String Runnable() {
Component LOWER_LEADING_CORNE
) 34.
R,
35. public void run() {
LOWER_TRAILING_CORN
36. createAndShowGUI();
ER, 37. }
UPPER_LEADING_CORNE 38. });
R, 39. }
UPPER_TRAILING_CORNE 40. }
R.
Output:
setViewportVie
void Set the scroll pane's client.
w(Component)
11. JList<String> list = new JList<>(l1);
12. list.setBounds(100,100, 75,75);
13. f.add(list);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. }}

Output:

Java JList
The object of JList class represents a list of text
items. The list of text items can be set up so that the
user can choose either one item or multiple items. It
inherits JComponent class.

Commonly used Methods:


Methods Description

Void It is used to add a listener to


addListSelectionListener the list, to be notified each
(ListSelectionListener time a change to the Java JComboBox
listener) selection occurs.

It is used to return the The object of Choice class is used to show popup
int getSelectedIndex() menu of choices. Choice selected by user is shown
smallest selected cell index.
on the top of a menu. It inherits JComponent class.
It is used to return the data
model that holds a list of
ListModel getModel()
items displayed by the JList
Commonly used Methods:
component.
Methods Description
void It is used to create a read-
setListData(Object[] only ListModel from an void addItem(Object It is used to add an item to the
listData) array of objects. anObject) item list.

void removeItem(Object It is used to delete an item to


anObject) the item list.
Java JList Example
It is used to remove all the
1. import javax.swing.*; void removeAllItems()
items from the list.
2. public class ListExample
3. { void It is used to determine whether
4. ListExample(){ setEditable(boolean b) the JComboBox is editable.
5. JFrame f= new JFrame();
6. DefaultListModel<String> l1 = new Default void
ListModel<>(); It is used to add the
addActionListener(Acti
7. l1.addElement("Item1"); ActionListener.
onListener a)
8. l1.addElement("Item2");
9. l1.addElement("Item3");
10. l1.addElement("Item4");
void The object of JMenuItem class adds a simple labeled
It is used to add the
addItemListener(ItemLi menu item. The items used in a menu must belong to
ItemListener.
stener i) the JMenuItem or any of its subclass.

Java JComboBox Example


Java JMenuItem and JMenu
1. import javax.swing.*;
2. public class ComboBoxExample { Example
3. JFrame f;
4. ComboBoxExample(){ 1. import javax.swing.*;
5. f=new JFrame("ComboBox Example"); 2. class MenuExample
6. String country[]={"India","Aus","U.S.A","Eng 3. {
land","Newzealand"}; 4. JMenu menu, submenu;
7. JComboBox cb=new JComboBox(country); 5. JMenuItem i1, i2, i3, i4, i5;
8. cb.setBounds(50, 50,90,20); 6. MenuExample(){
9. f.add(cb); 7. JFrame f= new JFrame("Menu and MenuIt
10. f.setLayout(null); em Example");
11. f.setSize(400,500); 8. JMenuBar mb=new JMenuBar();
12. f.setVisible(true); 9. menu=new JMenu("Menu");
13. } 10. submenu=new JMenu("Sub Menu");
14. public static void main(String[] args) { 11. i1=new JMenuItem("Item 1");
15. new ComboBoxExample(); 12. i2=new JMenuItem("Item 2");
16. } 13. i3=new JMenuItem("Item 3");
17. } 14. i4=new JMenuItem("Item 4");
15. i5=new JMenuItem("Item 5");
Output: 16. menu.add(i1); menu.add(i2); menu.add(i3);

17. submenu.add(i4); submenu.add(i5);


18. menu.add(submenu);
19. mb.add(menu);
20. f.setJMenuBar(mb);
21. f.setSize(400,400);
22. f.setLayout(null);
23. f.setVisible(true);
24. }
25. public static void main(String args[])
26. {
27. new MenuExample();
28. }}

Output:

Java JMenuBar, JMenu and


JMenuItem
The JMenuBar class is used to display menubar on
the window or frame. It may have several menus.

The object of JMenu class is a pull down menu


component which is displayed from the menu bar. It
inherits the JMenuItem class.
Java JDialog
The JDialog control represents a top level window
with a border and a title used to take some form of
input from the user. It inherits the Dialog class.

Unlike JFrame, it doesn't have maximize and


minimize buttons.

Java JDialog Example


1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class DialogExample {
5. private static JDialog d;
6. DialogExample() {
7. JFrame f= new JFrame();
8. d = new JDialog(f , "Dialog Example", true)
;
9. d.setLayout( new FlowLayout() );
10. JButton b = new JButton ("OK");
11. b.addActionListener ( new ActionListener()

12. {
13. public void actionPerformed( ActionEven
te)
14. {
15. DialogExample.d.setVisible(false);
16. }
17. });
18. d.add( new JLabel ("Click button to continu
e."));
19. d.add(b);
20. d.setSize(300,300);
21. d.setVisible(true);
22. }
23. public static void main(String args[])
24. {
25. new DialogExample();
26. }
27. }

Output:

You might also like