Java Notes
Java Notes
3) Enterprise Application
Java Example
An application that is distributed in nature, such as
Let's have a quick look at Java programming banking applications, etc. is called enterprise
example. A detailed description of hello Java application. It has advantages of the high-level
example is available in next page. security, load balancing, and clustering. In Java, EJB
is used for creating enterprise applications.
1. class Simple{
2. public static void main(String args[]){ 4) Mobile Application
3. System.out.println("Hello Java");
4. } An application which is created for mobile devices
5. } is called a mobile application. Currently, Android
and Java ME are used for creating mobile
applications.
Java supports
C++ doesn't
Document documentation
support
ation comment (/** ... */) to
documentation
comment create documentation Types of Variables
comment.
for java source code.
There are three types of variables in java:
Java has no virtual
C++ supports
keyword. We can • local variable
virtual keyword
Virtual so that we can
override all non-static • instance variable
methods by default. In • static variable
Keyword decide whether or
other words, non-static
not override a
methods are virtual by 1) Local Variable
function.
default.
A variable declared inside the body of the method is
Java supports unsigned called local variable. You can use this variable only
right shift >>> within that method and the other methods in the
operator that fills zero class aren't even aware that the variable exists.
unsigned C++ doesn't
at the top for the
right shift support >>>
negative numbers. For A local variable cannot be defined with "static"
>>> operator.
positive numbers, it keyword.
works same like >>
operator.
2) Instance Variable
Java uses a single
A variable declared inside the class but outside the
inheritance tree always
because all classes are body of the method, is called instance variable. It is
C++ creates a not declared as static.
Inheritanc the child of Object
new inheritance
e Tree class in java. The
tree always. It is called instance variable because its value is
object class is the root
of the inheritance tree instance specific and is not shared among instances.
in java.
3) Static variable
Java is not so
C++ is nearer to A variable which is declared as static is called static
Hardware interactive with
hardware. variable. It cannot be local. You can create a single
hardware.
copy of static variable and share among all the
Java is also an object- instances of the class. Memory allocation for static
oriented language. variable happens only once when the class is loaded
C++ is an object-
However, everything in the memory.
oriented
(except fundamental
language.
Object- types) is an object in Example to understand the types of variables in java
However, in C
oriented Java. It is a single root
language, single
hierarchy as 1. class A{
root hierarchy is
everything gets 2. int data=50;//instance variable
not possible.
derived from 3. static int m=100;//static variable
java.lang.Object. 4. void method(){
5. int n=90;//local variable
Note 6. }
7. }//end of class
• Java doesn't support default arguments like C++.
• Java does not support header files like C++. Java
uses the import keyword to include different
classes and methods.
• Multidimensional Array
Java Array
Example of Java Array
Java array is an object which contains elements of
a similar data type. 1. class Testarray{
2. public static void main(String args[]){
A data structure where we store similar elements. 3. int a[]=new int[5];//declaration and instantiation
4. a[0]=10;//initialization
We can store only a fixed set of elements in a Java 5. a[1]=20;
array. 6. a[2]=70;
7. a[3]=40;
Array in java is index-based, the first element of the 8. a[4]=50;
array is stored at the 0 index. 9. //traversing array
10. for(int i=0;i<a.length;i++)//length is the property
of array
11. System.out.println(a[i]);
12. }}
1. Primitive data types: The primitive data types Byte Data Type
include boolean, char, byte, short, int, long, float
and double. The byte data type is an example of primitive data
2. Non-primitive data types: The non-primitive type. It is an 8-bit signed two's complement integer.
data types include Classes, Interfaces, and
Its value-range lies between -2^7 to 2^7-1
Arrays.
(inclusive). Its default value is 0.
Java Primitive Data Types The byte data type is used to save memory in large
arrays where the memory savings is most required. It
There are 8 types of primitive data types: saves space because a byte is 4 times smaller than an
integer. It can also be used in place of "int" data
• boolean data type type.
• byte data type
• char data type Example: byte a = 10, byte b = -20
• short data type
• int data type
• long data type Short Data Type
• float data type
• double data type The short data type is a 16-bit signed two's
complement integer. Its value-range lies between -
2^15 to 2^15-1 (inclusive). Its default value is 0.
Data Type Default Value Default size
The short data type can also be used to save memory
boolean false 1 bit just like byte data type. A short data type is 2 times
smaller than an integer.
char '\u0000' 2 byte
byte 0 1 byte
Example: short s = 10000, short r = -5000
Operator 7. }}
Category Precedence
Type
postfix expr++ expr-- Java Right Shift Operator Example
Unary ++expr --expr +expr -
prefix expr ~ ! 1. class OperatorExample{
2. public static void main(String args[]){
multiplicative */% 3. System.out.println(10>>2);//10/2^2=10/4=2
Arithmetic
additive +- 4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
Shift shift << >> >>>
6. }}
comparison < > <= >= instanceof
Relational
equality == != Java AND Operator Example: Logical &&
bitwise AND & and Bitwise &
bitwise exclusive
^ The logical && operator doesn't check second
Bitwise OR
condition if first condition is false. It checks second
bitwise inclusive | condition only if first one is true.
OR
logical AND && The bitwise & operator always checks both
Logical
logical OR || conditions whether first condition is true or false.
Ternary ternary ?:
1. class OperatorExample{
= += -= *= /= %= &= 2. public static void main(String args[]){
Assignment assignment ^= |= <<= >>= >>>=
3. int a=10;
4. int b=5; 12. }}
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true =
false CONTROL STATEMENTS
7. System.out.println(a<b&a<c);//false & true = fals
e Java If-else Statement
8. }}
The Java if statement is used to test the condition. It
Java OR Operator Example: Logical || and checks boolean condition: true or false. There are
Bitwise | various types of if statement in java.
1. /*
2. This
3. is
4. multi line
5. comment
6. */
• Object
Abstraction
Hiding internal details and showing functionality is CamelCase in java naming
known as abstraction. For example phone call, we
don't know the internal processing. conventions
In Java, we use abstract class and interface to If name is combined with two words, second word
achieve abstraction. will start with uppercase letter always e.g.
actionPerformed(), firstName, ActionEvent,
ActionListener etc.
1. class <class_name>{
2. Fields;
3. Methods;
Encapsulation 4. Blocks;
5. Constructors;
Binding (or wrapping) code and data together into a 6. Nested Classes;
single unit are known as encapsulation. For example 7. Interfaces;
capsule, it is wrapped with different medicines. 8. }
• Is used to initialize the static data member. 3) this() : to invoke current class constructor
• It is executed before the main method at the time
class A{
of classloading.
A(){System.out.println("hello a");}
A(int x){
Example of static block
this();
System.out.println(x);
1. class A2{
2. static{System.out.println("static block is invoke }}
d");}
3. public static void main(String args[]){ Inheritance in Java
4. System.out.println("Hello main");
5. }
6. } Inheritance is a mechanism in which one object
acquires all the properties and behaviours of a parent
Output: object. The idea behind inheritance in Java is that
static block is invoked you can create new classes that are built upon
Hello main existing classes.
this is a reference variable that refers to the current • For Method Overriding (so runtime
object. polymorphism can be achieved).
• For Code Reusability.
Terms used in Inheritance
The extends keyword indicates that you are making Single Inheritance Example
a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality. File: TestInheritance.java
1. class Employee{ 1. class Animal{
2. float salary=40000; 2. void eat(){System.out.println("eating...");}
3. } 3. }
4. class Programmer extends Employee{ 4. class Dog extends Animal{
5. int bonus=10000; 5. void bark(){System.out.println("barking...");}
6. public static void main(String args[]){ 6. }
7. Programmer p=new Programmer(); 7. class TestInheritance{
8. System.out.println("Programmer salary is:" 8. public static void main(String args[]){
+p.salary); 9. Dog d=new Dog();
10. d.bark();
9. System.out.println("Bonus of Programmer
11. d.eat();
is:"+p.bonus); 12. }}
10. }
11. }
Multilevel Inheritance Example
Types of inheritance in java File: TestInheritance2.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat(); Java Polymorphism
16. }}
Polymorphisms are classified into:
Hierarchical Inheritance 1. Pure Polymorphism:
1. Method Overloading
Example 2. Method Overriding
2. Adhoc Polymorphism
File: TestInheritance3.java
Method Overloading (Compile
1. class Animal{
2. void eat(){System.out.println("eating...");} time Polymorphism)
3. }
4. class Dog extends Animal{ If a class has multiple methods having same name
5. void bark(){System.out.println("barking...");} but different in parameters, it is known as Method
6. } Overloading.
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");} Different ways to overload the method
1. class Adder{
Forms of Inheritance 2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
Inheritance gets used for a number of purposes in
typical object-oriented programming: 4. }
5. class TestOverloading1{
specialization -- the subclass is a special case of the 6. public static void main(String[] args){
parent class (e.g. Frame and CannonWorld) 7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
specification -- the superclass just specifies which 9. }}
methods should be available but doesn't give code.
This is supported in java by interfaces and abstract Can we overload java main() method?
methods.
Yes, by method overloading. You can have any
construction -- the superclass is just used to provide number of main methods in a class by method
behavior, but instances of the subclass don't really overloading. But JVM calls main() method which
act like the superclass. Violates substitutability. receives string array as arguments only. Let's see the
Exmample: defining Stack as a subclass of Vector. simple example:
This is not clean -- better to define Stack as having a
field that holds a vector. 1. class TestOverloading4{
2. public static void main(String[] args){System.out
extension -- subclass adds new methods, and .println("main with String[]");}
perhaps redefines inherited ones as well. 3. public static void main(String args){System.out.p
rintln("main with String");}
4. public static void main(){System.out.println("mai
limitation -- the subclass restricts the inherited n without args");}
behavior. Violates substitutability. Example: 5. }
defining Queue as a subclass of Dequeue.
Ad hoc Polymorphism
We have “+” operator implemented in a
polymorphic way.
If you make any class as final, you cannot extend it. Q) Can we declare a constructor final?
Ans) Yes, final method is inherited but you cannot Example of static binding
override it. For Example:
1. class Dog{
1. class Bike{ 2. private void eat(){System.out.println("dog is eati
2. final void run(){System.out.println("running...") ng...");}
;} 3.
3. } 4. public static void main(String args[]){
4. class Honda2 extends Bike{ 5. Dog d1=new Dog(); //static binding
5. public static void main(String args[]){ 6. d1.eat();
6. new Honda2().run(); 7. }
7. } 8. }
8. }
Example of dynamic binding
Que) What is blank or uninitialized final variable?
1. class Animal{
A final variable that is not initialized at the time of 2. void eat(){System.out.println("animal is eating...
declaration is known as blank final variable. ");}
3. }
It can be initialized only in constructor. Ex: 4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");
1. class Student{
}
2. int id;
7.
3. String name;
8. public static void main(String args[]){
4. final String PAN_CARD_NUMBER;
9. Animal a=new Dog(); //dynamic binding
5. ...
10. a.eat();
6. }
11. }
12. }
Que) Can we initialize blank final variable?
1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
1. class StringBufferExample2{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
1. class StringBufferExample3{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
UNIT-2 Interface in Java
PACKAGES & An interface in java is a blueprint of a class. It has
static constants and abstract methods.
INTERFACES
The interface in Java is a mechanism to achieve
Abstraction in Java abstraction. There can be only abstract methods in
the Java interface, not method body.
Abstraction is a process of hiding the
implementation details and showing only Uses:
functionality to the user.
1. to achieve abstraction.
Ways to achieve Abstraction 2. multiple inheritance in Java.
Interface Syntax:
There are two ways to achieve abstraction in java
1. interface <interface_name>{
1. Abstract class (0 to 100%) 2.
2. Interface (100%) 3. // declare constant fields
4. // declare methods that abstract
Abstract class in Java 5. // by default.
6. }
A class which is declared as abstract is known as an
abstract class. The relationship between classes
and interfaces
Rules for Abstract Class:
Output:Hello
How to run java package
program 3. fully qualified name.
To Compile: javac -d . Simple.java 1. //save by A.java
To Run: java mypack.Simple 2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hell
How to access package from o");}
another package? 5. }
Output:Hello
Subpackage in java
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{ 1. //save as Simple.java
3. public static void main(String args[]){ 2. package mypack;
4. System.out.println("Hello subpackage"); 3. public class Simple{
5. } 4. public static void main(String args[]){
6. } 5. System.out.println("Welcome to package")
;
To Compile: javac -d . Simple.java 6. }
To Run: java com.javatpoint.core.Simple 7. }
1. private
2. default
3. protected
4. public
1) private access modifier 5. }
The private access modifier is accessible only within
class. 1. //save by B.java
2. package mypack;
1. class A{ 3. import pack.*;
2. private int data=40; 4.
3. private void msg(){System.out.println("Hello 5. class B extends A{
java");} 6. public static void main(String args[]){
4. } 7. B obj = new B();
5. 8. obj.msg();
6. public class Simple{ 9. }
7. public static void main(String args[]){ 10. }
8. A obj=new A();
9. System.out.println(obj.data);//Compile Tim 4) public access modifier
e Error The public access modifier is accessible
10. obj.msg();//Compile Time Error everywhere. It has the widest scope among all other
11. } modifiers.
12. }
Public Y Y Y Y
1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("He
llo");}
Object class in Java Wrapper class in Java
The Object class is the parent class of all the classes Wrapper class in java provides the mechanism to
in java by default. In other words, it is the topmost convert primitive into object and object into
class of java. primitive.
Java Math class Since J2SE 5.0, autoboxing and unboxing feature
converts primitive into object and object into
primitive automatically. The automatic conversion
1. public class JavaMathExample1
of primitive into object is known as autoboxing and
2. {
vice-versa unboxing.
3. public static void main(String[] args)
4. {
The eight classes of java.lang package are known as
5. double x = 28;
wrapper classes in java. The list of eight wrapper
6. double y = 4;
classes are given below:
7.
8. // return the maximum of two numbers
9. System.out.println("Maximum number Primitive Type Wrapper class
of x and y is: " +Math.max(x, y));
10. boolean Boolean
11. // return the square root of y
12. System.out.println("Square root of y is: char Character
" + Math.sqrt(y));
13. byte Byte
14. //returns 28 power of 4 i.e. 28*28*28*2
short Short
8
15. System.out.println("Power of x and y is:
int Integer
" + Math.pow(x, y));
16. long Long
17. // return the logarithm of given value
float Float
18. System.out.println("Logarithm of x is: "
+ Math.log(x)); double Double
19. System.out.println("Logarithm of y is: "
+ Math.log(y));
20.
21. // return the logarithm of given value wh
Wrapper class Example: Primitive to
en base is 10 Wrapper
22. System.out.println("log10 of x is: " + M
ath.log10(x)); 1. public class WrapperExample1{
23. System.out.println("log10 of y is: " + M 2. public static void main(String args[]){
ath.log10(y)); 3. //Converting int into Integer
24. 4. int a=20;
25. // return the log of x + 1 5. Integer i=Integer.valueOf(a);//converting int
26. System.out.println("log1p of x is: " +Ma into Integer
th.log1p(x)); 6. Integer j=a;//autoboxing, now compiler will
27. write Integer.valueOf(a) internally
28. // return a power of 2 7.
29. System.out.println("exp of a is: " +Math 8. System.out.println(a+" "+i+" "+j);
.exp(x)); 9. }}
30.
31. // return (a power of 2)-1 Wrapper class Example: Wrapper to
32. System.out.println("expm1 of a is: " +M
ath.expm1(x));
Primitive
33. }
1. public class WrapperExample2{
34. }
2. public static void main(String args[]){
3. //Converting Integer to int 4) public void
is used to close the current
4. Integer a=new Integer(3); close()throws
output stream.
5. int i=a.intValue();//converting Integer to int IOException
6. int j=a;//unboxing, now compiler will write a
.intValue() internally OutputStream Hierarchy
7.
8. System.out.println(a+" "+i+" "+j);
9. }}
InputStream Hierarchy
OutputStream class
OutputStream class is an abstract class. It is the
superclass of all classes representing an output
stream of bytes.
FileOutputStream class methods
Useful methods of OutputStream
Method Description Method Description
It is used to read the next byte of void It is used to write string to the
int read()
data from the input stream. writeChars(String output stream as a sequence of
s) characters.
int read(byte[] It is used to read up to len bytes of
ary, int off, int data from an array of bytes in the void writeByte(int It is used to write a byte to the
len) input stream. v) output stream as a 1-byte value.
It closes the input stream and It tests whether the file denoted
void close() releases any of the system resources boolean isFile() by this abstract pathname is a
associated with the stream. normal file.
1. class EnumExample1{
2. public enum Season { WINTER, SPRING, SUM
MER, FALL }
3. public static void main(String[] args) {
4. for (Season s : Season.values())
5. System.out.println(s);
6.
7. }}
java.io.Serializable interface
Example
1. import java.io.Serializable;
2. public class Student implements Serializable
{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
Deserialization in java
Deserialization is the process of reconstructing the
object from the serialized state.It is the reverse
operation of serialization.
Enumeration
Enum in java is a data type that contains fixed set
of constants.
2) Unchecked Exception
Types of Java Exceptions
The classes which inherit RuntimeException are
There are mainly two types of exceptions: checked known as unchecked exceptions e.g.
and unchecked. Here, an error is considered as the ArithmeticException, NullPointerException,
unchecked exception. According to Oracle, there are ArrayIndexOutOfBoundsException etc. Unchecked
three types of exceptions: exceptions are not checked at compile-time, but they
are checked at runtime.
1. Checked Exception
2. Unchecked Exception
3) Error
3. Error
Exception Keywords
There are 5 keywords which are used in handling
exceptions in Java.
Keyword Description
5. else
6. System.out.println("welcome to vote");
7. }
8. public static void main(String args[]){
9. validate(13);
10. System.out.println("rest of the code...");
11. }
12. }
throws keyword
The Java throws keyword is used to declare an
exception. It gives an information to the programmer
that there may occur an exception so it is better for
the programmer to provide the exception handling
code so that normal flow can be maintained.
throws example
1. import java.io.IOException;
2. class Testthrows1{
Note: If you don't handle exception, before 3. void m()throws IOException{
terminating the program, JVM executes finally 4. throw new IOException("device error");//chec
block(if any). ked exception
5. }
6. void n()throws IOException{
Finally example: 7. m();
8. }
1. class TestFinallyBlock{ 9. void p(){
2. public static void main(String args[]){ 10. try{
3. try{ 11. n();
4. int data=25/5; 12. }catch(Exception e){System.out.println("excep
5. System.out.println(data); tion handled");}
6. } 13. }
7. catch(NullPointerException e){System.out.print 14. public static void main(String args[]){
ln(e);} 15. Testthrows1 obj=new Testthrows1();
8. finally{System.out.println("finally block is alwa 16. obj.p();
ys executed");} 17. System.out.println("normal flow...");
9. System.out.println("rest of the code..."); 18. }
10. } 19. }
11. }
Rule: For each try block there can be zero or Difference between throw and
more catch blocks, but only one finally block. throws in Java
throw throws
Note: The finally block will not be executed if
program exits(either by calling System.exit() or
Java throw keyword is
Java throws keyword is used Java finalize example
used to explicitly throw
to declare an exception.
an exception. 1. class FinalizeExample{
2. public void finalize(){System.out.println("finaliz
Checked exception e called");}
Checked exception can be
cannot be propagated 3. public static void main(String[] args){
propagated with throws.
using throw only. 4. FinalizeExample f1=new FinalizeExample();
5. FinalizeExample f2=new FinalizeExample();
Throw is followed by an 6. f1=null;
Throws is followed by class.
instance. 7. f2=null;
8. System.gc();
Throw is used within Throws is used with the 9. }}
the method. method signature.
Multitasking
Multitasking is a process of executing multiple tasks There can be multiple processes inside the OS, and
simultaneously. We use multitasking to utilize the one process can have multiple threads.
CPU. Multitasking can be achieved in two ways:
Note: At a time one thread is executed only.
• Process-based Multitasking (Multiprocessing)
• Thread-based Multitasking (Multithreading)
How to create thread
1) Process-based Multitasking (Multiprocessing)
There are two ways to create a thread:
• Each process has an address in memory. In other
words, each process allocates a separate memory 1. By extending Thread class
area. 2. By implementing Runnable interface.
• A process is heavyweight.
• Cost of communication between the process is
high.
• Switching from one process to another requires
Thread class:
some time for saving and loading registers, Thread class provide constructors and methods to create
memory maps, updating lists, etc. and perform operations on a thread.Thread class extends
Object class and implements Runnable interface.
2) Thread-based Multitasking (Multithreading)
Methods of Thread class:
• Threads share the same address space. 1. public void run(): is used to perform action for
• A thread is lightweight. a thread.
• Cost of communication between the thread is 2. public void start(): starts the execution of the
low. thread.JVM calls the run() method on the
thread.
Note: At least one process is required for each 3. public void join(): waits for a thread to die.
thread. 4. public int getPriority(): returns the priority of
the thread.
5. public int setPriority(int priority): changes
What is Thread in java the priority of the thread.
6. public String getName(): returns the name of
A thread is a lightweight subprocess, the smallest the thread.
unit of processing. It is a separate path of execution. 7. public void setName(String name): changes
the name of the thread.
Threads are independent. If there occurs exception 8. public Thread currentThread(): returns the
reference of currently executing thread.
in one thread, it doesn't affect other threads. It uses a
9. public int getId(): returns the id of the thread.
shared memory area.
10. public Thread.State getState(): returns the 2) Java Thread Example by implementing
state of the thread. Runnable interface
11. public void yield(): causes the currently
executing thread object to temporarily pause and 1. class Multi3 implements Runnable{
allow other threads to execute. 2. public void run(){
12. public void suspend(): is used to suspend the 3. System.out.println("thread is running...");
thread(depricated). 4. }
13. public void resume(): is used to resume the 5. public static void main(String args[]){
suspended thread(depricated). 6. Multi3 m1=new Multi3();
14. public void stop(): is used to stop the 7. Thread t1 =new Thread(m1);
thread(depricated). 8. t1.start();
15. public boolean isDaemon(): tests if the thread 9. }
is a daemon thread. 10. }
16. public void setDaemon(boolean b): marks the
thread as daemon or user thread.
17. public void interrupt(): interrupts the thread. Priority of a Thread (Thread
18. public boolean isInterrupted(): tests if the
thread has been interrupted. Priority):
19. public static boolean interrupted(): tests if the
current thread has been interrupted. 3 constants defined in Thread class:
1. public static int MIN_PRIORITY
Runnable interface: 2. public static int NORM_PRIORITY
The Runnable interface should be implemented by 3. public static int MAX_PRIORITY
any class whose instances are intended to be
executed by a thread. Runnable interface have only Default priority of a thread is 5 (NORM_PRIORITY).
one method named run(). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
1. public void run(): is used to perform action for Example of priority of a Thread:
a thread.
1. class TestMultiPriority1 extends Thread{
2. public void run(){
Starting a thread: 3. System.out.println("running thread name is:"+
Thread.currentThread().getName());
start() method of Thread class is used to start a 4. System.out.println("running thread priority is:"
newly created thread. It performs following tasks: +Thread.currentThread().getPriority());
5.
• A new thread starts(with new callstack). 6. }
• The thread moves from New state to the 7. public static void main(String args[]){
Runnable state. 8. TestMultiPriority1 m1=new TestMultiPriority1(
);
• When the thread gets a chance to execute,
9. TestMultiPriority1 m2=new TestMultiPriority1(
its target run() method will run.
);
10. m1.setPriority(Thread.MIN_PRIORITY);
11. m2.setPriority(Thread.MAX_PRIORITY);
1) Java Thread Example by extending Thread 12. m1.start();
class 13. m2.start();
In this example, there is no synchronization, so Synchronized method is used to lock an object for
output is inconsistent. Let's see the example: any shared resource.
1. class Table{ When a thread invokes a synchronized method, it
2. void printTable(int n){//method not synchronized
automatically acquires the lock for that object and
3. for(int i=1;i<=5;i++){ releases it when the thread completes its task.
4. System.out.println(n*i);
5. try{ 1. //example of java synchronized method
6. Thread.sleep(400); 2. class Table{
7. }catch(Exception e){System.out.println(e);} 3. synchronized void printTable(int n){//synchroni
8. } zed method
9. 4. for(int i=1;i<=5;i++){
10. } 5. System.out.println(n*i);
11. } 6. try{
12. 7. Thread.sleep(400);
13. class MyThread1 extends Thread{ 8. }catch(Exception e){System.out.println(e);}
14. Table t; 9. }
15. MyThread1(Table t){ 10.
11. } • notify()
12. } • notifyAll()
13.
14. class MyThread1 extends Thread{
15. Table t;
1) wait() method
16. MyThread1(Table t){
17. this.t=t;
18. } Causes current thread to release the lock and wait
19. public void run(){ until either another thread invokes the notify()
20. t.printTable(5); method or the notifyAll() method for this object, or a
21. } specified amount of time has elapsed.
22.
23. } The current thread must own this object's monitor,
24. class MyThread2 extends Thread{ so it must be called from the synchronized method
25. Table t; only otherwise it will throw exception.
26. MyThread2(Table t){
27. this.t=t;
28. } Method Description
29. public void run(){
30. t.printTable(100); public final void wait()throws waits until object is
31. } InterruptedException notified.
32. }
33. public final void wait(long waits for the
34. public class TestSynchronization2{ timeout)throws specified amount of
35. public static void main(String args[]){ InterruptedException time.
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start(); 2) notify() method
40. t2.start();
41. } Wakes up a single thread that is waiting on this
42. } object's monitor. If any threads are waiting on this
object, one of them is chosen to be awakened. The
Output: 5 choice is arbitrary and occurs at the discretion of the
10 implementation. Syntax:
15
20
25 public final void notify()
100
200
300
400 3) notifyAll() method
500
Wakes up all threads that are waiting on this object's
monitor. Syntax:
Inter-thread communication in
Java public final void notifyAll()
• wait()
The point to point explanation of the above diagram 16. System.out.println("going to deposit...");
is as follows: 17. this.amount+=amount;
18. System.out.println("deposit completed... ");
1. Threads enter to acquire lock. 19. notify();
2. Lock is acquired by on thread. 20. }
3. Now thread goes to waiting state if you call 21. }
wait() method on the object. Otherwise it releases 22.
the lock and exits. 23. class Test{
4. If you call notify() or notifyAll() method, thread 24. public static void main(String args[]){
moves to the notified state (runnable state). 25. final Customer c=new Customer();
5. Now thread is available to acquire lock. 26. new Thread(){
6. After completion of the task, thread releases the 27. public void run(){c.withdraw(15000);}
lock and exits the monitor state of the object. 28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
Why wait(), notify() and notifyAll() methods are 32.
defined in Object class not Thread class? 33. }}
It is because they are related to lock and object has a Output: going to withdraw...
lock. Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
Difference between wait and sleep?
wait() sleep()
should be notified by
after the specified amount
notify() or notifyAll()
of time, sleep is completed.
methods
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for dep
osit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
UNIT-4
COLLECTIONS
Collections
The Collection in Java is a framework that provides
an architecture to store and manipulate the group of
objects.
Java Collection means a single unit of objects. Java Methods of Collection interface
Collection framework provides many interfaces and Method Description
classes.
public boolean is used to insert an element
What is a framework in Java add(Object element) in this collection.
public boolean
is used to search an element.
contains(Object element)
The important points about Java ArrayList class are: It is used to return an array
Object[] toArray() containing all of the elements in this
• Java ArrayList class can contain duplicate list in the correct order.
elements.
• Java ArrayList class maintains insertion order. Object[] It is used to return an array
• Java ArrayList class is non synchronized. toArray(Object[] containing all of the elements in this
• Java ArrayList allows random access because a) list in the correct order.
array works at the index basis.
• In Java ArrayList class, manipulation is slow boolean It is used to append the specified
because a lot of shifting needs to be occurred if add(Object o) element to the end of a list.
any element is removed from the array list.
It is used to insert all of the
boolean addAll(int
Hierarchy of ArrayList class elements in the specified collection
index, Collection
into this list, starting at the specified
c)
position.
1. import java.util.*;
2. class TestCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>(
);//Creating arraylist
Methods of Java ArrayList 5. list.add("Ravi");//Adding object in arraylist
Method Description 6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. } Methods of Java LinkedList
15. } Method Description
1. import java.util.*;
2. class TestCollection9{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. } Methods of Java TreeSet class
Method Description
Java TreeSet class
It is used to add all of the
boolean
• Contains unique elements only like HashSet. elements in the specified
addAll(Collection c)
• Access and retrieval times are quiet fast. collection to this set.
• Maintains ascending order.
boolean It is used to return true if this set
contains(Object o) contains the specified element.
Object It is used to retrieves and removes the Methods of Java Deque Interface
remove() head of this queue. Method Description
It is used to retrieves and removes the It is used to insert the specified element
Object poll() head of this queue, or returns null if this boolean
into this deque and return true upon
queue is empty. add(object)
success.
Object It is used to retrieves, but does not boolean It is used to insert the specified element
element() remove, the head of this queue. offer(object) into this deque.
It is used to retrieves, but does not Object It is used to retrieves and removes the
Object peek() remove, the head of this queue, or remove() head of this deque.
returns null if this queue is empty.
It is used to retrieves and removes the Java ArrayDeque Example
Object poll() head of this deque, or returns null if this
deque is empty. 1. import java.util.*;
2. public class ArrayDequeExample {
Object It is used to retrieves, but does not 3. public static void main(String[] args) {
element() remove, the head of this deque. 4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<Stri
It is used to retrieves, but does not ng>();
Object peek() remove, the head of this deque, or 6. deque.add("Ravi");
7. deque.add("Vijay");
returns null if this deque is empty.
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
ArrayDeque class 14. }
Map.Entry Interface
Entry is the sub interface of Map. So we will be
accessed it by Map.Entry name. It provides methods
to get key and value.
Map doesn't allow duplicate keys, but you can have Object getValue() It is used to obtain value.
duplicate values. HashMap and LinkedHashMap
allows null keys and values but TreeMap doesn't Java Map Example: Generic (New Style)
allow any null key or value.
1. import java.util.*;
Map can't be traversed so you need to convert it into 2. class MapInterfaceExample{
Set using keySet() or entrySet() method. 3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Inte
ger,String>();
Class Description
5. map.put(100,"Amit");
6. map.put(101,"Vijay");
HashMap is the implementation of
HashMap 7. map.put(102,"Rahul");
Map but it doesn't maintain any order.
8. for(Map.Entry m:map.entrySet()){
9. System.out.println(m.getKey()+" "+m.getValue
LinkedHashMap is the implementation
());
LinkedHashMap of Map, it inherits HashMap class. It 10. }
maintains insertion order. 11. }
12. }
TreeMap is the implementation of
TreeMap Map and SortedMap, it maintains Java Map Example: Non-Generic (Old Style)
ascending order.
1. //Non-generic
Useful methods of Map interface 2. import java.util.*;
Method Description 3. public class MapExample1 {
4. public static void main(String[] args) {
Object put(Object It is used to insert an entry in this 5. Map map=new HashMap();
key, Object value) map. 6. //Adding elements to map
7. map.put(1,"Amit");
void putAll(Map It is used to insert the specified 8. map.put(5,"Rahul");
map) map in this map. 9. map.put(2,"Jai");
10. map.put(6,"Amit");
Object It is used to delete an entry for the 11. //Traversing Map
remove(Object key) specified key. 12. Set set=map.entrySet();//Converting to Set so t
hat we can traverse
Object get(Object It is used to return the value for 13. Iterator itr=set.iterator();
key) the specified key. 14. while(itr.hasNext()){
15. //Converting to Map.Entry so that we can ge
boolean t key and value separately
It is used to search the specified 16. Map.Entry entry=(Map.Entry)itr.next();
containsKey(Object
key from this map. 17. System.out.println(entry.getKey()+" "+entry
key)
.getValue());
18. } It is used to associate the
19. } Object put(Object
specified value with the
20. } key, Object value)
specified key in this map.
1. import java.util.*;
2. class TestCollection13{
3. public static void main(String args[]){
4. HashMap<Integer,String> hm=new HashMap<I
nteger,String>();
5. hm.put(100,"Amit");
6. hm.put(101,"Vijay");
7. hm.put(102,"Rahul");
8. for(Map.Entry m:hm.entrySet()){
9. System.out.println(m.getKey()+" "+m.getValue
());
10. }
Methods of Java HashMap class 11. }
Method Description 12. }
boolean It is used to return true if this map boolean It is used to return true if this map
containsKey(Object maps one or more keys to the containsValue maps one or more keys to the
key) specified value. (Object value) specified value.
• A TreeMap contains values based on the key. It Collection It is used to return a collection view
implements the NavigableMap interface and values() of the values contained in this map.
extends AbstractMap class.
• It contains only unique elements. Java TreeMap Example:
• It cannot have null key but can have multiple null
values. 1. import java.util.*;
• It is same as HashMap instead maintains 2. class TestCollection15{
ascending order. 3. public static void main(String args[]){
4. TreeMap<Integer,String> hm=new TreeMap<In
teger,String>();
5. hm.put(100,"Amit");
6. hm.put(102,"Ravi");
7. hm.put(101,"Vijay");
8. hm.put(103,"Rahul");
9. for(Map.Entry m:hm.entrySet()){
10. System.out.println(m.getKey()+" "+m.getValue
());
11. }
12. }
13. }
1. import java.util.*;
Java Comparable interface 2. class AgeComparator implements Comparator<S
tudent>{
This interface is found in java.lang package and 3. public int compare(Student s1,Student s2){
contains only one method named 4. if(s1.age==s2.age)
compareTo(Object). 5. return 0;
6. else if(s1.age>s2.age)
public int compareTo(Object obj): is used to 7. return 1;
8. else
compare the current object with the specified object.
9. return -1;
10. }
Java Comparable Example 11. }
1. import java.util.*;
Java Comparator interface 2. import java.io.*;
3. class Simple{
Java Comparator interface is used to order the 4. public static void main(String args[]){
objects of user-defined class. 5.
6. ArrayList<Student> al=new ArrayList<Student>
This interface is found in java.util package and ();
contains 2 methods compare(Object obj1,Object 7. al.add(new Student(101,"Vijay",23));
8. al.add(new Student(106,"Ajay",27));
obj2) and equals(Object element).
9. al.add(new Student(105,"Jai",21));
10.
Java Comparator Example 11. System.out.println("Sorting by Name...");
12.
Student.java 13. Collections.sort(al,new NameComparator());
14. for(Student st: al){
15. System.out.println(st.rollno+" "+st.name+" "+st.a
1. class Student{
ge);
2. int rollno;
16. }
3. String name;
17.
4. int age;
18. System.out.println("sorting by age...");
5. Student(int rollno,String name,int age){
19.
6. this.rollno=rollno;
20. Collections.sort(al,new AgeComparator());
7. this.name=name;
21. for(Student st: al){
8. this.age=age;
22. System.out.println(st.rollno+" "+st.name+" "+st.a
9. }
ge);
10. }
23. }
24.
AgeComparator.java
25. } Returns the maximum element in c as determined
26. } by natural ordering. The collection need not be
sorted.
Output:Sorting by Name...
106 Ajay 27 static Object min(Collection c)
105 Jai 21
101 Vijay 23 Returns the minimum element in c as determined
by natural ordering.
Sorting by age...
105 Jai 21 static void reverse(List list)
101 Vijay 23
106 Ajay 27
Reverses the sequence in list.
static Comparator reverseOrder( )
Difference between Comparable
and Comparator Returns a reverse comparator.
Comparable Comparator static void rotate(List list, int n)
The Comparator provides Rotates list by n places to the right. To rotate left,
1) Comparable provides a
multiple sorting use a negative value for n.
single sorting sequence. In
sequences. In other words, static void shuffle(List list)
other words, we can sort
we can sort the collection
the collection on the basis
on the basis of multiple Shuffles (i.e., randomizes) the elements in list.
of a single element such as
elements such as id, name,
id or name or price, etc. static Set singleton(Object obj)
and price, etc.
2) Comparable affects the Comparator doesn't affect Returns obj as an immutable set. This is an easy
original class, i.e., the the original class, i.e., way to convert a single object into a set.
actual class is modified. actual class is not modified. static void sort(List list)
3) Comparable provides Comparator provides Sorts the elements of the list as determined by their
compareTo() method to compare() method to sort natural ordering.
sort elements. elements.
static void swap(List list, int idx1, int idx2)
4) Comparable is found in A Comparator is found in
java.lang package. the java.util package. Exchanges the elements in the list at the indices
specified by idx1 and idx2.
5) We can sort the list We can sort the list static Collection
elements of Comparable elements of Comparator synchronizedCollection(Collection c)
type by type by
Collections.sort(List) Collections.sort(List, Returns a thread-safe collection backed by c.
method. Comparator) method.
static List synchronizedList(List list)
void clear() It is used to reset the hash table. It can be used to get property value based on the
property key. The Properties class provides methods
This method return true if some to get data from properties file and store data into
boolean
value equal to the value exist properties file. Moreover, it can be used to get
contains(Object
within the hash table, else return properties of system.
value)
false.
Advantage of properties file Now, lets create the java class to read the data from
the properties file.
Recompilation is not required, if information is
changed from properties file: If any information is Test.java
changed from the properties file, you don't need to
recompile the java class. It is used to store 1. import java.util.*;
information which is to be changed frequently. 2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exce
Methods of Properties class
ption{
5. FileReader reader=new FileReader("db.propert
The commonly used methods of Properties class are ies");
given below. 6.
7. Properties p=new Properties();
Method Description 8. p.load(reader);
9.
public void load(Reader loads data from the Reader 10. System.out.println(p.getProperty("user"));
r) object. 11. System.out.println(p.getProperty("password"))
;
public void loads data from the 12. }
load(InputStream is) InputStream object 13. }
public void Now if you change the value of the properties file,
sets the property in the you don't need to compile the java class again. That
setProperty(String
properties object. means no maintenance problem.
key,String value)
public void
The stack is the subclass of Vector. It implements
writes the properties in the the last-in-first-out data structure, i.e., Stack. The
store(OutputStream os,
OutputStream object. stack contains all of the methods of Vector class and
String comment)
also provides its own methods like boolean push(),
writers the properties in the boolean peek(), boolean push(object o), which
storeToXML(OutputStrea defines its properties.
writer object for generating
m os, String comment)
xml document.
Stack Example:
public void writers the properties in the
storeToXML(Writer w, writer object for generating 1. import java.util.*;
String comment, String xml document with 2. public class TestJavaCollection4{
encoding) specified encoding. 3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
Example of Properties class to get information 7. stack.push("Amit");
from properties file 8. stack.push("Ashish");
9. stack.push("Garima");
To get information from the properties file, create 10. stack.pop();
11. Iterator<String> itr=stack.iterator();
the properties file first. 12. while(itr.hasNext()){
13. System.out.println(itr.next());
db.properties 14. }
15. }
1. user=system 16. }
2. password=oracle
Vector
Vector uses a dynamic array to store the data Java BitSet Class
elements. It is similar to ArrayList. However, It is
synchronized and contains many methods that are
not the part of Collection framework. Each component of bit set contains at least one
Boolean value. The contents of one BitSet may be
Vector example changed by other BitSet using logical AND, logical
OR and logical exclusive OR operations. The index
1. import java.util.*; of bits of BitSet class is represented by positive
2. public class TestJavaCollection3{ integers.
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>(); Each element of bits contains either true or false
5. v.add("Ayush"); value. Initially, all bits of a set have the false value.
6. v.add("Amit"); A BitSet is not safe for multithreaded use without
7. v.add("Ashish"); using external synchronization.
8. v.add("Garima");
9. Iterator<String> itr=v.iterator();
10. while(itr.hasNext()){ Java BitSet Methods
11. System.out.println(itr.next());
12. } Type Method Description
13. }
14. } This method is used to perform a
and(BitSet logical AND operation of this
void
More Utility Classes set) target bit set with the specified
argument.
returns the total number of boolea get(int This method returns the bit value of
int countTokens()
tokens. n bitIndex) the specified index.
Example of StringTokenizer class
This method returns true if the
boolea
1. import java.util.StringTokenizer; isEmpty() current BitSet does not contain any
n
2. public class Simple{ bit which is set to true.
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my This method returns the "logical
int length()
name is khan"," "); size" of this BitSet.
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken()); This method is used to perform a
or(BitSet
7. } void logical OR operation of this target
set)
8. } bit set with the specified argument.
9. }
set(int This method sets true to bit value at
void
bitIndex) the specified index.
This method returns the number of java.util.Date Methods
int size() bit space actually in use by this
BitSet to represent bit values.
Method Description
This method is used to perform a
tests if current date is after the
xor(BitSet logical XOR operation of this bit boolean after(Date date)
void given date.
set) set with the specified bit set
argument.
boolean before(Date tests if current date is before
date) the given date.
Output:
101
Amar Singh
101.000000
65
c
Window
UNIT-5
GUI PROGRAMMING The window is the container that have no borders
and menu bars. You must use frame, dialog or
WITH SWING & EVENT another window for creating a window.
HANDLING
Java AWT Tutorial Panel
Java AWT (Abstract Window Toolkit) is an API to The Panel is the container that doesn't contain title
develop GUI or window-based applications in java. bar and menu bars. It can have other components
like button, textfield etc.
Java AWT components are platform-dependent i.e.
components are displayed according to the view of
operating system. AWT is heavyweight i.e. its Frame
components are using the resources of OS.
The Frame is the container that contain title bar and
The java.awt package provides classes for AWT api can have menu bars. It can have other components
such as TextField, Label, TextArea, RadioButton, like button, textfield etc.
CheckBox, Choice, List etc.
public void
changes the visibility of the
setVisible(boolean
component, by default false.
status)
Container
1. import java.awt.*;
2. class First extends Frame{ Third, the use of heavyweight components caused
3. First(){ some frustrating restrictions.
4. Button b=new Button("click me");
5. b.setBounds(30,100,80,30);// setting button positi Due to these limitations Swing came and was
on
integrated to java.
6. add(b);//adding button into frame
7. setSize(300,300);//frame size 300 width and 300
height Swing is built on the AWT.
8. setLayout(null);//no layout manager Two key Swing features are:
9. setVisible(true);//now frame will be visible, by d Swing components are light weight,
efault not visible Swing supports a pluggable look and feel.
10. }
11. public static void main(String args[]){
12. First f=new First();
The MVC Connection:
13. }} In general, a visual component is a composite of
three distinct aspects:
1. The way that the component looks when
AWT Example by Association rendered on the screen
2. The way that the component reacts to the
1. import java.awt.*; user
2. class First2{
3. The state information associated with the
3. First2(){
component.
4. Frame f=new Frame();
5. Button b=new Button("click me"); The Model-View-Controller architecture is
6. b.setBounds(30,50,80,30); successful for all these.
7. f.add(b);
8. f.setSize(300,300); Components and Containers:
9. f.setLayout(null); A component is an independent visual control, such
10. f.setVisible(true); as a push button. A container holds a group of
11. } components. Furthermore, in order for a component
12. public static void main(String args[]){ to be displayed must be held with in a container.
13. First2 f=new First2();
14. }} Swing components are derived from JComponent
class. Note that all component classes begin with the
Limitations of AWT, MVC letter J. For example, a label is JLabel, a button is
JButton etc.
Architecture, Components &
Containers Swing defines two types of containers. The first are
top level containers: JFrame, JApplet, JWindow, and
Limitations of AWT: JDialog. These containers do not inherit
The AWT defines a basic set of controls, windows, JComponent. They do, however inherit the AWT
and dialog boxes that support a classes Container and Component. Unlike Swing’s
usable, but limited graphical interface. One reason other components which are heavy weight, the top
for the limited nature of the AWT is level containers are heavy weight. The
that it translates its various visual components into
their corresponding, platform-specific equivalents or second type of containers are light weight inherit
peers. This means that the look and feel of a from JComponent. Example- Jpanel.
component is defined by the platform, not by java.
Because the AWT components use native code
resources, they are referred to as heavy weight. Java FlowLayout
The use of native peers led to several problems. The FlowLayout is used to arrange the components
First, because of variations between operating in a line, one after another (in a flow). It is the
systems, a component might look, or even act, default layout of applet or panel.
differently on different platforms. This variability
threatened java’s philosophy: write once, run Fields of FlowLayout class
anywhere. Second, the look and feel of each
component was fixed and could not be changed. 1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER 22. }
4. public static final int LEADING 23. public static void main(String[] args) {
5. public static final int TRAILING 24. new MyFlowLayout();
25. }
Constructors of FlowLayout class 26. }
Java BorderLayout
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border {
5. JFrame f;
6. Border(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("NORTH");;
10. JButton b2=new JButton("SOUTH");;
11. JButton b3=new JButton("EAST");; 1. import java.awt.*;
12. JButton b4=new JButton("WEST");; 2. import javax.swing.*;
13. JButton b5=new JButton("CENTER");; 3.
14. 4. public class MyGridLayout{
15. f.add(b1,BorderLayout.NORTH); 5. JFrame f;
16. f.add(b2,BorderLayout.SOUTH); 6. MyGridLayout(){
17. f.add(b3,BorderLayout.EAST); 7. f=new JFrame();
18. f.add(b4,BorderLayout.WEST); 8.
19. f.add(b5,BorderLayout.CENTER); 9. JButton b1=new JButton("1");
20. 10. JButton b2=new JButton("2");
21. f.setSize(300,300); 11. JButton b3=new JButton("3");
22. f.setVisible(true); 12. JButton b4=new JButton("4");
23. } 13. JButton b5=new JButton("5");
24. public static void main(String[] args) { 14. JButton b6=new JButton("6");
25. new Border(); 15. JButton b7=new JButton("7");
26. } 16. JButton b8=new JButton("8");
27. } 17. JButton b9=new JButton("9");
18.
19. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b
Java GridLayout 5);
20. f.add(b6);f.add(b7);f.add(b8);f.add(b9);
The GridLayout is used to arrange the components 21.
22. f.setLayout(new GridLayout(3,3));
in rectangular grid. One component is displayed in
23. //setting grid layout of 3 rows and 3 columns
each rectangle. 24.
25. f.setSize(300,300);
Constructors of GridLayout class 26. f.setVisible(true);
27. }
1. GridLayout(): creates a grid layout with one 28. public static void main(String[] args) {
column per component in a row. 29. new MyGridLayout();
30. } 5.
31. } 6. public class CardLayoutExample extends JFrame
implements ActionListener{
7. CardLayout card;
Java CardLayout 8. JButton b1,b2,b3;
9. Container c;
The CardLayout class manages the components in 10. CardLayoutExample(){
such a manner that only one component is visible at 11.
a time. It treats each component as a card that is why 12. c=getContentPane();
it is known as CardLayout. 13. card=new CardLayout(40,30);
14. //create CardLayout object with 40 hor space and
30 ver space
Constructors of CardLayout class 15. c.setLayout(card);
16.
1. CardLayout(): creates a card layout with zero 17. b1=new JButton("Apple");
horizontal and vertical gap. 18. b2=new JButton("Boy");
2. CardLayout(int hgap, int vgap): creates a card 19. b3=new JButton("Cat");
layout with the given horizontal and vertical gap. 20. b1.addActionListener(this);
21. b2.addActionListener(this);
Commonly used methods of CardLayout class 22. b3.addActionListener(this);
23.
• public void next(Container parent): is used to 24. c.add("a",b1);c.add("b",b2);c.add("c",b3);
flip to the next card of the given container. 25.
• public void previous(Container parent): is 26. }
used to flip to the previous card of the given 27. public void actionPerformed(ActionEvent e) {
container.
• public void first(Container parent): is used to 28. card.next(c);
flip to the first card of the given container. 29. }
• public void last(Container parent): is used to 30.
flip to the last card of the given container. 31. public static void main(String[] args) {
• public void show(Container parent, String 32. CardLayoutExample cl=new CardLayoutEx
name): is used to flip to the specified card with ample();
the given name. 33. cl.setSize(400,400);
34. cl.setVisible(true);
35. cl.setDefaultCloseOperation(EXIT_ON_CL
OSE);
Example of CardLayout class 36. }
37. }
Java GridBagLayout
The Java GridBagLayout class is used to align
components vertically, horizontally or along their
baseline.
Registration Methods
• Button
o public void
addActionListener(ActionListener a){}
• MenuItem
o public void
addActionListener(ActionListener a){}
• TextField
o public void
addActionListener(ActionListener a){}
Event and Listener (Java Event o public void
addTextListener(TextListener a){}
Handling) • TextArea
o public void
Changing the state of an object is known as an
addTextListener(TextListener a){}
event. For example, click on button, dragging • Checkbox
mouse etc. The java.awt.event package provides o public void
many event classes and Listener interfaces for event addItemListener(ItemListener a){}
handling. • Choice
o public void
addItemListener(ItemListener a){}
• List
Java Event classes and Listener o public void
interfaces addActionListener(ActionListener a){}
o public void
addItemListener(ItemListener a){}
Event Classes Listener Interfaces
ActionEvent ActionListener
Java Event Handling Code
MouseListener and
MouseEvent We can put the event handling code into one of the
MouseMotionListener
following places:
MouseWheelEvent MouseWheelListener
1. Within class
KeyEvent KeyListener 2. Other class
3. Anonymous class
ItemEvent ItemListener
Java event handling by implementing
TextEvent TextListener ActionListener
AdjustmentEvent AdjustmentListener
1. import java.awt.*;
2. import java.awt.event.*;
WindowEvent WindowListener
3. class AEvent extends Frame implements ActionL
istener{
ComponentEvent ComponentListener
4. TextField tf;
5. AEvent(){
ContainerEvent ContainerListener
6.
7. //create components
FocusEvent FocusListener 8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10. Button b=new Button("click me");
Steps to perform Event Handling 11. b.setBounds(100,120,80,30);
12.
13. //register listener 10. }
14. b.addActionListener(this);//passing current instan
ce
15.
3) Java event handling by anonymous class
16. //add components and set size, layout and visibili
ty
17. add(b);add(tf); 1. import java.awt.*;
18. setSize(300,300); 2. import java.awt.event.*;
19. setLayout(null); 3. class AEvent3 extends Frame{
20. setVisible(true); 4. TextField tf;
21. } 5. AEvent3(){
22. public void actionPerformed(ActionEvent e){ 6. tf=new TextField();
23. tf.setText("Welcome"); 7. tf.setBounds(60,50,170,20);
24. } 8. Button b=new Button("click me");
25. public static void main(String args[]){ 9. b.setBounds(50,120,80,30);
26. new AEvent(); 10.
27. } 11. b.addActionListener(new ActionListener(){
28. } 12. public void actionPerformed(){
13. tf.setText("hello");
14. }
public void setBounds(int xaxis, int yaxis, int 15. });
width, int height); have been used in the above 16. add(b);add(tf);
example that sets the position of the component it 17. setSize(300,300);
may be button, textfield etc. 18. setLayout(null);
19. setVisible(true);
2) Java event handling by outer class 20. }
21. public static void main(String args[]){
1. import java.awt.*; 22. new AEvent3();
2. import java.awt.event.*; 23. }
3. class AEvent2 extends Frame{ 24. }
4. TextField tf;
5. AEvent2(){ Java AWT Button
6. //create components
7. tf=new TextField();
8. tf.setBounds(60,50,170,20); The button class is used to create a labeled button
9. Button b=new Button("click me"); that has platform independent implementation. The
10. b.setBounds(100,120,80,30); application result in some action when the button is
11. //register listener pushed.
12. Outer o=new Outer(this);
13. b.addActionListener(o);//passing outer class insta
nce
Java AWT Button Example
14. //add components and set size, layout and visibili
ty 1. import java.awt.*;
15. add(b);add(tf); 2. public class ButtonExample {
16. setSize(300,300); 3. public static void main(String[] args) {
17. setLayout(null); 4. Frame f=new Frame("Button Example");
18. setVisible(true); 5. Button b=new Button("Click Here");
19. } 6. b.setBounds(50,100,80,30);
20. public static void main(String args[]){ 7. f.add(b);
21. new AEvent2(); 8. f.setSize(400,400);
22. } 9. f.setLayout(null);
23. } 10. f.setVisible(true);
11. }
1. import java.awt.event.*; 12. }
2. class Outer implements ActionListener{
3. AEvent2 obj; Output:
4. Outer(AEvent2 obj){
5. this.obj=obj;
6. }
7. public void actionPerformed(ActionEvent e){
8. obj.tf.setText("welcome");
9. }
1. import java.awt.*;
2. class LabelExample{
3. public static void main(String args[]){
4. Frame f= new Frame("Label Example");
5. Label l1,l2;
6. l1=new Label("First Label.");
7. l1.setBounds(50,100, 100,30);
8. l2=new Label("Second Label.");
9. l2.setBounds(50,150, 100,30);
10. f.add(l1); f.add(l2);
11. f.setSize(400,400);
12. f.setLayout(null);
13. f.setVisible(true);
Java AWT Button Example with 14. }
15. }
ActionListener
Output:
1. import java.awt.*;
2. import java.awt.event.*;
3. public class ButtonExample {
4. public static void main(String[] args) {
5. Frame f=new Frame("Button Example");
6. final TextField tf=new TextField();
7. tf.setBounds(50,50, 150,20);
8. Button b=new Button("Click Here");
9. b.setBounds(50,100,60,30);
10. b.addActionListener(new ActionListener(){
11. public void actionPerformed(ActionEvent e){
12. tf.setText("Welcome to Javatpoint.");
13. }
14. });
15. f.add(b);f.add(tf);
16. f.setSize(400,400);
17. f.setLayout(null);
18. f.setVisible(true);
19. }
Java AWT Label Example with
20. } ActionListener
Output: 1. import java.awt.*;
2. import java.awt.event.*;
3. public class LabelExample extends Frame imple
ments ActionListener{
4. TextField tf; Label l; Button b;
5. LabelExample(){
6. tf=new TextField();
7. tf.setBounds(50,50, 150,20);
8. l=new Label();
9. l.setBounds(50,100, 250,20);
10. b=new Button("Find IP");
11. b.setBounds(50,150,60,30);
12. b.addActionListener(this);
13. add(b);add(tf);add(l);
Java AWT Label 14. setSize(400,400);
15. setLayout(null);
The object of Label class is a component for placing 16. setVisible(true);
text in a container. It is used to display a single line 17. }
of read only text. The text can be changed by an 18. public void actionPerformed(ActionEvent e) {
application but a user cannot edit it directly.
19. try{
20. String host=tf.getText();
Java Label Example
21. String ip=java.net.InetAddress.getByName(
host).getHostAddress();
22. l.setText("IP of "+host+" is: "+ip);
23. }catch(Exception ex){System.out.println(ex
);}
24. }
25. public static void main(String[] args) {
26. new LabelExample();
27. }
28. }
Output:
Output:
Output:
Java AWT Checkbox Example
with ItemListener
1. import java.awt.*;
Java AWT Checkbox 2. import java.awt.event.*;
3. public class CheckboxExample
The Checkbox class is used to create a checkbox. It 4. {
is used to turn an option on (true) or off (false). 5. CheckboxExample(){
Clicking on a Checkbox changes its state from "on" 6. Frame f= new Frame("CheckBox Example"
to "off" or from "off" to "on". );
7. final Label label = new Label();
8. label.setAlignment(Label.CENTER);
Java AWT Checkbox Example 9. label.setSize(400,100);
10. Checkbox checkbox1 = new Checkbox("C+
1. import java.awt.*; +");
2. public class CheckboxExample 11. checkbox1.setBounds(100,100, 50,50);
3. { 12. Checkbox checkbox2 = new Checkbox("Jav
4. CheckboxExample(){ a");
5. Frame f= new Frame("Checkbox Example"); 13. checkbox2.setBounds(100,150, 50,50);
14. f.add(checkbox1); f.add(checkbox2); f.add(l
6. Checkbox checkbox1 = new Checkbox("C+ abel);
+"); 15. checkbox1.addItemListener(new ItemListen
7. checkbox1.setBounds(100,100, 50,50); er() {
8. Checkbox checkbox2 = new Checkbox("Jav 16. public void itemStateChanged(ItemEvent
a", true); e) {
9. checkbox2.setBounds(100,150, 50,50); 17. label.setText("C++ Checkbox: "
10. f.add(checkbox1); 18. + (e.getStateChange()==1?"checked":"
11. f.add(checkbox2); unchecked"));
12. f.setSize(400,400); 19. }
13. f.setLayout(null); 20. });
14. f.setVisible(true); 21. checkbox2.addItemListener(new ItemListen
15. } er() {
16. public static void main(String args[]) 22. public void itemStateChanged(ItemEvent
17. { e) {
18. new CheckboxExample(); 23. label.setText("Java Checkbox: "
19. } 24. + (e.getStateChange()==1?"checked":"
20. } unchecked"));
25. }
Output: 26. });
27. f.setSize(400,400);
28. f.setLayout(null);
29. f.setVisible(true);
30. } 6. CheckboxGroup cbg = new CheckboxGroup
31. public static void main(String args[]) ();
32. { 7. Checkbox checkBox1 = new Checkbox("C+
33. new CheckboxExample(); +", cbg, false);
34. } 8. checkBox1.setBounds(100,100, 50,50);
35. } 9. Checkbox checkBox2 = new Checkbox("Jav
a", cbg, true);
Output: 10. checkBox2.setBounds(100,150, 50,50);
11. f.add(checkBox1);
12. f.add(checkBox2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String args[])
18. {
19. new CheckboxGroupExample();
20. }
21. }
Output:
Output:
Output:
Output:
Output:
29. }
30. }
Output:
Output:
11. { Output:
12. public void actionPerformed( ActionEven
te) Screen resolution = 96
13. { Screen width = 1366
14. DialogExample.d.setVisible(false); Screen height = 768
15. }
16. });
17. d.add( new Label ("Click button to continue.
")); Java AWT Toolkit Example:
18.
19.
d.add(b);
d.setSize(300,300);
beep()
20. d.setVisible(true);
21. } 1. import java.awt.event.*;
22. public static void main(String args[]) 2. public class ToolkitExample {
23. { 3. public static void main(String[] args) {
24. new DialogExample(); 4. Frame f=new Frame("ToolkitExample");
25. } 5. Button b=new Button("beep");
26. } 6. b.setBounds(50,100,60,30);
7. f.add(b);
8. f.setSize(300,300);
Output: 9. f.setLayout(null);
10. f.setVisible(true);
11. b.addActionListener(new ActionListener(){
12. public void actionPerformed(ActionEvent e)
{
13. Toolkit.getDefaultToolkit().beep();
14. }
15. });
16. }
17. }
Output:
Output:
Output:
17. checkBox2.addItemListener(this);
18. f.setSize(400,400);
19. f.setLayout(null);
20. f.setVisible(true);
21. }
22. public void itemStateChanged(ItemEvent e) {
23. if(e.getSource()==checkBox1)
24. label.setText("C++ Checkbox: "
25. + (e.getStateChange()==1?"checked":"un
checked"));
26. if(e.getSource()==checkBox2)
27. label.setText("Java Checkbox: "
28. + (e.getStateChange()==1?"checked":"unch
ecked"));
29. }
30. public static void main(String args[])
31. {
32. new ItemListenerExample();
33. }
Java ItemListener Interface 34. }
itemStateChanged() method
The itemStateChanged() method is invoked
automatically whenever you click or unclick on the
registered checkbox component.
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
javax.swing.event Adapter
classes
Adapter class Listener interface
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
Output:
Java MouseMotionAdapter
Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseMotionAdapterExample exten
Java MouseAdapter Example ds MouseMotionAdapter{
4. Frame f;
1. import java.awt.*; 5. MouseMotionAdapterExample(){
2. import java.awt.event.*; 6. f=new Frame("Mouse Motion Adapter");
3. public class MouseAdapterExample extends Mou 7. f.addMouseMotionListener(this);
seAdapter{ 8.
4. Frame f; 9. f.setSize(300,300);
5. MouseAdapterExample(){ 10. f.setLayout(null);
6. f=new Frame("Mouse Adapter"); 11. f.setVisible(true);
7. f.addMouseListener(this); 12. }
8. 13. public void mouseDragged(MouseEvent e) {
9. f.setSize(300,300); 14. Graphics g=f.getGraphics();
10. f.setLayout(null); 15. g.setColor(Color.ORANGE);
11. f.setVisible(true); 16. g.fillOval(e.getX(),e.getY(),20,20);
12. } 17. }
13. public void mouseClicked(MouseEvent e) { 18. public static void main(String[] args) {
14. Graphics g=f.getGraphics(); 19. new MouseMotionAdapterExample();
15. g.setColor(Color.BLUE); 20. }
16. g.fillOval(e.getX(),e.getY(),30,30); 21. }
17. }
18. Output:
19. public static void main(String[] args) {
20. new MouseAdapterExample();
21. }
22. }
Output:
Java KeyAdapter Example
1. import java.awt.*; How to close AWT Window in
2. import java.awt.event.*;
3. public class KeyAdapterExample extends KeyAd Java
apter{
4. Label l; We can close the AWT Window or Frame by calling
5. TextArea area; dispose() or System.exit() inside windowClosing()
6. Frame f;
method. The windowClosing() method is found in
7. KeyAdapterExample(){
8. f=new Frame("Key Adapter"); WindowListener interface and WindowAdapter
9. l=new Label(); class.
10. l.setBounds(20,50,200,20);
11. area=new TextArea(); The WindowAdapter class implements
12. area.setBounds(20,80,300, 300); WindowListener interfaces. It provides the default
13. area.addKeyListener(this); implementation of all the 7 methods of
14. WindowListener interface. To override the
15. f.add(l);f.add(area); windowClosing() method, you can either use
16. f.setSize(400,400); WindowAdapter class or WindowListener interface.
17. f.setLayout(null);
18. f.setVisible(true);
19. } If you implement the WindowListener interface, you
20. public void keyReleased(KeyEvent e) { will be forced to override all the 7 methods of
21. String text=area.getText(); WindowListener interface. So it is better to use
22. String words[]=text.split("\\s"); WindowAdapter class.
23. l.setText("Words: "+words.length+" Charact
ers:"+text.length());
24. }
Different ways to override
25. windowClosing() method
26. public static void main(String[] args) {
27. new KeyAdapterExample(); There are many ways to override windowClosing()
28. }
method:
29. }
• By anonymous class
Output: • By inheriting WindowAdapter class
• By implementing WindowListener interface
File: FirstSwingExample.java
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFr 11.
ame 12. f.setSize(400,500);//400 width and 500 height
5. 13. f.setLayout(null);//using no layout managers
6. JButton b=new JButton("click");//creating instan 14. f.setVisible(true);//making the frame visible
ce of JButton 15. }
7. b.setBounds(130,100,100, 40);//x axis, y axis, wi 16.
dth, height 17. public static void main(String[] args) {
8. 18. new Simple();
9. f.add(b);//adding button in JFrame 19. }
10. 20. }
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers The setBounds(int xaxis, int yaxis, int width, int
13. f.setVisible(true);//making the frame visible height)is used in the above example that sets the
14. } position of the button.
15. }
File: Simple2.java
1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting
JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,100,100, 40);
7.
8. add(b);//adding button on frame
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. }
13. public static void main(String[] args) {
14. new Simple2();
15. }}
Example of Swing by Association inside
constructor
Java Applet
We can also write all the codes of creating JFrame,
JButton and method call inside the java constructor. Applet is a special type of program that is embedded
in the webpage to generate the dynamic content. It
File: Simple.java runs inside the browser and works at client side.
• Plugin is required at client browser to execute There are two ways to run an applet
applet.
1. By html file.
Hierarchy of Applet 2. By appletViewer tool (for testing purpose).
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }
myapplet.html
Example of Painting in Applet: JLabel(String s, Icon Creates a JLabel instance with the
i, int specified text, image, and
1. import java.awt.*; horizontalAlignment) horizontal alignment.
2. import java.awt.event.*;
3. import java.applet.*;
4. public class MouseDrag extends Applet impleme
nts MouseMotionListener{ Commonly used Methods:
5. Methods Description
6. public void init(){
7. addMouseMotionListener(this); t returns the text string that a
8. setBackground(Color.red); String getText()
label displays.
9. }
10. void setText(String It defines the single line of text
11. public void mouseDragged(MouseEvent me){ text) this component will display.
12. Graphics g=getGraphics();
13. g.setColor(Color.white); void
14. g.fillOval(me.getX(),me.getY(),5,5); It sets the alignment of the
setHorizontalAlignme
15. } label's contents along the X axis.
16. public void mouseMoved(MouseEvent me){} nt (int alignment)
17.
18. } It returns the graphic image that
Icon getIcon()
the label displays.
In the above example, getX() and getY() method of int getHorizontal It returns the alignment of the
MouseEvent is used to get the current x-axis and y-axis. Alignment() label's contents along the X axis.
The getGraphics() method of Component class returns
the object of Graphics.
myapplet.html Java JLabel Example
1. <html> 1. import javax.swing.*;
2. <body> 2. class LabelExample
3. {
4. public static void main(String args[]) 20. try{
5. { 21. String host=tf.getText();
6. JFrame f= new JFrame("Label Example"); 22. String ip=java.net.InetAddress.getByName(
7. JLabel l1,l2; host).getHostAddress();
8. l1=new JLabel("First Label."); 23. l.setText("IP of "+host+" is: "+ip);
9. l1.setBounds(50,50, 100,30); 24. }catch(Exception ex){System.out.println(ex
10. l2=new JLabel("Second Label."); );}
11. l2.setBounds(50,100, 100,30); 25. }
12. f.add(l1); f.add(l2); 26. public static void main(String[] args) {
13. f.setSize(300,300); 27. new LabelExample();
14. f.setLayout(null); 28. }}
15. f.setVisible(true);
16. } Output:
17. }
Output:
Java JTextField
The object of a JTextField class is a text component
that allows the editing of a single line text. It inherits
JTextComponent class.
Java JLabel Example with
ActionListener Commonly used Methods:
1. import javax.swing.*; Methods Description
2. import java.awt.*;
3. import java.awt.event.*; void It is used to add the specified
4. public class LabelExample extends Frame imple addActionListener action listener to receive action
ments ActionListener{ (ActionListener l) events from this textfield.
5. JTextField tf; JLabel l; JButton b;
6. LabelExample(){ It returns the currently set Action
7. tf=new JTextField(); Action getAction() for this ActionEvent source, or
8. tf.setBounds(50,50, 150,20); null if no Action is set.
9. l=new JLabel();
10. l.setBounds(50,100, 250,20); void setFont(Font f) It is used to set the current font.
11. b=new JButton("Find IP");
12. b.setBounds(50,150,95,30); It is used to remove the specified
13. b.addActionListener(this); void
action listener so that it no longer
14. add(b);add(tf);add(l); removeActionListener
receives action events from this
15. setSize(400,400); (ActionListener l)
textfield.
16. setLayout(null);
17. setVisible(true);
18. }
19. public void actionPerformed(ActionEvent e) {
Java JTextField Example
1. import javax.swing.*; 15. b1=new JButton("+");
2. class TextFieldExample 16. b1.setBounds(50,200,50,50);
3. { 17. b2=new JButton("-");
4. public static void main(String args[]) 18. b2.setBounds(120,200,50,50);
5. { 19. b1.addActionListener(this);
6. JFrame f= new JFrame("TextField Example"); 20. b2.addActionListener(this);
21. f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.ad
7. JTextField t1,t2; d(b2);
8. t1=new JTextField("Welcome to Javatpoint."); 22. f.setSize(300,300);
23. f.setLayout(null);
9. t1.setBounds(50,100, 200,30); 24. f.setVisible(true);
10. t2=new JTextField("AWT Tutorial"); 25. }
11. t2.setBounds(50,150, 200,30); 26. public void actionPerformed(ActionEvent e) {
12. f.add(t1); f.add(t2);
13. f.setSize(400,400); 27. String s1=tf1.getText();
14. f.setLayout(null); 28. String s2=tf2.getText();
15. f.setVisible(true); 29. int a=Integer.parseInt(s1);
16. } 30. int b=Integer.parseInt(s2);
17. } 31. int c=0;
32. if(e.getSource()==b1){
Output: 33. c=a+b;
34. }else if(e.getSource()==b2){
35. c=a-b;
36. }
37. String result=String.valueOf(c);
38. tf3.setText(result);
39. }
40. public static void main(String[] args) {
41. new TextFieldExample();
42. } }
Output:
void setText(String s)
It is used to set specified Java JButton Example with
text on button
ActionListener
It is used to return the text
String getText() 1. import java.awt.event.*;
of the button.
2. import javax.swing.*;
3. public class ButtonExample {
void setEnabled(boolean It is used to enable or
4. public static void main(String[] args) {
b) disable the button.
5. JFrame f=new JFrame("Button Example");
6. final JTextField tf=new JTextField();
It is used to set the
7. tf.setBounds(50,50, 150,20);
void setIcon(Icon b) specified Icon on the 8. JButton b=new JButton("Click Here");
button. 9. b.setBounds(50,100,95,30);
10. b.addActionListener(new ActionListener(){
It is used to get the Icon of 11. public void actionPerformed(ActionEvent e){
Icon getIcon()
the button. 12. tf.setText("Welcome to Javatpoint.");
13. }
It is used to set the 14. });
void setMnemonic(int a)
mnemonic on the button. 15. f.add(b);f.add(tf);
16. f.setSize(400,400);
void addActionListener It is used to add the action 17. f.setLayout(null);
(ActionListener a) listener to this object. 18. f.setVisible(true);
19. }
20. }
Java JButton Example Output:
1. import javax.swing.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton("Click Here");
6. b.setBounds(50,100,95,30);
7. f.add(b);
Java JToggleButton
JToggleButton is used to create toggle button, it is
two-states button to switch on or off.
Nested Classes
Type Class Description
Methods
Example of displaying image on Modifier
Method Description
and Type
the button:
getAccessi It gets the AccessibleContext
1. import javax.swing.*; Accessible
bleContext( associated with this
2. public class ButtonExample{ Context
) JToggleButton.
3. ButtonExample(){
4. JFrame f=new JFrame("Button Example");
It returns a string that
5. JButton b=new JButton(new ImageIcon("D:\\ico getUIClassI specifies the name of the l&f
String
n.png")); D() class that renders this
6. b.setBounds(100,100,100, 40); component.
7. f.add(b);
8. f.setSize(300,400); It returns a string
protected paramStrin
9. f.setLayout(null); representation of this
String g()
10. f.setVisible(true); JToggleButton.
11. f.setDefaultCloseOperation(JFrame.EXIT_ON_C
LOSE); It resets the UI property to a
12. } void updateUI() value from the current look
13. public static void main(String[] args) { and feel.
14. new ButtonExample();
15. }
16. }
Output:
Java JCheckBox
The JCheckBox class is used to create a checkbox. It
is used to turn an option on (true) or off (false).
Clicking on a CheckBox changes its state from "on"
to "off" or from "off" to "on ".It inherits
JToggleButton class.
void
It is used to enable or disable
setEnabled(boolean
the button.
b)
Output:
Java JList
The object of JList class represents a list of text
items. The list of text items can be set up so that the
user can choose either one item or multiple items. It
inherits JComponent class.
It is used to return the The object of Choice class is used to show popup
int getSelectedIndex() menu of choices. Choice selected by user is shown
smallest selected cell index.
on the top of a menu. It inherits JComponent class.
It is used to return the data
model that holds a list of
ListModel getModel()
items displayed by the JList
Commonly used Methods:
component.
Methods Description
void It is used to create a read-
setListData(Object[] only ListModel from an void addItem(Object It is used to add an item to the
listData) array of objects. anObject) item list.
Output:
12. {
13. public void actionPerformed( ActionEven
te)
14. {
15. DialogExample.d.setVisible(false);
16. }
17. });
18. d.add( new JLabel ("Click button to continu
e."));
19. d.add(b);
20. d.setSize(300,300);
21. d.setVisible(true);
22. }
23. public static void main(String args[])
24. {
25. new DialogExample();
26. }
27. }
Output: