Java Programming Coursefile
Java Programming Coursefile
Approved by AICTE, New Delhi, Acredited by NAAC, Permanently Afiliated to JNTUH, Hyderabad)
An Autonomous Institution
Aziznagar Gate, ChilkurBalaji Road,
Hyderabad 500075, Telangana, India
www.vjit.ac.in
Department of Information Technology
Course file
Regulations
Batch
019-&013
Academic year
900-0a)
Programn
Course name
:JAVA PRoGRMMIG
Year/ Sem
Course Code
: A3Gs
Pre-Requisites
Ppe-4D
Course Coordinator
:D. Tavauthi
Index
INDEX
S.NO.
ITEM DESCRIPTION
Course Information Sheet
2
Syllabus
3 Text Books, Reference Books, Web/Internet Resources
4 Time table
9 Course Schedule
12 Assignment Questions
13 Unit wise Question Bank
UNIT - II
UNIT III
Files:
Introduction to I/O Streams: Byte Streams, Character Streams. File 1/O.
Multi threading: Differences belween multi threading and multitasking, thread life cycle,
creating threads, thread
priorities, synchronizing inter thread
Java.uul package- Collection Interfaces: List,threads,
Map,
communicanon.
Set. The Collection classes
LinkedList, HashMap, TrecSet,
StringTokenizer, Date, Random,Scanne
UNIT - IV
AWT:
Classhierarchy, Component, Container, Panel, Window, Frame, GraphicS.
AWT controls:
Labels, Button, Serollbar, Text
Panes ScrollPane,
Components, Checkbox, CheckboxGroup, Choice, LIst,
Dialog and Menu Bar.
Event Handling:
Events, Event sources, Even classes, Event Listeners, Delegation event model, handling
mouse and keyboard cvents, Adapterclasses.
UNIT VV
Layout Manager:
Border, Grid, Flow, Card and Gridbag.
Applets:
Concepts of Applets, life cycle of an applet, creating applets, passing parameters
toapplets.
JDBC Connectivity:
JDBC Type 1 to 4 Drivers, connection establishment, Query Execution.
Text Books:
1. Java- the complete reference, Seventh edition, Herbert Schildt, Tata McGraw
Hill Reese,
2. Database Programming with JDBC & JAVA, Second Edition, George
O'Reilly Media.
Reference Books:
OXFORID Higher Education.
Programming in JAVA, Second Edition,
1.
Bruce Eckel
2. Thinking in Java Fourth Edition,
Y, Daniel Liang, Pearson Education.
3 Introduction to Java programming, Education.
with Java, updated edition, T. Budd, Pearson
4. Understanding OOP
Program Educational1
Objectives &
Program Outcomes
Vidya Jyothi Institute of Technology
(Afiliated to JNTUH)
AzimagarGate,C. B.Post. Hyderabad-500 075
(PEOs)
PEOL: Core Capabilities / Competence: Impart profound knowledge in humanities
and basic sciences along with core engineering concepts for practical understanding
and project development.
PEO2: Career Advancement: Enrich analytical and industry based technical skills
through ICT for accomplishing research, higher education and entrepreneurship
Progran Outeomes
PO
Engineering Knowledge: Apply knowledgc of
engineering specialization to the solution of complexmathematics, science, cngincering fundamentals and an
engincering problems.
PO2 P'roblem Analysis: ldentify, Fomulatc, review rescarch literaturc, and
feaching substantiated conclusions using first analyze complcx engineering probiems
SCIences. principles of mathematics, natural sciences and engineering
PO3
Design/Development of Solutions: Design solutions for complex
cngincering problems and design system
components or
processes that meet the specitlied necds with
safcty and the cultural, sociclal and appropriate consideration for the public health and
environmental considerations.
PO4 Conduct Investigations of Complex
problems: Usc rescarch-based knowledge and rescarch methods
including design of experiments,
analysis and interpretation of data and synthesis of the information to
valid conclusions. provide
PO5 Modern Tool Usage: Create, Select and
apply appropriate techniques, resources and modern engineering and
IT tools
including prediction and modeling to complex
engineering activities with an understanding of the
limitations.
PO12 Life-Long Learning: Recognize the need lor and have the
preparation and ability to
engage in
and life-long learning in the broadest context of technological
change. independent
Program Specific Outcomes
(PSOs)
Vidya Jyothi Institute of Technology
(Affiliated to JNTUH)
AziznagarGate,C.B.Post,Hyderabad-500 075
DEPARTMENT OF INFORMATION TECHNOLOGY
(PSOs)
PO1 PO2 PO3 P04 PO5 PO6 PO7 PO8 PO9 PO10 | PO11 PO12
CO1
CO2
3 3 3 2
CO3
3 2
3
C04
3 3 2
CO5
3 3 3
21 3
PSO1 PSO2
CO1
CO2
CO3
C04
CO5
Course File
outcomes
with Pos
Articulation matrix of Course
PO12
PO11
PO8 PO9 PO10
PO3 P04 PO5 PO6 PO7 2
PO1 PO2
1 3
2 2
cOI 3 3 3 3 I3 1
2
CO2 3 3 33 2 2
2 13
C03 3 3 33
C04 333 33 2 2 1 2
CO5 333 33 2 T3
3
CO1
CO2
3 3
CO3
3 3
CO4
3 3
CO5
Lecture Plan /Teaching Plan
VIDYA JYOTHI INSTITUTE OF TECHNOLOGY
(An Autonomous Institution)
L8
Concepts of classes, objects, constructors,
TI(Chapter 6) 19/04/2021 0/u
methods
L9
Access control, this keyword, garbage TI(Chapter 6) 20/04/2021 a3u
collection
L10
Overloading methods and constructors,
TI(Chapter 6) 23/04/202124 /u/
parameter passing, 26/04/2021
Recursion, nested and inner classes,
L11 TI Chapter 6)
Strings TI(Chapter8) 27/04/2021 9 /u ly
L12 Object Class
L18
Differences between TI(Chapter9) elsl l s l
interfaces
L19 Multiple inheritance through
interfaces TI(Chapter 9) 1lsu s Is
L20 Creating and Accessing a Package
TI(Chapter 9) 14 sly t
L21 Understanding CLASSPATH, import1ng TIChapter 9) 6 t15
packages
Exception handling
Unit II
Date:
Remarks:
Unit-III
Date
Remarks
Co-pllaA
Unit-IV
Date:
3y
Remarks:
Unit V
Date
Remarks:
Copuls
Page 16
Course File
Programming (R19)
-
Java
Unit wise Assignment
Questions
Blooms Taxonomy and Course
Levels of thinking
-
Outcomes)
concepts.
1
DIscuss the various characteristics of object oriented programming
(Level-2, CO-1)
conditional statements with an
2 EXplain about different loop control statements and
examples (Level-2, CO-1)
and with an
3 DIscuss about the features of constructors and constructor overloading
C0-5)
Write a program to develop calculator (Level-1,
Page 17
Course File
Java Programming (R19)
-
Unit-V
(Level-1) (C0-5)
rokus Pasod
fretettl AessModiHie modiFie decax
ate
members
methods
anddlda Jhe samtet,
the
when within
hem
aCess
we Can
as vom "subclasscs
l Proteotad metud
*class Anina
ietectd void dislayc)
am an animul"):
Systm out 7istkn("a
3
class Deqextends f e l
le
Pabic, Variab
fublhct esandr 4
Mblic Yoid
ublie
Void
display fab1 lic mehed f
s4stem Ou ritin (L am an aniva,")
3
IMain Jav
Pablic class main
rublbe vaviable
animaeacou-4 llaccesing
mebor.
onim d isplayc); latcessin Pablic
3 .
3
Oudpd
Qn imas
1 have 4 Jeys
anguhere
lic be aceMed
Can
fadknge P4
class *A
Void dsplag C)
aubage P2;
class k New
Y ob hew k)
od. dislag ()
OutR
COmple me er yon
Assignment()
Frame f
Label 11
=
Frame( "MY ASSIGNMENT");
new
Label 12
Label( "studentID: ")
=
new
new Label("password: ");
TextField t1 new TextField(26);
=
//t2.setEchoChar
Button b new
("*");
f.add(11)
Buttton("Login");
f.add(t1)
f.add(12)
f.add(t2)
f.add(b);
Label 14
List al=
new
Label("course enrol1l by student: ");
new List(7);
al.setBounds(600,550,50,5e);
a1.add("c");
al.add("C++");
a1.add("Python");
al.add("Java") ;
al.add("Machine learning");
al.add("Data Science");
a1.add("web devlopment");
f.add (14);
f.add(al);
Label 15 new
TextArea ta
Label("student Feedback: ");
new
=
TextArea(20, 10);
ta.setBounds (600, 600, 50, 50);
f. add (15):
f.add(ta);
f.setSize(400, 400) 5
f.setVisible (true)
f.setBackground(Color.gray);
f.setlayout (new FlowLayout ();
Page 2
Unit wise Question Bank
VIDYA JYOTHI INSTITUTE OF TECHNOLOGY
(An Autonomous Institution)
Department of Information Technology
B.Tech, II Sem (R19)
Java Programming- Question Bank
Faculty: P. Lakshmi Sony Phone no: 9908545005
UNIT-I
Short Answer Questions
UNIT-III
Short Answer Questions
1. Define stream.List the standard 10 streams
2. Differentiate InputStrean and OutputStream
3. Differentiate ByteStream and Character Stream
4. Write a program to demonstrate console 10 operations.
5. Write the syntax and an example for different forms of read() operation
6. Write the syntax and an example for different forms of write() operation
7. List the mandatory methods to implement threads
8. Differentiate process and a thread.
9. List and explain thread states.
10. What are the different ways to create a thread?
11. List the methods for inter-thread communication
12. What are the pre defined thread priorities?
13. How threads are synchronized?
14. Explain about the alive() and join) methods.
15. List the Thread class methods.
16. Differentiate Thread class and Runnable interface for creating threads.
17. Define Collection Class and its framework.
14. Differentiate MenuBar and Menultem write necessary syntax.
15. Define ScollPane. Write the syntax to create ScrollPane
16. Write the syntax to create Dialog box
17. Explain about Events, Event sources, Event classes
18. Differentiate Event Listeners and Event classes
19. List the methods of MouselListener interface
20. List the Methods of KeyListener interface
21. Explain ActionEvent Class
22. Define Adapter class with necessary syntax and an example
Long Answer Questions
UNIT- V
Short Answer Questions
.
Define interface. Multiple inheritance is supported through
1.a)
interfaces. justify.
b) Demonstrate multilevel inheritance with a program
OR
ii. Explain Exception Handling Mechanism 2
5
6.i)
Demonstrate creating a thread by Extending Thread class
3 4
[OR]
Explain Thread Priorities, write a program to set and get
ii) thread
priority of a
3 4
***VJIT(A)***
Etanch:T1
bjeckaa oomu
Nlax Ma s: o Maas
Tnskuce):D Sotoa
Pont-
1 D n e olsmolphsn
nbiaze
10 andl &DaRJS
an
i ) D e clate
intolize DR2D
M
lota25 dlau
Haos and
cteranbale
Laad& Tqocdá -
2r
blreshale
nie dynlax
od exonp k- Ir9
1 eino in herlone,
inhoidance M
debinitico coh an epony
-
A7
onded
ot jawa 33r
4 io 6plain he B A
B.ahne Slakeae.k
Slakeae.h a0.14
a0:14
9nd ohn
bsaak
dlrrun biele an endn pe
e Caskra
6pain M
debire bype
Cat hi 15
jolox
-
aovel
ConvISico
btonpe
pe
hilone
1s igpa kel
nkrtar in
nbikag Aulhiple
51.a) debini
ongl inbortate jyske
cebnt inkerlate-1
e-/
uathan eonny
kiu lhpe n herilane
6b> deonyhale mulkleel iohailant alth a hoplO
plain hanllirarMechaniS+n 5 1 1
htopho
b &kodiag30od clas 4M
-
dbonito ot toal4 -1
loccad clan ulh
on vxonp& ioqgon-39
le a hognen to e t a r
61i lain locnd qsuBi-ke,
o v 8 t h ob a-Heaad 4
-Iorad ouSutheg ly
3
Vidya Jyothi Institute of Technology
(A7iz
(Autonomous)
(Accrelted by NAAC & NIBA, Appraved By
A1CTE, Ne elb1, Permanenitly A
fillated ta &TUU, I1yderabad
Nagar,R Post, 11yderabnd, 504K175)
I,II,II & IV Ycar B.Tech Il Semester Ist
Mid xam
Branch:I1- IT
Sub: Java Programming Duration: 90Min
Date: Marks: 20
Course Outcomes: Session:
1
Understand O0P concepts to apply basic Java constructs.
.
Analyze different forms of inheritance and usage of
3.
Understand the different kinds of file Exception Handling
1/O,Multithreading in
Contrast different GUl layouts and design GUl applications complex programs, and usage of Container classes
4. Java
Dean Exminations
DIRECTOR
of Technology (Autonomous)
Vidya Jyothi Institute
Approved ByNAAC & NBA, A.l.CT.E, New Delhi, Permanently
Afiliated to JNTU, Hyderabad)
(Accredited by
(Aziz Nagar, C.B.Post, Hyderabad -500075)
DIRECTOR
Controller of Exminaticns
UNIT-I
OOP Concepts
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
Benefits of Inheritance
• One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent code
exists in two related classes, the hierarchy can usually be refactored to move the common
code up to a mutual superclass. This also tends to result in a better organization of code and
smaller, simpler compilation units.
• Inheritance can also make application code more flexible to change because classes that
inherit from a common superclass can be used interchangeably. If the return type of a
method is superclass
• Reusability - facility to use public methods of base class without rewriting the same.
• Extensibility - extending the base class logic as per business logic of the derived class.
The history of java starts from Green Team. Java team members (also known as Green
Team), initiated a revolutionary task to develop a language for digital devices such as set-top
boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was suited for internet
programming. Later, Java technology as incorporated by Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc.
There are given the major points that describes the history of java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set- top boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
Java Version History
There are many java versions that has been released. Current stable release of Java is Java SE 8.
Java Comments
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement. It can also be used to hide program code for specific time.
Syntax:
Output:
10
Syntax:
/*
This
is
multi line
comment
*/
Example:
Output:
10
The documentation comment is used to create documentation API. To create documentation API,
you need to use javadoc tool.
Syntax:
/**
Thi
s is
documentatio
n comment
*/
Example:
/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
public class Calculator {
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b){return a+b;}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b){return a-b;}
}
javac Calculator.java
javadoc Calculator.java
Now, there will be HTML files created for your Calculator class in the current directory. Open
the HTML files and see the explanation of Calculator class provided through documentation
comment.
Data types represent the different values to be stored in the variable. In java, there are two types of data
types:
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Output:20
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.
There are two types of data types in java: primitive and non-primitive.
Types of Variable
o local variable
o instance variable
o static variable
1) Local Variable
2) Instance Variable
A variable which is declared inside the class but outside the method, is called instance variable . It
is not declared as static.
3) Static variable
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
Constants in Java
A constant is a variable which cannot have its value changed after declaration. It uses the 'final'
keyword.
Syntax
modifier final dataType variableName = value; //global constant
Instance variables
Instance variables are those that are defined within a class itself and not in any method or
constructor of the class. They are known as instance variables because every instance of the class
(object) contains a copy of these variables. The scope of instance variables is determined by the
access specifier that is applied to these variables. We have already seen about it earlier. The
lifetime of these variables is the same as the lifetime of the object to which it belongs. Object
once created do not exist for ever. They are destroyed by the garbage collector of Java when there
are no more reference to that object. We shall see about Java's automatic garbage collector later
on.
Argument variables
These are the variables that are defined in the header oaf constructor or a method. The scope of
these variables is the method or constructor in which they are defined. The lifetime is limited to
the time for which the method keeps executing. Once the method finishes execution, these
variables are destroyed.
Local variables
A local variable is the one that is declared within a method or a constructor (not in the header).
The scope and lifetime are limited to the method itself.
One important distinction between these three types of variables is that access specifiers can be
applied to instance variables only and not to argument or local variables.
In addition to the local variables defined in a method, we also have variables that are defined in
bocks life an if block and an else block. The scope and is the same as that of the block itself.
Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in java which are given below:
o Unary Operator,
o Arithmetic Operator,
o shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Operators Hierarchy
Types of Expressions
While an expression frequently produces a result, it doesn't always. There are three types of
expressions in Java:
For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST)
etc. The java enum constants are static and final implicitly. It is available from JDK 1.5.
Java Enums can be thought of as classes that have fixed set of constants.
The control flow statements in Java allow you to run or skip blocks of code when special
conditions are met.
if (condition) {
// execute this code
}
1. Write a main method that runs your program. You can write this method anywhere. In this
example, I'll write my main method in a class called Main that has no other methods. For
example:
2. public class Main
3. {
4. public static void main(String[] args)
5. {
6. Game.play();
7. }}
8. Make sure your code is compiled, and that you have tested it thoroughly.
9. If you're using Windows, you will need to set your path to include Java, if you haven't
done so already. This is a delicate operation. Open Explorer, and look inside
C:\ProgramFiles\Java, and you should see some version of the JDK. Open this folder, and
then open the bin folder. Select the complete path from the top of the Explorer window, and
press Ctrl-C to copy it.
Next, find the "My Computer" icon (on your Start menu or desktop), right-click it, and select
properties. Click on the Advanced tab, and then click on the Environment variables button.
Look at the variables listed for all users, and click on the Path variable. Do not delete the
contents of this variable! Instead, edit the contents by moving the cursor to the right end,
entering a semicolon (;), and pressing Ctrl-V to paste the path you copied earlier. Then go
ahead and save your changes. (If you have any Cmd windows open, you will need to close
them.)
10. If you're using Windows, go to the Start menu and type "cmd" to run a program that
brings up a command prompt window. If you're using a Mac or Linux machine, run the
Terminal program to bring up a command prompt.
11. In Windows, type dir at the command prompt to list the contents of the current directory.
On a Mac or Linux machine, type ls to do this.
cd Desktop
cd ..
Every time you change to a new directory, list the contents of that directory to see where to go
next. Continue listing and changing directories until you reach the directory that contains
your .class files.
13. If you compiled your program using Java 1.6, but plan to run it on a Mac, you'll need to
recompile your code from the command line, by typing:
14. Now we'll create a single JAR file containing all of the files needed to run your program.
Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using
indexed variables.
Example:
JAVA PROGRAMMING Page 16
The following code snippets are examples of this syntax:
Creating Arrays:
You can create an array by using the new operator with the following syntax:
• It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:
Example:
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:
Following picture represents array myList. Here, myList holds ten double values and the indices
are from 0 to 9.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
The Java Console class is be used to get input from console. It provides methods to read texts and
passwords.
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console class is
introduced since 1.5.
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);
import java.io.Console;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n); } }
Constructors
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}}
Output: Bike is created
Output:
111 Karan
222 Aryan
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
Output:
111 Karan 0
222 Aryan 25
Java Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
oBy constructor
oBy assigning the values of one object into another
oBy clone() method of Object class
In this example, we are going to copy the values of one object into another using java
constructor.
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
Output:
111 Karan
111 Karan
Now you will learn how to create your own methods with or without return values, invoke a
method with or without parameters, and apply method abstraction in the program design.
Creating Method
Considering the following example to explain the syntax of a method −
Syntax
Here,
• a, b − formal parameters
Method definition consists of a method header and a method body. The same is shown in the
following syntax −
Syntax
• modifier − It defines the access type of the method and it is optional to use.
• nameOfMethod − This is the method name. The method signature consists of the method
JAVA PROGRAMMING Page 24
name and the parameter list.
• method body − The method body defines what the method does with the statements.
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it
is known as call by value. The changes being done in the called method, is not affected in the
calling method.
In Java, parameters are always passed by value. For example, following program prints
i = 10, j = 20.
// Test.java
class Test {
// swap() doesn't swap i and j
public static void swap(Integer i, Integer j) {
Integer temp = new Integer(i);
i = j;
j = temp;
}
public static void main(String[] args) {
Integer i = new Integer(10);
Integer j = new Integer(20);
swap(i, j);
System.out.println("i = " + i + ", j = " + j);
JAVA PROGRAMMING Page 26
}
}
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the class
than instance of the class.
o The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of students etc.
o The static variable gets memory only once in class area at the time of class loading.
s1.display();
s2.display();
}}
Output:111 Karan ITS
222 Aryan ITS
If you apply static keyword with any method, it is known as static method.
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
Access Control
There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor
or class.
//save by B.java
package mypack;
import pack.*;
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't
be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}}
Output:Hello
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
111 ankit 5000
112 sumit 6000
Constructor is used to initialize the state of an object. Method is used to expose behaviour
of an object.
Constructor must not have return type. Method must have return type.
The java compiler provides a default constructor if you Method is not provided by compiler in
don't have any constructor. any case.
Constructor name must be same as the class name. Method name may or may not be
JAVA PROGRAMMING Page 33
same as class name.
There are many differences between constructors and methods. They are given belo
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
Output:
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
Output:
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
gc() method
string is basically an object that represents sequence of char values. An array of characters works
same as java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
ssame as:
1. String s="javatpoint";
2. Java String class provides a lot of methods to perform operations on string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
3. The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.
CharSequence Interface
The java String is immutable i.e. it cannot be changed. Whenever we change any
string, a new instance is created. For mutable string, you can use StringBuffer and StringBuilder
classes.
There are two ways to create String object:
1. By string literal
2. By new keyword
String Literal
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in
the pool, a new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object
in heap (non pool).
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
Let's try to understand the immutability concept by the example given below:
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}}
Output:Sachin
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
} } Output:Sachin Tendulkar
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object. Inheritance represents the IS-A relationship, also known as parent-
child relationship.
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}}
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
Output:
weeping...
barking...
eating...
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
A subclass includes all of the members of its super class but it cannot access those members of
the super class that have been declared as private. Attempt to access a private variable would
cause compilation error as it causes access violation. The variables declared as private, is only
accessible by other members of its own class. Subclass have no access to it.
The super keyword in java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
Output:
black
white
Final Keyword in Java
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only.
The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:
1. Object obj=getObject();//we don't know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
1. class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}}
Output:
SBI Rate of Interest: 8
A class that is declared with abstract keyword is known as abstract class in java. It can have
abstract and non-abstract methods (method with body). It needs to be extended and its method
implemented. It cannot be instantiated.
abstract method
1. abstract void printStatus();//no body and abstract
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction. There can be only abstract methods
in the java interface not method body. It is used to achieve abstraction and multiple inheritance in
Java.
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
interface Printable{
JAVA PROGRAMMING Page 44
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}}
Output:Hello
Welcome
Abstract class Interface
1) Abstract class can have abstract Interface can have only abstract methods. Since
and non-abstract methods. Java 8, it can have default and static
methods also.
2) Abstract class doesn't support Interface supports multiple inheritance.
multiple inheritance.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to The interface keyword is used to declare
declare abstract class. interface.
6) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Java inner class or nested class is a class which is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
Inner class is a part of nested class. Non-static nested classes are known as inner classes.
There are two types of nested classes non-static and static nested classes.The non-static nested
classes are also known as inner classes.
Java Package
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}}
If you are not using any IDE, you need to follow the syntax given below:
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
JAVA PROGRAMMING Page 47
Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception: The classes that extend Throwable class except RuntimeException
and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked
exceptions are checked at compile-time.
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw exception
3. }finally{}
Java catch block is used to handle the Exception. It must be used after the try block only.
As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
Output:task1 completed
rest of the code...
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
JAVA PROGRAMMING Page 51
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
1. }
Java finally block
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
1. throw exception;
In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
Output:
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
JAVA PROGRAMMING Page 53
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow..."); } }
Output:
exception handled
normal flow...
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly used
examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of
these two classes to copy an input file into an output file −
Example
FileInputStream in = null;
try {
in = new FileInputStream("input.txt");
int c;
}finally {
if (in != null) {
in.close();
if (out != null) {
out.close();
}} }}
As a next step, compile the above program and execute it, which will result in creating output.txt
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java
file and do the following −
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode. Though there
are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input
file (having unicode characters) into an output file −
Example
try {
in = new FileReader("input.txt");
int c;
out.write(c);}
}finally {
if (in != null) {
in.close();}
if (out != null) {
out.close();
}} }}
As a next step, compile the above program and execute it, which will result in creating output.txt
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java
file and do the following −
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where the user's program can
take input from a keyboard and then produce an output on the computer screen. Java provides the
following three standard streams −
• Standard Input − This is used to feed the data to user's program and usually a keyboard
is used as standard input stream and represented asSystem.in.
• Standard Error − This is used to output the error data produced by the user's program
and usually a computer screen is used for standard error stream and represented
as System.err.
Following is a simple program, which creates InputStreamReader to read standard input stream
until the user types a "
Example
import java.io.*;
try {
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
} } }}
This program continues to read and output the same character until we press 'q' −
FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the
file −
• ByteArrayInputStream
• DataInputStream
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the
file −
Example
import java.io.*;
try {
JAVA PROGRAMMING Page 63
byte bWrite [] = {11,21,3,40,5};
os.close();
is.close();
} catch (IOException e) {
System.out.print("Exception");
} }}
Java.io.RandomAccessFile Class
The Java.io.RandomAccessFile class file behaves like a large array of bytes stored in the file
system.Instances of this class support both reading and writing to a random access file.
Class declaration
Following is the declaration for Java.io.RandomAccessFile class −
1
RandomAccessFile(File file, String mode)
This creates a random access file stream to read from, and optionally to write to, the file
specified by the File argument.
This creates a random access file stream to read from, and optionally to write to, a file with
the specified name.
Methodsinherited
This class inherits methods from the following classes −
• Java.io.Object
defines an abstract file name for the geeks file in directory /usr/local/bin. This is an absolute
abstract file name.
Program to check if a file or directory physically exist or not.
// In this program, we accepts a file or directory name from
// command line arguments. Then the program will check if
// that file or directory physically exist or not and
// it displays the property of that file or directory.
*import java.io.File;
Output:
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt
Parent:null
Exists :true
Is writeable:true
Is readabletrue
Is a directory:false
Connceting to DB
Multithreading
Multithreading in java is a process of executing multiple threads simultaneously.
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
How to create thread
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
oThread()
oThread(String name)
oThread(Runnable r)
oThread(Runnable r,String name)
Commonly used methods of Thread class:
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
oA new thread starts(with new callstack).
oThe thread moves from New state to the Runnable state.
oWhen the thread gets a chance to execute, its target run() method will run.
Java Thread Example by extending Thread class
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}
start();
}}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such way, we can
suspend, resume or interrupt group of threads by a single method call.
ThreadGroup(String name)
ThreadGroup(ThreadGroup parent, String name)
Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is the
class that implements Runnable interface and "one", "two" and "three" are the thread names.
1. Thread.currentThread().getThreadGroup().interrupt();
The java.net package of the J2SE APIs contains a collection of classes and interfaces that
provide the low-level communication details, allowing you to write programs that focus on
solving the problem at hand.
The java.net package provides support for the two common network protocols −
• TCP − TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.
• UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows
for packets of data to be transmitted between applications.
• Socket Programming − This is the most widely used concept in Networking and it has
been explained in very detail.
java.text
The java.text package is necessary for every java developer to master because it has a lot of
classes that is helpful in formatting such as dates, numbers, and messages.
java.text Classes
[table]
Class|Description
SimpleDateFormat|is a concrete class that helps in formatting and parsing of dates.
[/table]
Collection Framework in Java
Java Collection simply means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
✓ is optional.
Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:
2. Algorithm
List Interface is the sub interface of Collection. It contains index-based methods to insert and delete
elements. It is a factory of ListIterator interface.
Method Description
void add(int index, E element) It is used to insert the specified element at the
specified position in a list.
boolean add(E e) It is used to append the specified element at the end
of a list.
boolean addAll(Collection<? extends E> c) It is used to append all of the elements in the
specified collection to the end of a list.
boolean addAll(int index, Collection<? It is used to append all the elements in the specified
extends E> c) collection, starting at the specified position of the
list.
void clear() It is used to remove all of the elements from this
list.
1. import java.util.*;
2. public class ListExample{
3. public static void main(String args[]){
4. List<String> al=new ArrayList<String>();
5. al.add("Amit");
6. al.add("Vijay");
7. al.add("Kumar");
8. al.add(1,"Sachin");
9. System.out.println("An element at 2nd position: "+al.get(2));
10. for(String s:al){
11. System.out.println(s);
12. }
13. }
14. }
Output:
Method Description
void add(E e) This method inserts the specified element into the list.
boolean hasNext() This method returns true if the list iterator has more elements while
traversing the list in the forward direction.
E next() This method returns the next element in the list and advances the
cursor position.
int nextIndex() This method returns the index of the element that would be returned
by a subsequent call to next()
boolean hasPrevious() This method returns true if this list iterator has more elements while
traversing the list in the reverse direction.
E previous() This method returns the previous element in the list and moves the
cursor position backward.
E previousIndex() This method returns the index of the element that would be returned
by a subsequent call to previous().
void remove() This method removes the last element from the list that was returned
by next() or previous() methods
void set(E e) This method replaces the last element returned by next() or
previous() methods with the specified element.
1. import java.util.*;
2. public class ListIteratorExample1{
3. public static void main(String args[]){
4. List<String> al=new ArrayList<String>();
5. al.add("Amit");
6. al.add("Vijay");
7. al.add("Kumar");
8. al.add(1,"Sachin");
9. ListIterator<String> itr=al.listIterator();
10. System.out.println("Traversing elements in forward direction");
11. while(itr.hasNext())
12. {
13.
14. System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());
15. }
16. System.out.println("Traversing elements in backward direction");
17. while(itr.hasPrevious())
18. {
19.
20. System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());
21. }
22. }
23. }
Output:
Traversing elements in forward
direction index:0 value:Amit
index:1
value:Sachin
index:2
value:Vijay
index:3
value:Kumar
Traversing elements in backward
direction index:3 value:Kumar
index:2 value:Vijay
index:1
Example value:Sachin
of ListIterator Interface: Book
index:0 value:Amit
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class ListIteratorExample2 {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new ArrayList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw
Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
29. }
30. }
31. }
Output:
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList
class and implements List interface.
✓ Java ArrayList allows random access because array works at the index basis.
import java.util.*;
class TestCollection1
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Ouput: Ravi
Vijay Ravi
Ajay
Java Map Interface
A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known
as an entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a key.
There are two interfaces for implementing Map in java: Map and SortedMap, and three classes:
HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given below:
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or value.
A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.
Class Description
HashMap HashMap is the implementation of Map, but it doesn't maintain any
order.
LinkedHashMap LinkedHashMap is the implementation of Map. It inherits HashMap
class. It maintains insertion order.
TreeMap TreeMap is the implementation of Map and SortedMap. It maintains
ascending order.
Output:
1 Amit
2 Jai
5 Rahul
6 Amit
Output:
102 Rahul
100 Amit
101 Vijay
Java HashMap class
Java HashMap class implements the map interface by using a hash table. It inherits AbstractMap
class and implements Map interface.
Points to remember
o Java HashMap class contains values based on the key.
o Java HashMap class contains only unique keys.
o Java HashMap class may have one null key and multiple null values.
o Java HashMap class is non synchronized.
o Java HashMap class maintains no order.
o The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
As shown in the above figure, HashMap class extends AbstractMap class and implements Map
HashMap(int capacity, float It is used to initialize both the capacity and load factor
loadFactor) of the hash map by using its arguments.
void putAll(Map map) It is used to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value with the specified key
in the map only if it is not already specified.
boolean remove(Object key, Object It removes the specified values with the associated
value) specified keys from the map.
V compute(K key, BiFunction<? super It is used to compute a mapping for the specified
K,? super V,? extends V> key and its current mapped value (or null if there is
remappingFunction) no current mapping).
V computeIfAbsent(K key, Function<? It is used to compute its value using the given
super K,? extends V> mappingFunction) mapping function, if the specified key is not already
associated with a value (or is mapped to null), and
enters it into this map unless null.
V computeIfPresent(K key, It is used to compute a new mapping given the key
BiFunction<? super K,? super V,? and its current mapped value if the value for the
extends V> remappingFunction) specified key is present and non-null.
boolean containsValue(Object value) This method returns true if some value equal to the
value exists within the map, else return false.
boolean containsKey(Object key) This method returns true if some key equal to the
key exists within the map, else return false.
void forEach(BiConsumer<? super K,? It performs the given action for each entry in the
super V> action) map until all entries have been processed or the
action throws an exception.
V get(Object key) This method returns the object that contains the
value associated with the key.
V merge(K key, V value, BiFunction<? If the specified key is not already associated with a
super V,? super V,? extends V> value or is associated with null, associates it with
remappingFunction) the given non-null value.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V It replaces the old value with the new value for a
newValue) specified key.
void replaceAll(BiFunction<? super K,? It replaces each entry's value with the result of
super V,? extends V> function) invoking the given function on that entry until all
entries have been processed or the function throws
an exception.
import java.util.*;
class HashMap1{
public static void main(String args[]){
HashMap<Integer,String> hm=new
HashMap<Integer,String>(); System.out.println("Initial list
of elements: "+hm); hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
hm.putIfAbsent(103, "Gaurav");
System.out.println("After invoking putIfAbsent() method ");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(104,"Ravi");
map.putAll(hm);
System.out.println("After invoking putAll() method ");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
100 Amit
101 Vijay
102 Rahul
103 Gaurav
104 Ravi
Java HashMap example to remove() elements
import java.util.*;
public class HashMap2
{
public static void main(String args[])
{
HashMap<Integer,String> map=new
HashMap<Integer,String>(); map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
map.put(103, "Gaurav");
System.out.println("Initial list of elements:
"+map);
//key-based removal
map.remove(100);
System.out.println("Updated list of elements: "+map);
//value-based removal
map.remove(101);
System.out.println("Updated list of elements: "+map);
//key-value pair based removal
map.remove(102, "Rahul");
System.out.println("Updated list of elements: "+map);
}
}
Output:
import java.util.*;
class HashMap3{
public static void main(String args[]){
HashMap<Integer,String> hm=new
HashMap<Integer,String>(); hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
System.out.println("Initial list of
elements:"); for(Map.Entry
m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated list of elements:");
hm.replace(102, "Gaurav");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated list of
elements:"); hm.replace(101, "Vijay",
"Ravi"); for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
System.out.println("Updated list of elements:");
hm.replaceAll((k,v) -> "Ajay");
for(Map.Entry m:hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Initial list of elements:
100 Amit
101 Vijay
102 Rahul
Updated list of elements:
100 Amit
101 Vijay
102 Gaurav
Updated list of elements:
100 Amit
101 Ravi
102 Gaurav
Updated list of elements:
100 Ajay
101 Ajay
102 Ajay
HashSet contains only values whereas HashMap contains an entry(key and value).
Java TreeMap class is a red-black tree based implementation. It provides an efficient means of
storing key-value pairs in sorted order.
o Java TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
o Java TreeMap contains only unique elements.
o Java TreeMap cannot have a null key but can have multiple null values.
o Java TreeMap is non synchronized.
o Java TreeMap maintains ascending order.
TreeMap(Comparator<? super K> It is used to construct an empty tree-based map that will
comparator) be sorted using the comparator comp.
TreeMap(Map<? extends K,? It is used to initialize a treemap with the entries from
extends V> m) m, which will be sorted using the natural order of the
keys.
TreeMap(SortedMap<K,? extends It is used to initialize a treemap with the entries
V> m) from the SortedMap sm, which will be sorted in
the same order as sm.
Map.Entry<K,V> ceilingEntry(K key) It returns the key-value pair having the least
key, greater than or equal to the specified
key, or null if there is no such key.
SortedMap<K,V> headMap(K toKey) It returns the key-value pairs whose keys are
strictly less than toKey.
NavigableMap<K,V> headMap(K toKey, It returns the key-value pairs whose keys are
boolean inclusive) less than (or equal to if inclusive is true)
toKey.
Map.Entry<K,V> higherEntry(K key) It returns the least key strictly greater than the
given key, or null if there is no such key.
K lowerKey(K key) It returns the greatest key strictly less than the
given key, or null if there is no such key.
V put(K key, V value) It inserts the specified value with the specified
key in the map.
void putAll(Map<? extends K,? extends V> It is used to copy all the key-value pair from
map) one map to another map.
V replace(K key, V value) It replaces the specified value for a specified
key.
boolean replace(K key, V oldValue, V It replaces the old value with the new value
newValue) for a specified key.
void replaceAll(BiFunction<? super K,? It replaces each entry's value with the result of
super V,? extends V> function) invoking the given function on that entry until
all entries have been processed or the function
throws an exception.
boolean containsValue(Object value) It returns true if the map maps one or more
keys to the specified value.
Output:
Before invoking remove() method
100 Amit
101 Vijay
102 Ravi
103 Rahul
After invoking remove() method
100 Amit
101 Vijay
103 Rahul
1) HashMap can contain one null key. TreeMap cannot contain any null key.
//Traversing map
for(Map.Entry<Integer, Book> entry:map.entrySet()){
int key=entry.getKey(); Book
b=entry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+""+b.q uantity);
}
}
}
Output:
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6
Set in Java
• Set is an interface which extends Collection. It is an unordered collection of objects in which
duplicate values cannot be stored.
• Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet (sorted representation).
• Set has various methods to add, remove clear, size, etc to enhance the usage of this
interface filter_none
edit play_arrow
brightness_4
// Java code for adding elements in Set
import java.util.*;
public class Set_example
{
public static void main(String[] args)
{
// Set deonstration using HashSet
Set<String> hash_Set = new
HashSet<String>(); hash_Set.add("Geeks");
hash_Set.add("For");
hash_Set.add("Geeks");
hash_Set.add("Example"
); hash_Set.add("Set");
System.out.print("Set output without the duplicates");
System.out.println(hash_Set);
Output:
Set output without the duplicates[Set, Example, Geeks, for]
Sorted Set after passing into TreeSet[Example, For, Geeks, Set]
TreeSet in Java
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a
Tree for storage. The ordering of the elements is maintained by a set using their natural ordering
whether or not an explicit comparator is provided. This must be consistent with equals if it is to
correctly implement the Set interface. It can also be ordered by a Comparator provided at set
creation time, depending on which constructor is used. The TreeSet implements a NavigableSet
interface by inheriting AbstractSet class.
Few important features of TreeSet are as follows:
1. TreeSet implements the SortedSet interface so duplicate values are not allowed.
2. Objects in a TreeSet are stored in a sorted and ascending order.
3. TreeSet does not preserve the insertion order of elements but elements are sorted by keys.
4. TreeSet does not allow to insert Heterogeneous objects. It will throw classCastException at
Runtime if trying to add hetrogeneous objects.
5. TreeSet serves as an excellent choice for storing large amounts of sorted information
which are supposed to be accessed quickly because of its faster access and retrieval
time.
6. TreeSet is basically implementation of a self-balancing binary search tree like Red-Black
Tree. Therefore operations like add, remove and search take O(Log n) time. And operations
like printing n elements in sorted order takes O(n) time.
Constructors of TreeSet class:
1. TreeSet t = new TreeSet();
This will create empty TreeSet object in which elements will get stored in default natural
sorting order.
2. TreeSet t = new TreeSet(Comparator comp);
This constructor is used when external specification of sorting order of elements is needed.
3. TreeSet t = new TreeSet(Collection col);
This constructor is used when any conversion is needed from any Collection object to
TreeSet object.
4. TreeSet t = new TreeSet(SortedSet s);
This constructor is used to convert SortedSet object to TreeSet Object.
Synchronized TreeSet:
The implementation in a TreeSet is not synchronized in a sense that if multiple threads access a tree
set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.
This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If
no such object exists, the set should be “wrapped” using the Collections.synchronizedSortedSet
method. This is best done at creation time, to prevent accidental unsynchronized access to the set:
class TreeSetDemo {
public static void main(String[] args)
{
TreeSet<String> ts1 = new TreeSet<String>();
.
NOTE:
1. An object is said to be comparable if and only if the corresponding class implements
Comparable interface.
2. String class and all Wrapper classes already implements Comparable interface but
StringBuffer class doesn’t implements Comparable interface.Hence we got
ClassCastException in the above example.
3. For an empty tree-set, when trying to insert null as first value, one will get NPE from JDK
7.From
1.7 onwards null is not at all accepted by TreeSet. However upto JDK 6, null will be
accepted as first value, but any if insertion of any more values in the TreeSet, will also
throw NullPointerException.
Hence it was considered as bug and thus removed in JDK 7.
Methods of TreeSet class:
TreeSet implements SortedSet so it has availability of all methods in Collection, Set and SortedSet
interfaces. Following are the methods in Treeset interface.
1. void add(Object o): This method will add specified element according to some sorting
order in TreeSet. Duplicate entires will not get added.
2. boolean addAll(Collection c): This method will add all elements of specified Collection
to the set. Elements in Collection should be homogeneous otherwise ClassCastException
will be thrown. Duplicate Entries of Collection will not be added to TreeSet.
3. void clear(): This method will remove all the elements.
4. boolean contains(Object o): This method will return true if given element is present in
TreeSet else it will return false.
5. Object first(): This method will return first element in TreeSet if TreeSet is not null
else it will throw NoSuchElementException.
6. Object last(): This method will return last element in TreeSet if TreeSet is not null else it
will throw NoSuchElementException.
7. SortedSet headSet(Object toElement): This method will return elements of TreeSet which
are less than the specified element.
8. SortedSet tailSet(Object fromElement): This method will return elements of TreeSet
which are greater than or equal to the specified element.
9. SortedSet subSet(Object fromElement, Object toElement): This method will return elements
ranging from fromElement to toElement. fromElement is inclusive and toElement is
exclusive.
10. boolean isEmpty(): This method is used to return true if this set contains no elements or
is empty and false for the opposite case.
11. Object clone(): The method is used to return a shallow copy of the set, which is just a
simple copied set.
12. int size(): This method is used to return the size of the set or the number of elements
present in the set.
13. boolean remove(Object o): This method is used to return a specific element from the set.
14. Iterator iterator(): Returns an iterator for iterating over the elements of the set.
15. Comparator comparator(): This method will return Comparator used to sort elements in
TreeSet or it will return null if default natural sorting order is used.
16. ceiling(E e): This method returns the least element in this set greater than or equal to
the given element, or null if there is no such element.
17. descendingIterator(): This method returns an iterator over the elements in this set in
descending order.
18. descendingSet(): This method returns a reverse order view of the elements contained in this
set.
19. floor(E e): This method returns the greatest element in this set less than or equal to
the given element, or null if there is no such element.
20. higher(E e): This method returns the least element in this set strictly greater than the given
element, or null if there is no such element.
21. lower(E e): This method returns the greatest element in this set strictly less than the given
element, or null if there is no such element.
22. pollFirst(): This method retrieves and removes the first (lowest) element, or returns null if
this set is empty.
23. pollLast(): This method retrieves and removes the last (highest) element, or returns null if
this set is empty.
24. spliterator(): This method creates a late-binding and fail-fast Spliterator over the
elements in this set.
Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data
structure. It inherits the AbstractList class and implements List and Deque interfaces.
As shown in the above diagram, Java LinkedList class extends AbstractSequentialList class and
implements List and Deque interfaces.
In the case of a doubly linked list, we can add or remove elements from both sides.
LinkedList class declaration
void add(int index, E element) It is used to insert the specified element at the
specified position index in a list.
LinkedList<String> al=new
LinkedList<String>(); al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
import java.util.*;
public class LinkedList2{
public static void main(String args[]){
LinkedList<String> ll=new LinkedList<String>();
System.out.println("Initial list of elements:
"+ll); ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
System.out.println("After invoking add(E e) method: "+ll);
//Adding an element at the specific position
ll.add(1, "Gaurav");
System.out.println("After invoking add(int index, E element) method: "+ll);
LinkedList<String> ll2=new LinkedList<String>();
ll2.add("Sonoo");
ll2.add("Hanumat");
//Adding second list elements to the first list
ll.addAll(ll2);
System.out.println("After invoking addAll(Collection<? extends E> c) method: "+ll);
LinkedList<String> ll3=new LinkedList<String>();
ll3.add("John");
ll3.add("Rahul");
//Adding second list elements to the first list at specific position
ll.addAll(1, ll3);
System.out.println("After invoking addAll(int index, Collection<? extends E> c) method:
"+ll);
//Adding an element at the first position
ll.addFirst("Lokesh");
System.out.println("After invoking addFirst(E e) method: "+ll);
//Adding an element at the last position
ll.addLast("Harsh");
System.out.println("After invoking addLast(E e) method: "+ll);
}
}
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo,
Hanumat] After invoking addLast(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]
import java.util.*;
public class LinkedList3 {
}
}
Output: Ajay
Vijay
Ravi
Let's see the simple example of StringTokenizer class that tokenizes a string "my name is khan"
on the basis of whitespace.
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
java.util.Random
▪ For using this class to generate random numbers, we have to first create an instance of this
class and then invoke methods such as nextInt(), nextDouble(), nextLong() etc using that
instance.
▪ We can generate random numbers of types integers, float, double, long, booleans using this
class.
▪ We can pass arguments to the methods for placing an upper bound on the range of the
numbers to be generated. For example, nextInt(6) will generate numbers in the range 0 to 5
both inclusive.
// A Java program to demonstrate random number generation
// using java.util.Random;
import java.util.Random;
There are various ways to read input from the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive types using regular
expression.
Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
Method Description
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and returns the value
as a string.
Let's see the simple example of the Java Scanner class which reads the int, string and double
value as an input:
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
} } Output:
Enter your rollno
111
Enter your name
Ratan
Enter
450000
Rollno:111 name:Ratan fee:450000
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. It
inherits Object class and implements the Comparable interface.
import java.util.Calendar;
public class CalendarExample1 {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("The current date is : " + calendar.getTime());
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}}
Output:
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in
java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components
like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Useful Methods of Component class
Method Description
public void setSize(int width,int sets the size (width and height) of the
height) component.
public void setLayout(LayoutManager defines the layout manager for the component.
m)
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.
1. import java.awt.*;
2. class First extends Frame{
3. First(){
4. Button b=new Button("click me");
5. b.setBounds(30,100,80,30);// setting button position
6. add(b);//adding button into frame
7. setSize(300,300);//frame size 300 width and 300 height
8. setLayout(null);//no layout manager
9. setVisible(true);//now frame will be visible, by default not visible
10. }
11. public static void main(String args[]){
12. First f=new First();
13. } }
The setBounds(int x axis, int yaxis, int width, int height) method is used in the above example that
sets the position of the awt button.
Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are
showing Button component on the Frame.
1. import java.awt.*;
2. class First2{
3. First2(){
4. Frame f=new Frame();
5. Button b=new Button("click me");
6. b.setBounds(30,50,80,30);
7. f.add(b);
8. f.setSize(300,300);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. public static void main(String args[]){
13. First2 f=new First2();
14. }}
AWT Controls:
AWT Label:
The object of Label class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly.
1. import java.awt.*;
2. class LabelExample{
5. Label l1,l2;
7. l1.setBounds(50,100, 100,30);
9. l2.setBounds(50,150, 100,30);
11. f.setSize(400,400);
12. f.setLayout(null);
13. f.setVisible(true);
14. }
15. }
Output:
Java AWT Button
The button class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed.
1. import java.awt.*;
6. b.setBounds(50,100,80,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. }
Output:
Java AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is
a GUI component allows us to see invisible number of rows and columns.
1. import java.awt.*;
2. class ScrollbarExample{
3. ScrollbarExample(){
4. Frame f= new Frame("Scrollbar Example");
5. Scrollbar s=new Scrollbar();
6. s.setBounds(100,100, 50,100);
7. f.add(s);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. public static void main(String args[]){
13. new ScrollbarExample();
14. }
15. }
Output:
Text Components:
The object of a TextField class is a text component that allows the editing of a single line text. It
inherits TextComponent class.
1. import java.awt.*;
2. class TextFieldExample{
5. TextField t1,t2;
7. t1.setBounds(50,100, 200,30);
9. t2.setBounds(50,150, 200,30);
11. f.setSize(400,400);
12. f.setLayout(null);
13. f.setVisible(true);
14. }
15. }
Output:
The object of a TextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits TextComponent class.
1. import java.awt.*;
3. {
4. TextAreaExample(){
area.setBounds(10,30, 300,300);
8. f.add(area);
9. f.setSize(400,400);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
14. {
16. }
17. }
Output:
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
1. import java.awt.*;
3. {
4. CheckboxExample(){
5. Frame f= new Frame("Checkbox Example");
7. checkbox1.setBounds(100,100, 50,50);
9. checkbox2.setBounds(100,150, 50,50);
10. f.add(checkbox1);
11. f.add(checkbox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
17. {
19. }
20. }
Output:
Java AWT CheckboxGroup
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only
one check box button is allowed to be in "on" state and remaining check box button in "off" state.
It inherits the object class.
Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special control for
creating radio buttons in AWT.
1. import java.awt.*;
3. {
4. CheckboxGroupExample(){
8. checkBox1.setBounds(100,100, 50,50);
11. f.add(checkBox1);
12. f.add(checkBox2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
20. }
21. }
Output:
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits Component class.
1. import java.awt.*;
3. {
4. ChoiceExample(){
7. c.setBounds(100,100, 75,75);
8. c.add("Item 1");
9. c.add("Item 2");
10. c.add("Item 3");
13. f.add(c);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
19. {
21. }
22. }
Output:
The object of List class represents a list of text items. By the help of list, user can choose either
one item or multiple items. It inherits Component class.
1. import java.awt.*;
3. {
4. ListExample(){
7. l1.setBounds(100,100, 75,75);
8. l1.add("Item 1");
9. l1.add("Item 2");
13. f.add(l1);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
19. {
21. }
22. }
Output:
Java AWT Dialog
The Dialog control represents a top level window with a border and a title used to take some form
of input from the user. It inherits the Window class.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but
Dialog doesn't have.
1. import java.awt.*;
2. import java.awt.event.*;
3. public class DialogExample {
4. private static Dialog d;
5. DialogExample() {
6. Frame f= new Frame();
7. d = new Dialog(f , "Dialog Example", true);
8. d.setLayout( new FlowLayout() );
9. Button b = new Button ("OK");
10. b.addActionListener ( new ActionListener()
11. {
12. public void actionPerformed( ActionEvent e )
13. {
14. DialogExample.d.setVisible(false);
15. }
16. });
17. d.add( new Label ("Click button to continue."));
18. d.add(b);
19. d.setSize(300,300);
20. d.setVisible(true);
21. }
22. public static void main(String args[])
23. {
24. new DialogExample();
25. }
26. }
Output:
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu
must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the menu bar. It
inherits the MenuItem class.
1. import java.awt.*;
2. class MenuExample
3. {
4. MenuExample(){
5. Frame f= new Frame("Menu and MenuItem Example");
6. MenuBar mb=new MenuBar();
7. Menu menu=new Menu("Menu");
8. Menu submenu=new Menu("Sub Menu");
9. MenuItem i1=new MenuItem("Item 1");
10. MenuItem i2=new MenuItem("Item 2");
11. MenuItem i3=new MenuItem("Item 3");
12. MenuItem i4=new MenuItem("Item 4");
13. MenuItem i5=new MenuItem("Item 5");
14. menu.add(i1);
15. menu.add(i2);
16. menu.add(i3);
17. submenu.add(i4);
18. submenu.add(i5);
19. menu.add(submenu);
20. mb.add(menu);
21. f.setMenuBar(mb);
22. f.setSize(400,400);
23. f.setLayout(null);
24. f.setVisible(true);
25. }
26. public static void main(String args[])
27. {
28. new MenuExample();
29. }
30. }
Output:
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Registration Methods
For registering the component with the Listener, many classes provide the registration methods.
For example:
o Button
o MenuItem
o TextField
o TextArea
o Checkbox
o Choice
o List
1. import java.awt.*;
2. import java.awt.event.*;
4. TextField tf;
5. AEvent()
6. {
7. //create components
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
11. b.setBounds(100,120,80,30);
12.
15.
17. add(b);add(tf);
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21. }
23. tf.setText("Welcome");
24. }
27. }
28. }
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above
example that sets the position of the component it may be button, textfield etc.
Output:
The Java MouseListener is notified whenever you change the state of mouse. It is notified against
MouseEvent. The MouseListener interface is found in java.awt.event package. It has five methods.
Java
MouseListener
Example 1
1. import java.awt.*;
2. import java.awt.event.*;
6. addMouseListener(this);
7.
8. l=new Label();
9. l.setBounds(20,50,100,20);
10. add(l);
11. setSize(300,300);
12. setLayout(null);
13. setVisible(true);
14. }
17. }
20. }
23. }
26. }
29. }
30. public static void main(String[] args) {
32. }
33. }
Output:
Java MouseListener
Example 2
1. import java.awt.*;
2. import java.awt.event.*;
4. MouseListenerExample2(){
5. addMouseListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),30,30);
15. }
20.
23. }
24. }
Output:
The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in java.awt.event package. It has three methods.
Java
KeyListener
Example 1
1. import java.awt.*;
2. import java.awt.event.*;
4. Label l;
5. TextArea area;
6. KeyListenerExample(){
7.
8. l=new Label();
9. l.setBounds(20,50,100,20);
12. area.addKeyListener(this);
13.
14. add(l);add(area);
15. setSize(400,400);
16. setLayout(null);
17. setVisible(true);
18. }
21. }
22. public void keyReleased(KeyEvent e) {
23. l.setText("Key Released");
24. }
27. }
28.
31. }
32. }
Output:
Java KeyListener
1. import java.awt.*;
2. import java.awt.event.*;
4. Label l;
5. TextArea area;
6. KeyListenerExample(){
7.
8. l=new Label();
9. l.setBounds(20,50,200,20);
12. area.addKeyListener(this);
13.
14. add(l);add(area);
15. setSize(400,400);
16. setLayout(null);
17. setVisible(true);
18. }
24. }
26.
29. }
30. }
Output:
Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
The adapter classes are found in java.awt.event package. The Adapter classes with their
corresponding listener interfaces are given below.
HierarchyBoundsAdapter HierarchyBoundsListener
java.awt.dnd Adapter classes
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
1.import java.awt.*;
2. import java.awt.event.*;
3. public class MouseMotionAdapterExample extends MouseMotionAdapter{
4. Frame f;
5. MouseMotionAdapterExample(){
6. f=new Frame("Mouse Motion Adapter");
7. f.addMouseMotionListene
r(this); 8.
9. f.setSize(300,300);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13. public void mouseDragged(MouseEvent e) {
Output
:
Java KeyAdapter Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class KeyAdapterExample extends KeyAdapter{
4. Label l;
5. TextArea area;
6. Frame f;
7. KeyAdapterExample(){
8. f=new Frame("Key Adapter");
9. l=new Label();
10. l.setBounds(20,50,200,20);
11. area=new TextArea();
12. area.setBounds(20,80,300, 300);
13.
area.addKeyListener(
this); 14.
15. f.add(l);f.add(area);
16. f.setSize(400,400);
17. f.setLayout(null);
18. f.setVisible(true);
19. }
20. public void keyReleased(KeyEvent e) {
21. String text=area.getText();
22. String words[]=text.split("\\s");
23. l.setText("Words: "+words.length+" Characters:"+text.length());
24. }
25.
26. public static void main(String[] args) {
27. new KeyAdapterExample();
28. }
29. }
Output
:
UNIT-V
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components
like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Useful Methods of Component class
Method Description
public void setSize(int width,int sets the size (width and height) of the
height) component.
public void setLayout(LayoutManager defines the layout manager for the component.
m)
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
1. import java.awt.*;
2. class First extends Frame{
3. First(){
4. Button b=new Button("click me");
5. b.setBounds(30,100,80,30);// setting button position
6. add(b);//adding button into frame
7. setSize(300,300);//frame size 300 width and 300 height
8. setLayout(null);//no layout manager
9. setVisible(true);//now frame will be visible, by default not visible
10. }
11. public static void main(String args[]){
12. First f=new First();
13. } }
The setBounds(int x axis, int yaxis, int width, int height) method is used in the above example that
sets the position of the awt button.
1. import java.awt.*;
2. class First2{
3. First2(){
4. Frame f=new Frame();
5. Button b=new Button("click me");
6. b.setBounds(30,50,80,30);
7. f.add(b);
8. f.setSize(300,300);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. public static void main(String args[]){
13. First2 f=new First2();
14. }}
AWT Controls:
AWT Label:
The object of Label class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly.
2. class LabelExample{
5. Label l1,l2;
7. l1.setBounds(50,100, 100,30);
9. l2.setBounds(50,150, 100,30);
11. f.setSize(400,400);
12. f.setLayout(null);
13. f.setVisible(true);
14. }
15. }
Output:
Java AWT Button
The button class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed.
6. b.setBounds(50,100,80,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. }
Output:
Java AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is
a GUI component allows us to see invisible number of rows and columns.
Output:
Text Components:
The object of a TextField class is a text component that allows the editing of a single line text. It
inherits TextComponent class.
2. class TextFieldExample{
5. TextField t1,t2;
7. t1.setBounds(50,100, 200,30);
9. t2.setBounds(50,150, 200,30);
11. f.setSize(400,400);
12. f.setLayout(null);
13. f.setVisible(true);
14. }
15. }
Output:
The object of a TextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits TextComponent class.
3. {
4. TextAreaExample(){
area.setBounds(10,30, 300,300);
8. f.add(area);
9. f.setSize(400,400);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
14. {
16. }
17. }
Output:
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
3. {
4. CheckboxExample(){
5. Frame f= new Frame("Checkbox Example");
7. checkbox1.setBounds(100,100, 50,50);
9. checkbox2.setBounds(100,150, 50,50);
10. f.add(checkbox1);
11. f.add(checkbox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
17. {
19. }
20. }
Output:
Java AWT CheckboxGroup
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only
one check box button is allowed to be in "on" state and remaining check box button in "off" state.
It inherits the object class.
Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special control for
creating radio buttons in AWT.
1. import java.awt.*;
3. {
4. CheckboxGroupExample(){
8. checkBox1.setBounds(100,100, 50,50);
11. f.add(checkBox1);
12. f.add(checkBox2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
20. }
21. }
Output:
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits Component class.
3. {
4. ChoiceExample(){
7. c.setBounds(100,100, 75,75);
8. c.add("Item 1");
9. c.add("Item 2");
10. c.add("Item 3");
13. f.add(c);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
19. {
21. }
22. }
Output:
The object of List class represents a list of text items. By the help of list, user can choose either
one item or multiple items. It inherits Component class.
1. import java.awt.*;
3. {
4. ListExample(){
7. l1.setBounds(100,100, 75,75);
8. l1.add("Item 1");
9. l1.add("Item 2");
13. f.add(l1);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
19. {
21. }
22. }
Output:
Java AWT Dialog
The Dialog control represents a top level window with a border and a title used to take some form
of input from the user. It inherits the Window class.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but
Dialog doesn't have.
Output:
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu
must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the menu bar. It
inherits the MenuItem class.
Output:
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Registration Methods
For registering the component with the Listener, many classes provide the registration methods.
For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
2. import java.awt.event.*;
4. TextField tf;
5. AEvent()
6. {
7. //create components
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
11. b.setBounds(100,120,80,30);
12.
15.
17. add(b);add(tf);
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21. }
23. tf.setText("Welcome");
24. }
27. }
28. }
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above
example that sets the position of the component it may be button, textfield etc.
Output:
The Java MouseListener is notified whenever you change the state of mouse. It is notified against
MouseEvent. The MouseListener interface is found in java.awt.event package. It has five methods.
Java
MouseList
ener
Example 1
1. import java.awt.*;
2. import java.awt.event.*;
4. Label l;
5. MouseListenerExample(){
6. addMouseListener(this);
7.
8. l=new Label();
9. l.setBounds(20,50,100,20);
10. add(l);
11. setSize(300,300);
12. setLayout(null);
13. setVisible(true);
14. }
17. }
20. }
23. }
26. }
29. }
30. public static void main(String[] args) {
32. }
33. }
Output:
Java MouseListener
Example 2
1. import java.awt.*;
2. import java.awt.event.*;
4. MouseListenerExample2(){
5. addMouseListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),30,30);
15. }
20.
23. }
24. }
Output:
The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in java.awt.event package. It has three methods.
Java
KeyListen
er
Example 1
1. import java.awt.*;
2. import java.awt.event.*;
4. Label l;
5. TextArea area;
6. KeyListenerExample(){
7.
8. l=new Label();
9. l.setBounds(20,50,100,20);
12. area.addKeyListener(this);
13.
14. add(l);add(area);
15. setSize(400,400);
16. setLayout(null);
17. setVisible(true);
18. }
24. }
27. }
28.
31. }
32. }
Output:
Java KeyListener
1. import java.awt.*;
2. import java.awt.event.*;
4. Label l;
5. TextArea area;
6. KeyListenerExample(){
7.
8. l=new Label();
9. l.setBounds(20,50,200,20);
12. area.addKeyListener(this);
13.
14. add(l);add(area);
15. setSize(400,400);
16. setLayout(null);
17. setVisible(true);
18. }
24. }
26.
29. }
30. }
Output:
Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
The adapter classes are found in java.awt.event package. The Adapter classes with their
corresponding listener interfaces are given below.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
java.awt.dnd Adapter classes
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
Output:
Java MouseMotionAdapter Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseMotionAdapterExample extends MouseMotionAdapter{
4. Frame f;
5. MouseMotionAdapterExample(){
6. f=new Frame("Mouse Motion Adapter");
7. f.addMouseMotionListener(this);
8.
9. f.setSize(300,300);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13. public void mouseDragged(MouseEvent e) {
14. Graphics g=f.getGraphics();
15. g.setColor(Color.ORANGE);
16. g.fillOval(e.getX(),e.getY(),20,20);
17. }
18. public static void main(String[] args) {
19. new MouseMotionAdapterExample();
20. }
21. }
Output:
Java KeyAdapter Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class KeyAdapterExample extends KeyAdapter{
4. Label l;
5. TextArea area;
6. Frame f;
7. KeyAdapterExample(){
8. f=new Frame("Key Adapter");
9. l=new Label();
10. l.setBounds(20,50,200,20);
11. area=new TextArea();
12. area.setBounds(20,80,300, 300);
13. area.addKeyListener(this);
14.
15. f.add(l);f.add(area);
16. f.setSize(400,400);
17. f.setLayout(null);
18. f.setVisible(true);
19. }
20. public void keyReleased(KeyEvent e) {
21. String text=area.getText();
22. String words[]=text.split("\\s");
23. l.setText("Words: "+words.length+" Characters:"+text.length());
24. }
25.
26. public static void main(String[] args) {
27. new KeyAdapterExample();
28. }
29. }
Output:
UNIT-V
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:
o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
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");;
12. JButton b4=new JButton("WEST");;
13. JButton b5=new JButton("CENTER");;
14.
15. f.add(b1,BorderLayout.NORTH);
16. f.add(b2,BorderLayout.SOUTH);
17. f.add(b3,BorderLayout.EAST);
18. f.add(b4,BorderLayout.WEST);
19. f.add(b5,BorderLayout.CENTER);
20.
21. f.setSize(300,300);
22. f.setVisible(true);
23. }
24. public static void main(String[] args) {
25. new Border();
26. }
27. }
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed
in each rectangle.
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyGridLayout{
5. JFrame f;
6. MyGridLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14. JButton b6=new JButton("6");
15. JButton b7=new JButton("7");
16. JButton b8=new JButton("8");
17. JButton b9=new JButton("9");
18.
19. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
20. f.add(b6);f.add(b7);f.add(b8);f.add(b9);
21.
22. f.setLayout(new GridLayout(3,3));
23. //setting grid layout of 3 rows and 3 columns
24.
25. f.setSize(300,300);
26. f.setVisible(true);
27. }
28. public static void main(String[] args) {
29. new MyGridLayout();
30. }
31. }
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the
default layout of applet or panel.
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment
and the given horizontal and vertical gap.
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyFlowLayout{
5. JFrame f;
6. MyFlowLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14.
15. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
16.
17. f.setLayout(new FlowLayout(FlowLayout.RIGHT));
18. //setting flow layout of right alignment
19.
20. f.setSize(300,300);
21. f.setVisible(true);
22. }
23. public static void main(String[] args) {
24. new MyFlowLayout();
25. }
26. }
Java CardLayout
The CardLayout class manages the components in such a manner that only one component is
visible at a time. It treats each component as a card that is why it is known as CardLayout.
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.
o public void next(Container parent): is used to flip to the next card of the given container.
o public void previous(Container parent): is used to flip to the previous card of the given
container.
o public void first(Container parent): is used to flip to the first card of the given container.
o public void last(Container parent): is used to flip to the last card of the given container.
o public void show(Container parent, String name): is used to flip to the specified card
with the given name.
1. import java.awt.*;
2. import java.awt.event.*;
3.
4. import javax.swing.*;
5.
6. public class CardLayoutExample extends JFrame implements ActionListener{
7. CardLayout card;
8. JButton b1,b2,b3;
9. Container c;
10. CardLayoutExample(){
11.
12. c=getContentPane();
13. card=new CardLayout(40,30);
14. //create CardLayout object with 40 hor space and 30 ver space
15. c.setLayout(card);
16. 16.
17. b1=new JButton("Apple");
18. b2=new JButton("Boy");
19. b3=new JButton("Cat");
20. b1.addActionListener(this);
21. b2.addActionListener(this);
22. b3.addActionListener(this);
23.
24. c.add("a",b1);c.add("b",b2);c.add("c",b3);
25.
26. }
27. public void actionPerformed(ActionEvent e) {
28. card.next(c);
29. }
30.
31. public static void main(String[] args) {
32. CardLayoutExample cl=new CardLayoutExample();
33. cl.setSize(400,400);
34. cl.setVisible(true);
35. cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
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.
Fields
Useful Methods
Modifier and Type Method Description
Example
1. import java.awt.Button;
2. import java.awt.GridBagConstraints;
3. import java.awt.GridBagLayout;
4.
5. import javax.swing.*;
6. public class GridBagLayoutExample extends JFrame{
7. public static void main(String[] args) {
8. GridBagLayoutExample a = new GridBagLayoutExample(); 9.
}
10. public GridBagLayoutExample() {
11. GridBagLayout grid = new GridBagLayout();
12. GridBagConstraints gbc = new GridBagConstraints();
13. setLayout(grid);
14. setTitle("GridBag Layout Example");
15. GridBagLayout layout = new GridBagLayout();
16. this.setLayout(layout);
17. gbc.fill = GridBagConstraints.HORIZONTAL;
18. gbc.gridx = 0;
19. gbc.gridy = 0;
20. this.add(new Button("Button One"), gbc);
21. gbc.gridx = 1;
22. gbc.gridy = 0;
23. this.add(new Button("Button two"), gbc);
24. gbc.fill = GridBagConstraints.HORIZONTAL;
25. gbc.ipady = 20;
26. gbc.gridx = 0;
27. gbc.gridy = 1;
28. this.add(new Button("Button Three"), gbc);
29. gbc.gridx = 1;
30. gbc.gridy = 1;
31. this.add(new Button("Button Four"), gbc);
32. gbc.gridx = 0;
33. gbc.gridy = 2;
34. gbc.fill = GridBagConstraints.HORIZONTAL;
35. gbc.gridwidth = 2;
36. this.add(new Button("Button Five"), gbc);
37. setSize(300, 300);
38. setPreferredSize(getSize());
39. setVisible(true);
40. setDefaultCloseOperation(EXIT_ON_CLOSE);
41.
42. }
43.
44. }
Output:
Applets
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
Drawback of Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides
1 life cycle method for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
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
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is
for testing purpose only.
1. //First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter(). Syntax:
1. import java.applet.Applet;
2. import java.awt.Graphics;
3. public class UseParam extends Applet
4. {
5. public void paint(Graphics g)
6. {
7. String str=getParameter("msg");
8. g.drawString(str,50, 50);
9. } }
myapplet.html
1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>
Connceting to DB
What is JDBCDriver?
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server. For example, using JDBC drivers enable you to open database connections and to
interact with it by sending SQL or database commands then receiving results with Java.
The Java.sql package that ships with JDK, contains various classes with their behaviours defined
and their actual implementaions are done in third-party drivers. Third party vendors implements
the java.sql.Driver interface in their database driver.
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the client
application. As a result, you need some knowledge of the application server's configuration in order to
effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
The type 1 driver is not considered a deployment-level driver, and is typically used for development and
testing purposes only.
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver. 2.Connection
4. Password: Password is given by the user at the time of installing the mysql database. In this
example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create database first.
In this example, sonoo is the database name, root is the username and password.
import java.sql.*;
class MysqlCon
{
public static void main(String args[])
{
Try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)); con.close();
}
catch(Exception e){ System.out.println(e);
}
}
}
The above example will fetch all the records of emp table.
10 17911A1212 15 10
26
3
11 17911A1213 11 54
4 17
18 47
12 17911Alzie 1
4 13
13 17911A1215 50
8
14 17911A1216
4 5 3
4 36
15 |17911A1218 14| 15
16 17911A1219 3 48
16 4 3| 51
17 17911A1220 16
4
17 4 4 5
18 17911A1221
4
10
19 17911A1222 O 3 48
3 10
20 17911A1223 11 O
49
11
2 10
21 17911A1224
47
4 15
22 17911A1225 16 29
11 25 10
23 17911A1226
17 3 52
17911A1227 18 4 5
51
24
4 5 19 2 4 5
25 17911A1228 20
NNN
LOLOOO
u uunuuun u n n uu
EGG36|
NN|N|
oNE|+|=
OE|E|E|UwN OE|N|O|
w
N
wNNN wN ONwN|
N|w |S||A|D
unuu| wn
NNNO| E||N|
EFLLLIL
ASSP MENT OF COs FOR THE COURSE
CO CO Attainment (End
CO Attainment Overall CO Attainment
COs Method value Attain Assignments
(Internal-Theory) Exam)
ment
MI
3.0
CO1 Q1
2.0
MI
1.0
Q5
MI
3.0
Co2 Q2 1.5
MI
0.0
Q6
MI
3.0
Q3
MI
3.0
CO3 Q7 3.0 3.0 2.1 3.00 2.89
M2
3.0
Q1
M2
3.0
Q4
M2
3.0
CO4 Q2 3.0
M2
Q5
3.0
M2 2.0
Q3
CO5 1.0
M2
Course End Survey Form
1AVA PROGRAMMING
basic Java constructs?46 responses
Are you ableto understand OOP concepts to apply
Slight
Moderate 3
Substantial 41
Slight 3
Moderate 3
Substantial 40
3. Are you able to evaluate the usage of Exception Handling and Multithreading in complex
Java programs?46 responses
Slight 3
Moderate 1
Substantial 42
4. Are you able to contrast different GUI layouts and design GUI applications?46 responses
Slight
Moderate 4
Substantial 41
5. Are you able to construct a full-ledged Java GUI application, and Applet with database
connectivity?46 responses
Slight 3
Moderate 4
Substantial 39