JAVA Unit 4 5 Course Material 2
JAVA Unit 4 5 Course Material 2
UNIT IV
Collections in Java
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
o It is optional.
2. Algorithm
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
There are only three methods in the Iterator interface. They are:
2 public Object next() It returns the element and moves the cursor pointer to the
next element.
3 public void remove() It removes the last elements returned by the iterator. It is
less used.
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The
Collection interface extends the Iterable interface and therefore all the subclasses of
Collection interface also implement the Iterable interface.
1. Iterator<T> iterator()
Some of the methods of Collection interface are Boolean add ( Objectobj), Boolean
addAll ( Collection c), void clear(), etc. which are implemented by all the subclasses
of Collection interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data
structure in which we can store the ordered collection of objects. It can have
duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
There are various methods in List interface that can be used to insert, delete, and
access the elements from the list.
The classes that implement the List interface are given below.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store
the duplicate element of different data types. The ArrayList class maintains the
insertion order and is non-synchronized. The elements stored in the ArrayList class
can be randomly accessed. Consider the following example.
1. import java.util.*;
2. class TestJavaCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
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. }
15. }
Output:
Ravi
Vijay
Ravi
Ajay
Method Description
void add(int index, E element) It is used to insert the specified element at the
specified position in a list.
boolean addAll(int index, Collection<? It is used to append all the elements in the
extends E> c) specified collection, starting at the specified
position of the list.
Iterator()
listIterator()
int lastIndexOf(Object o) It is used to return the index in this list of the last
occurrence of the specified element, or -1 if the list
does not contain this element.
int indexOf(Object o) It is used to return the index in this list of the first
occurrence of the specified element, or -1 if the List
does not contain this element.
boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.
booleanremoveIf(Predicate<? super E> It is used to remove all the elements from the list
filter) that satisfies the given predicate.
protected void removeRange(int It is used to remove all the elements lies within the
fromIndex, int toIndex) given range.
void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list
operator) with the specified element.
void retainAll(Collection<?> c) It is used to retain all the elements in the list that
are present in the specified collection.
void sort(Comparator<? super E> c) It is used to sort the elements of the list on the
basis of specified comparator.
List<E>subList(int fromIndex, int It is used to fetch all the elements lies within the
toIndex) given range.
Example
cars.set(0,"Opel");
Remove an Item
To remove an element, use the remove() method and refer to the index
number:
Example
cars.remove(0);
To remove all the elements in the ArrayList, use the clear() method:
Example
cars.clear();
ArrayList Size
To find out how many elements an ArrayList have, use the size method:
Example
cars.size();
Loop Through an ArrayList
Loop through the elements of an ArrayList with a for loop, and use
the size() method to specify how many times the loop should run:
Example
publicclassMain{
publicstaticvoidmain(String[]args){
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
for(inti=0;i<cars.size();i++){
System.out.println(cars.get(i));
You can also loop through an ArrayList with the for-each loop:
Example
publicclassMain{
publicstaticvoidmain(String[]args){
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
for(Stringi: cars){
System.out.println(i);
Other Types
Elements in an ArrayList are actually objects. In the examples above, we
created elements (objects) of type "String". Remember that a String in Java
is an object (not a primitive type). To use other types, such as int, you must
specify an equivalent wrapper class: Integer. For other primitive types,
use: Boolean for boolean, Character for char, Double for double, etc:
Example
Create an ArrayList to store numbers (add elements of type Integer):
importjava.util.ArrayList;
publicclassMain{
publicstaticvoidmain(String[]args){
ArrayList<Integer>myNumbers=newArrayList<Integer>();
myNumbers.add(10);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(25);
for(inti:myNumbers){
System.out.println(i);
}
}
Sort an ArrayList
Another useful class in the java.util package is the Collections class, which
include the sort() method for sorting lists alphabetically or numerically:
Example
Sort an ArrayList of Strings:
importjava.util.ArrayList;
publicclassMain{
publicstaticvoidmain(String[]args){
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
for(Stringi: cars){
System.out.println(i);
}
Example
Sort an ArrayList of Integers:
importjava.util.ArrayList;
publicclassMain{
publicstaticvoidmain(String[]args){
ArrayList<Integer>myNumbers=newArrayList<Integer>();
myNumbers.add(33);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(34);
myNumbers.add(8);
myNumbers.add(12);
for(inti:myNumbers){
System.out.println(i);
LinkedList
Method Description
1. import java.util.*;
2. public class LinkedList1{
3. public static void main(String args[]){
4.
5. LinkedList<String> al=new LinkedList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output: Ravi
Vijay
Ravi
Ajay
1. import java.util.*;
2. public class LinkedList3 {
3.
4. public static void main(String [] args)
5. {
6. LinkedList<String> ll=new LinkedList<String>();
7. ll.add("Ravi");
8. ll.add("Vijay");
9. ll.add("Ajay");
10. ll.add("Anuj");
11. ll.add("Gaurav");
12. ll.add("Harsh");
13. ll.add("Virat");
14. ll.add("Gaurav");
15. ll.add("Harsh");
16. ll.add("Amit");
17. System.out.println("Initial list of elements: "+ll);
18. //Removing specific element from arraylist
19. ll.remove("Vijay");
20. System.out.println("After invoking remove(object) method: "+ll);
21. //Removing element on the basis of specific position
22. ll.remove(0);
23. System.out.println("After invoking remove(index) method: "+ll);
24. LinkedList<String> ll2=new LinkedList<String>();
25. ll2.add("Ravi");
26. ll2.add("Hanumat");
27. // Adding new elements to arraylist
28. ll.addAll(ll2);
29. System.out.println("Updated list : "+ll);
30. //Removing all the new elements from arraylist
31. ll.removeAll(ll2);
32. System.out.println("After invoking removeAll() method: "+ll);
33. //Removing first element from the list
34. ll.removeFirst();
35. System.out.println("After invoking removeFirst() method: "+ll);
36. //Removing first element from the list
37. ll.removeLast();
38. System.out.println("After invoking removeLast() method: "+ll);
39. //Removing first occurrence of element from the list
40. ll.removeFirstOccurrence("Gaurav");
41. System.out.println("After invoking removeFirstOccurrence() method
: "+ll);
42. //Removing last occurrence of element from the list
43. ll.removeLastOccurrence("Harsh");
44. System.out.println("After invoking removeLastOccurrence() method
: "+ll);
45.
46. //Removing all the elements available in the list
47. ll.clear();
48. System.out.println("After invoking clear() method: "+ll);
49. }
50. }
Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh,
Virat, Gaurav, Harsh, Amit]
After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit,
Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh,
Amit]
After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]
After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav,
Harsh]
After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]
After invoking clear() method: []
1. import java.util.*;
2. public class LinkedList4{
3. public static void main(String args[]){
4.
5. LinkedList<String> ll=new LinkedList<String>();
6. ll.add("Ravi");
7. ll.add("Vijay");
8. ll.add("Ajay");
9. //Traversing the list of elements in reverse order
10. Iterator i=ll.descendingIterator();
11. while(i.hasNext())
12. {
13. System.out.println(i.next());
14. }
15.
16. }
17. }
Output: Ajay
Vijay
Ravi
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 LinkedListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new LinkedList<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:
LinkedList implements the Collection interface. It uses a doubly linked list internally
to store the elements. It can store the duplicate elements. It maintains the insertion
order and is not synchronized. In LinkedList, the manipulation is fast because no
shifting is required.
Output:
Ravi
Vijay
Ravi
Ajay
ArrayList and LinkedList both implements List interface and maintains insertion
order. Both are non synchronized classes.
However, there are many differences between ArrayList and LinkedList classes that
are given below.
ArrayList LinkedList
3) An ArrayList class can act as a list only LinkedList class can act as a list and
because it implements List only. queue both because it implements List and
Deque interfaces.
4) ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.
Vector
Constructors:
// working of Vector
importjava.io.*;
importjava.util.*;
classVectorExample {
publicstaticvoidmain(String[] args)
// Size of the
// Vector
intn = 5;
// initial size n
Vector<Integer> v = newVector<Integer>(n);
v.add(i);
// Printing elements
System.out.println(v);
v.remove(3);
// after deletion
System.out.println(v);
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
importjava.util.*;
importjava.io.*;
classAddElementsToVector {
publicstaticvoidmain(String[] arg)
Vector v1 = newVector();
v1.add(1);
v1.add(2);
v1.add("geeks");
v1.add("forGeeks");
v1.add(3);
Vector<Integer> v2 = newVector<Integer>();
v2.add(1);
v2.add(2);
v2.add(3);
Output:
Vector v1 is [1, 2, geeks, forGeeks, 3]
Vector v2 is [1, 2, 3]
2. Changing Elements: After adding the elements, if we wish to change the
element, it can be done using the set() method. Since a Vector is indexed,
the element which we wish to change is referenced by the index of the
element. Therefore, this method takes an index and the updated element
which needs to be inserted at that index.
• Java
importjava.util.*;
publicclassUpdatingVector {
publicstaticvoidmain(String args[])
Vector<Integer>vec_tor = newVector<Integer>();
vec_tor.add(12);
vec_tor.add(23);
vec_tor.add(22);
vec_tor.add(10);
vec_tor.add(20);
// Displaying the Vector
+ vec_tor.set(0, 21));
+ vec_tor.set(4, 50));
Output
Vector: [12, 23, 22, 10, 20]
The Object that is replaced is: 12
The Object that is replaced is: 20
The new Vector is:[21, 23, 22, 10, 50]
3. Removing Elements: In order to remove an element from a Vector, we
can use the remove() method. This method is overloaded to perform multiple
operations based on different parameters. They are:
• remove(Object): This method is used to simply remove an object
from the Vector. If there are multiple such objects, then the first
occurrence of the object is removed.
• remove(int index): Since a Vector is indexed, this method takes an
integer value which simply removes the element present at that
specific index in the Vector. After removing the element, all the
elements are moved to the left to fill the space and the indices of
the objects are updated.
• Java
importjava.util.*;
importjava.io.*;
classRemovingElementsFromVector {
publicstaticvoidmain(String[] arg)
Vector v = newVector();
v.add(2);
v.add("Geeks");
v.add("forGeeks");
v.add(4);
v.remove(1);
// checking vector
Output:
importjava.util.*;
publicclassIteratingVector {
publicstaticvoidmain(String args[])
Vector<String> v = newVector<>();
v.add("Geeks");
v.add("Geeks");
v.add(1, "For");
// for loop
System.out.println();
for(String str : v)
Output
Geeks For Geeks
Geeks For Geeks
Important points regarding Increment of vector capacity:
If the increment is specified, Vector will expand according to it in each
allocation cycle but if the increment is not specified then the vector’s capacity
gets doubled in each allocation cycle. Vector defines three protected data
member:
•
int capacityIncreament: Contains the increment value.
•
int elementCount: Number of elements currently in vector stored
in it.
• Object elementData[]: Array that holds the vector is stored in it.
Common Errors in Declaration of Vectors
• Vector throws an IllegalArgumentException if the InitialSize of the
vector defined is negative.
• If the specified collection is null, It throws NullPointerException.
insertElementAt(E obj, int Inserts the specified object as a component in this vector
index) at the specified index.
Vector uses a dynamic array to store the data elements. It is similar to ArrayList.
However, It is synchronized and contains many methods that are not the part of
Collection framework.
Output:
Ayush
Amit
Ashish
Garima
Stack
n order to create a stack, we must import java.util.stack package and use
the Stack() constructor of this class. The below example creates an empty
Stack.
Stack<E> stack = new Stack<E>();
Here E is the type of Object.
Example:
• Java
importjava.io.*;
importjava.util.*;
classTest
{
staticvoidstack_push(Stack<Integer> stack)
stack.push(i);
staticvoidstack_pop(Stack<Integer> stack)
System.out.println("Pop Operation:");
System.out.println(y);
}
// Displaying element on the top of the stack
staticvoidstack_peek(Stack<Integer> stack)
if(pos == -1)
else
System.out.println("Element is found at
position: "+ pos);
}
publicstaticvoidmain (String[] args)
stack_push(stack);
stack_pop(stack);
stack_push(stack);
stack_peek(stack);
stack_search(stack, 2);
stack_search(stack, 6);
Output:
Pop Operation:
4
3
2
1
0
Element on stack top: 4
Element is found at position: 3
Element not found
• Java
importjava.io.*;
importjava.util.*;
classStackDemo {
// Main Method
publicstaticvoidmain(String[] args)
// Initialization of Stack
// using Generics
stack1.push(4);
stack1.push("All");
stack1.push("Geeks");
stack2.push("Geeks");
stack2.push("For");
stack2.push("Geeks");
System.out.println(stack1);
System.out.println(stack2);
Output:
[4, All, Geeks]
[Geeks, For, Geeks]
2. Accessing the Element: To retrieve or fetch the first element of the Stack
or the element present at the top of the Stack, we can use peek() method.
The element retrieved does not get deleted or removed from the Stack.
• Java
// Java program to demonstrate the accessing
importjava.util.*;
importjava.io.*;
publicclassStackDemo {
// Main Method
publicstaticvoidmain(String args[])
stack.push("Welcome");
stack.push("To");
stack.push("Geeks");
stack.push("For");
stack.push("Geeks");
// Displaying the Stack
Output:
Initial Stack: [Welcome, To, Geeks, For, Geeks]
The element at the top of the stack is: Geeks
Final Stack: [Welcome, To, Geeks, For, Geeks]
3. Removing Elements: To pop an element from the stack, we can use
the pop() method. The element is popped from the top of the stack and is
removed from the same.
• Java
importjava.util.*;
importjava.io.*;
publicclassStackDemo {
publicstaticvoidmain(String args[])
stack.push(10);
stack.push(15);
stack.push(30);
stack.push(20);
stack.push(5);
+ stack.pop());
+ stack);
Output:
Initial Stack: [10, 15, 30, 20, 5]
Popped element: 5
Popped element: 20
Stack after pop operation [10, 15, 30]
METHOD DESCRIPTION
It returns true if nothing is on the top of the stack. Else, returns false.
empty()
The stack is the subclass of Vector. It implements the last-in-first-out data structure,
i.e., Stack. The stack contains all of the methods of Vector class and also provides
its methods like booleanpush(), boolean peek(), boolean push(object o), which
defines its properties.
1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ayush
Garvit
Amit
Ashish
Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an
ordered list that is used to hold the elements which are about to be processed.
There are various classes like PriorityQueue, Deque, and ArrayDeque which
implements the Queue interface.
There are various classes that implement the Queue interface, some of them are
given below.
PriorityQueue
PriorityQueue in Java
A PriorityQueue is used when the objects are supposed to be processed
based on the priority. It is known that a Queue follows the First-In-First-Out
algorithm, but sometimes the elements of the queue are needed to be
processed according to the priority, that’s when the PriorityQueue comes into
play. The PriorityQueue is based on the priority heap. The elements of the
priority queue are ordered according to the natural ordering, or by a
Comparator provided at queue construction time, depending on which
constructor is used.
In the below priority queue, an element with maximum ASCII value will have
the highest priority.
Declaration:
The class
implements Serializable, Iterable<E>, Collection<E>, Queue<E> interfaces
.
Few important points on Priority Queue are as follows:
• PriorityQueue doesn’t permit null.
• We can’t create PriorityQueue of Objects that are non-comparable
• PriorityQueue are unbound queues.
• The head of this queue is the least element with respect to the
specified ordering. If multiple elements are tied for least value, the
head is one of those elements — ties are broken arbitrarily.
• Since PriorityQueue is not thread-safe, so java
provides PriorityBlockingQueue class that implements
the BlockingQueue interface to use in java multithreading
environment.
• The queue retrieval operations poll, remove, peek,
and element access the element at the head of the queue.
• It provides O(log(n)) time for add and poll methods.
The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow null
values to be stored in the queue.
1. import java.util.*;
2. public class TestJavaCollection5{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit Sharma");
6. queue.add("Vijay Raj");
7. queue.add("JaiShankar");
8. queue.add("Raj");
9. System.out.println("head:"+queue.element());
10. System.out.println("head:"+queue.peek());
11. System.out.println("iterating the queue elements:");
12. Iterator itr=queue.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. queue.remove();
17. queue.poll();
18. System.out.println("after removing two elements:");
19. Iterator<String> itr2=queue.iterator();
20. while(itr2.hasNext()){
21. System.out.println(itr2.next());
22. }
23. }
24. }
Output:
head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj
Deque Interface
• Java
// ArrayDeque in Java
importjava.util.*;
publicclassArrayDequeDemo
publicstaticvoidmain(String[] args)
{
// Initializing an deque
Deque<Integer>de_que = newArrayDeque<Integer>(10);
de_que.add(10);
de_que.add(20);
de_que.add(30);
de_que.add(40);
de_que.add(50);
// clear() method
de_que.clear();
de_que.addFirst(291);
de_que.addLast(24);
de_que.addLast(14);
// Iterator() :
System.out.println(itr.next());
dItr.hasNext();)
{
System.out.println(dItr.next());
de_que.element());
de_que.getFirst());
de_que.getLast());
// toArray() method :
// push() method :
de_que.push(265);
de_que.push(984);
de_que.push(2365);
Output:
Element : 10
Element : 20
Element : 30
Element : 40
Element : 50
Using clear()
Above elements are removed now
Elements of deque using Iterator :
291
564
24
14
Elements of deque in reverse order :
14
24
564
291
Array Size : 4
Array elements : 291 564 24 14
Head element : 291
Head element poll : 291
Head element remove : 2365
The final array is: [984, 265, 564, 24, 14]
Let’s see how to perform a few frequently used operations on the ArrayDeque.
1. Adding Elements: In order to add an element to the ArrayDeque, we can use
the methods add(), addFirst(), addLast(), offer(), offerFirst(), offerLast()
methods.
• add()
• addFirst()
• addLast()
• offer()
• offerFirst()
• offerLast()
• Java
importjava.io.*;
importjava.util.*;
publicclassAddingElementsToArrayDeque {
publicstaticvoidmain(String[] args)
// Initializing a deque
// it is assigned the
// ArrayDeque class
Deque<String>dq = newArrayDeque<String>();
// add() method to insert
dq.add("The");
dq.addFirst("To");
dq.addLast("Geeks");
dq.offer("For");
dq.offerFirst("Welcome");
dq.offerLast("Geeks");
Output:
ArrayDeque : [Welcome, To, The, Geeks, For, Geeks]
2. Accessing the Elements: After adding the elements, if we wish to access the
elements, we can use inbuilt methods like getFirst(), getLast(), etc.
• getFirst()
• getLast()
• peek()
• peekFirst()
• peekLast()
• Java
// Java program to access the
// elements of ArrayDeque
importjava.util.*;
importjava.io.*;
publicclassAccessingElementsOfArrayDeque {
publicstaticvoidmain(String args[])
ArrayDeque<String>de_que
= newArrayDeque<String>();
de_que.add("Welcome");
de_que.add("To");
de_que.add("Geeks");
de_que.add("4");
de_que.add("Geeks");
+ de_que.getFirst());
+ de_que.getLast());
Output:
ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
The first element is: Welcome
The last element is: Geeks
3. Removing Elements: In order to remove an element from a deque, there are
various methods available. Since we can also remove from both the ends, the
deque interface provides us with removeFirst(), removeLast() methods. Apart
from that, this interface also provides us with
the poll(), pop(), pollFirst(), pollLast() methods where pop() is used to remove
and return the head of the deque. However, poll() is used because this offers the
same functionality as pop() and doesn’t return an exception when the deque is
empty.
• remove()
• removeFirst()
• removeLast()
• poll()
• pollFirst()
• pollLast()
• pop()
• Java
importjava.util.*;
publicclassRemoveElementsOfArrayDeque {
publicstaticvoidmain(String[] args)
// Initializing a deque
Deque<String>dq = newArrayDeque<String>();
dq.add("One");
dq.addFirst("Two");
System.out.println(dq.pop());
System.out.println(dq.poll());
System.out.println(dq.pollFirst());
System.out.println(dq.pollLast());
Output:
• Java
importjava.util.*;
publicclassIterateArrayDeque {
publicstaticvoidmain(String[] args)
// Initializing an deque
Deque<String>dq = newArrayDeque<String>();
// at the back
dq.add("For");
// add element at the front
dq.addFirst("Geeks");
dq.addLast("Geeks");
dq.add("is so good");
System.out.println();
// Iterate in reverse
// sequence in a queue
itr.hasNext();) {
Output:
Geeks For Geeks is so good
is so good Geeks For Geeks
Methods in ArrayDeque
METHOD DESCRIPTION
removeFirst() The method returns the first element and also removes it
removeIf(Predicate<? super Removes all of the elements of this collection that satisfy
Element> filter) the given predicate.
removeLast() The method returns the last element and also removes it
METHOD DESCRIPTION
Retrieves, but does not remove, the first element of this deque,
peekFirst() or returns null if this deque is empty.
Retrieves, but does not remove, the last element of this deque,
peekLast() or returns null if this deque is empty.
Gautam
Karan
Ajay
Set Interface
Java HashSet class is used to create a collection that uses a hash table for storage.
It inherits the AbstractSet class and implements Set interface.
o HashSet doesn't maintain the insertion order. Here, elements are inserted on
the basis of their hashcode.
o The initial default capacity of HashSet is 16, and the load factor is 0.75.
SN Constructor Description
2) HashSet(int capacity) It is used to initialize the capacity of the hash set to the
given integer value capacity. The capacity grows
automatically as elements are added to the HashSet.
3) HashSet(int capacity, float It is used to initialize the capacity of the hash set to the
loadFactor) given integer value capacity and the specified load factor.
1. import java.util.*;
2. class HashSet1{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet();
6. set.add("One");
7. set.add("Two");
8. set.add("Three");
9. set.add("Four");
10. set.add("Five");
11. Iterator<String> i=set.iterator();
12. while(i.hasNext())
13. {
14. System.out.println(i.next());
15. }
16. }
17. }
Five
One
Four
Two
Three
1. import java.util.*;
2. class HashSet2{
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. }
Ajay
Vijay
Ravi
1. import java.util.*;
2. class HashSet3{
3. public static void main(String args[]){
4. HashSet<String> set=new HashSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Arun");
8. set.add("Sumit");
9. System.out.println("An initial list of elements: "+set);
10. //Removing specific element from HashSet
11. set.remove("Ravi");
12. System.out.println("After invoking remove(object) method: "+set);
13. HashSet<String> set1=new HashSet<String>();
14. set1.add("Ajay");
15. set1.add("Gaurav");
16. set.addAll(set1);
17. System.out.println("Updated List: "+set);
18. //Removing all the new elements from HashSet
19. set.removeAll(set1);
20. System.out.println("After invoking removeAll() method: "+set);
21. //Removing elements on the basis of specified condition
22. set.removeIf(str->str.contains("Vijay"));
23. System.out.println("After invoking removeIf() method: "+set);
24. //Removing all the elements available in the set
25. set.clear();
26. System.out.println("After invoking clear() method: "+set);
27. }
28. }
An initial list of elements: [Vijay, Ravi, Arun, Sumit]
After invoking remove(object) method: [Vijay, Arun, Sumit]
Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay]
After invoking removeAll() method: [Vijay, Arun, Sumit]
After invoking removeIf() method: [Arun, Sumit]
After invoking clear() method: []
1. import java.util.*;
2. class HashSet4{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("Ravi");
6. list.add("Vijay");
7. list.add("Ajay");
8.
9. HashSet<String> set=new HashSet(list);
10. set.add("Gaurav");
11. Iterator<String> i=set.iterator();
12. while(i.hasNext())
13. {
14. System.out.println(i.next());
15. }
16. }
17. }
Vijay
Ravi
Gaurav
Ajay
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 HashSetExample {
15. public static void main(String[] args) {
16. HashSet<Book> set=new HashSet<Book>();
17. //Creating Books
18. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
19. Book b2=new Book(102,"Data Communications & Networking","Forouzan"
,"Mc Graw Hill",4);
20. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
21. //Adding Books to HashSet
22. set.add(b1);
23. set.add(b2);
24. set.add(b3);
25. System.out.println(set);
26. //Traversing HashSet
27. for(Book b:set){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.
quantity);
29. }
30. }
31. }
Output:
Java HashSet
A HashSet is a collection of items where every item is unique, and it is found
in the java.util package:
Example
Create a HashSet object called cars that will store strings:
Example
// Import the HashSet class
importjava.util.HashSet;
publicclassMain{
publicstaticvoidmain(String[]args){
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("BMW");
cars.add("Mazda");
System.out.println(cars);
Try it Yourself »
Note: In the example above, even though BMW is added twice it only
appears once in the set because every item in a set has to be unique.
Example
cars.contains("Mazda");
Try it Yourself »
Remove an Item
To remove an item, use the remove() method:
Example
cars.remove("Volvo");
Try it Yourself »
Example
cars.clear();
Try it Yourself »
HashSet Size
To find out how many items there are, use the size method:
Example
cars.size();
Try it Yourself »
System.out.println(i);
Try it Yourself »
Other Types
Items in an HashSet are actually objects. In the examples above, we created
items (objects) of type "String". Remember that a String in Java is an object
(not a primitive type). To use other types, such as int, you must specify an
equivalent wrapper class: Integer. For other primitive types, use: Boolean for
boolean, Character for char, Double for double, etc:
Example
Use a HashSet that stores Integer objects:
importjava.util.HashSet;
publicclassMain{
publicstaticvoidmain(String[]args){
numbers.add(4);
numbers.add(7);
numbers.add(8);
// Show which numbers between 1 and 10 are in the set
for(inti=1;i<=10;i++){
if(numbers.contains(i)){
}else{
importjava.util.LinkedHashSet;
publicclassLinkedHashSetExample
// Main Method
publicstaticvoidmain(String[] args)
LinkedHashSet<String>linkedset =
newLinkedHashSet<String>();
linkedset.add("A");
linkedset.add("B");
linkedset.add("C");
linkedset.add("D");
linkedset.add("A");
linkedset.add("E");
System.out.println("Size of LinkedHashSet = "+
linkedset.size());
linkedset.remove("D"));
System.out.println("Checking if A is present="+
linkedset.contains("A"));
Let’s see how to perform a few frequently used operations on the LinkedHashSet.
1. Adding Elements: In order to add an element to the LinkedHashSet, we can use the add() method.
This is different from HashSet because in HashSet, the insertion order is not retained but it is
retained in the LinkedHashSet.
• Java
// elements to LinkedHashSet
import java.util.*;
import java.io.*;
class AddingElementsToLinkedHashSet {
public static void main(String[] args)
// create an instance of
// LinkedHashSet
LinkedHashSet<String>hs
= new LinkedHashSet<String>();
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
Output:
2. Removing the Elements: The values can be removed from the LinkedHashSet using
the remove() method.
• Java
// from LinkedHashSet
import java.io.*;
import java.util.*;
class RemoveElementsFromLinkedHashSet {
public static void main(String[] args)
// create an instance of
// LinkedHashSet
LinkedHashSet<String>hs
= new LinkedHashSet<String>();
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
hs.add("A");
hs.add("B");
hs.add("Z");
hs.remove("B");
System.out.println(hs.remove("AC"));
Output:
Initial HashSet [Geek, For, Geeks, A, B, Z]
false
• Java
import java.io.*;
import java.util.*;
class IteratingLinkedHashSet {
hs.add("Geek");
hs.add("For");
hs.add("Geeks");
hs.add("A");
hs.add("B");
hs.add("Z");
// Iterating though the LinkedHashSet
Iteratoritr = hs.iterator();
while (itr.hasNext())
System.out.println();
//Object
System.out.println();
Output:
Methods of LinkedHashSet
METHOD DESCRIPTION
spliterator() Creates a late-binding and fail-fast Spliterator over the elements in this set.
METHOD DESCRIPTION
equals(Object o) Compares the specified object with this set for equality.
removeAll(Collection Removes from this set all of its elements that are contained in the
c) specified collection (optional operation).
METHOD DESCRIPTION
addAll(Collection<? Adds all of the elements in the specified collection to this collection
extends E> c) (optional operation).
containsAll Returns true if this collection contains all of the elements in the specified
(Collection<?> c) collection.
retainAll(Collection<?> Retains only the elements in this collection that are contained in the
c) specified collection (optional operation).
METHOD DESCRIPTION
parallelStream() Returns a possibly parallel Stream with this collection as its source.
removeIf(Predicate<?
super
Removes all of the elements of this collection that satisfy the given
E> filter) predicate.
METHOD DESCRIPTION
METHOD DESCRIPTION
add(E e) Adds the specified element to this set if it is not already present.
Returns a shallow copy of this HashSet instance: the elements themselves are
clone() not cloned.
contains(Object
o) Returns true if this set contains the specified element.
METHOD DESCRIPTION
forEach(Consumer<?
super
Performs the given action for each element of the Iterable until all
T> action) elements have been processed or the action throws an exception.
This method is used to add a specific element to the set. The function adds
the element only if the specified element is not already present in the set
add(element) else the function returns False if the element is already present in the Set.
This method is used to append all of the elements from the mentioned
collection to the existing set. The elements are added randomly without
addAll(Collection c) following any specific order.
This method is used to remove all the elements from the set but not
clear() delete the set. The reference for the set still exists.
This method is used to check whether the set contains all the elements
present in the given collection or not. This method returns true if the set
containsAll(Collection contains all the elements and returns false if any of the elements are
c) missing.
This method is used to get the hashCode value for this instance of the Set.
It returns an integer value which is the hashCode value for this instance of
hashCode() the Set.
isEmpty() This method is used to check whether the set is empty or not.
This method is used to return the iterator of the set. The elements from
iterator() the set are returned in random order.
This method is used to remove the given element from the set. This
method returns True if the specified element is present in the Set
remove(element) otherwise it returns False.
This method is used to remove all the elements from the collection which
removeAll(collection)
are present in the set. This method returns true if this set changed as a
METHOD DESCRIPTION
This method is used to retain all the elements from the set which are
mentioned in the given collection. This method returns true if this set
retainAll(collection) changed as a result of the call.
This method is used to get the size of the set. This returns an integer value
size() which signifies the number of elements.
This method is used to form an array of the same elements as that of the
toArray() Set.
Returns an array containing all of the elements in this set; the runtime
toArray(T[] a) type of the returned array is that of the specified array.
importjava.util.Vector;
importjava.util.Enumeration;
publicclassEnumerationClass {
publicstaticvoidmain(String args[])
{
Enumeration months;
Vector<String>monthNames = newVector<>();
monthNames.add("January");
monthNames.add("Febraury");
monthNames.add("March");
monthNames.add("April");
monthNames.add("May");
monthNames.add("June");
monthNames.add("July");
monthNames.add("August");
monthNames.add("September");
monthNames.add("Octobor");
monthNames.add("November");
monthNames.add("December");
months = monthNames.elements();
while(months.hasMoreElements()) {
System.out.println(months.nextElement());
}
Output
January
Febraury
March
April
May
June
July
August
September
Octobor
November
December
HashSet
HashSet class implements Set Interface. It represents the collection that uses a
hash table for storage. Hashing is used to store the elements in the HashSet. It
contains unique items.
1. import java.util.*;
2. public class TestJavaCollection7{
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. }
Output:
Vijay
Ravi
Ajay
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It
extends the HashSet class and implements Set interface. Like HashSet, It also
contains unique elements. It maintains the insertion order and permits null
elements.
1. import java.util.*;
2. public class TestJavaCollection8{
3. public static void main(String args[]){
4. LinkedHashSet<String> set=new LinkedHashSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ravi");
8. set.add("Ajay");
9. Iterator<String> itr=set.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ravi
Vijay
Ajay
SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its
elements. The elements of the SortedSet are arranged in the increasing (ascending)
order. The SortedSet provides the additional methods that inhibit the natural
ordering of the elements.
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits
AbstractSet class and implements the NavigableSet interface. The objects of the
TreeSet class are stored in ascending order.
Constructor Description
TreeSet(Collection<? extends It is used to build a new tree set that contains the
E> c) elements of the collection c.
Method Description
1. import java.util.*;
2. class TreeSet1{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> al=new TreeSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Test it Now
Output:
C++ vs Java
Ajay
Ravi
Vijay
1. import java.util.*;
2. class TreeSet2{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ajay");
8. System.out.println("Traversing element through Iterator in descending or
der");
9. Iterator i=set.descendingIterator();
10. while(i.hasNext())
11. {
12. System.out.println(i.next());
13. }
14.
15. }
16. }
Test it Now
Output:
1. import java.util.*;
2. class TreeSet3{
3. public static void main(String args[]){
4. TreeSet<Integer> set=new TreeSet<Integer>();
5. set.add(24);
6. set.add(66);
7. set.add(12);
8. set.add(15);
9. System.out.println("Highest Value: "+set.pollFirst());
10. System.out.println("Lowest Value: "+set.pollLast());
11. }
12. }
Output:
Highest Value: 12
Lowest Value: 66
1. import java.util.*;
2. class TreeSet4{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. set.add("A");
6. set.add("B");
7. set.add("C");
8. set.add("D");
9. set.add("E");
10. System.out.println("Initial Set: "+set);
11.
12. System.out.println("Reverse Set: "+set.descendingSet());
13.
14. System.out.println("Head Set: "+set.headSet("C", true));
15.
16. System.out.println("SubSet: "+set.subSet("A", false, "E", true));
17.
18. System.out.println("TailSet: "+set.tailSet("C", false));
19. }
20. }
Output:
1. import java.util.*;
2. class TreeSet4{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. set.add("A");
6. set.add("B");
7. set.add("C");
8. set.add("D");
9. set.add("E");
10.
11. System.out.println("Intial Set: "+set);
12.
13. System.out.println("Head Set: "+set.headSet("C"));
14.
15. System.out.println("SubSet: "+set.subSet("A", "E"));
16.
17. System.out.println("TailSet: "+set.tailSet("C"));
18. }
19. }
Output:
Intial Set: [A, B, C, D, E]
Head Set: [A, B]
SubSet: [A, B, C, D]
TailSet: [C, D, E]
1. import java.util.*;
2. class Book implements Comparable<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. public int compareTo(Book b) {
14. if(id>b.id){
15. return 1;
16. }else if(id<b.id){
17. return -1;
18. }else{
19. return 0;
20. }
21. }
22. }
23. public class TreeSetExample {
24. public static void main(String[] args) {
25. Set<Book> set=new TreeSet<Book>();
26. //Creating Books
27. Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
28. Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
29. Book b3=new Book(101,"Data Communications & Networking","Forouzan",
"Mc Graw Hill",4);
30. //Adding Books to TreeSet
31. set.add(b1);
32. set.add(b2);
33. set.add(b3);
34. //Traversing TreeSet
35. for(Book b:set){
36. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.qu
antity);
37. }
38. }
39. }
Output:
1. import java.util.*;
2. public class TestJavaCollection9{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> set=new TreeSet<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. }
Output:
Ajay
Ravi
Vijay
importjava.util.*;
publicclassMain
publicstaticvoidmain(String[] args)
Date d1 = newDate();
Date d2 = newDate(2323223232L);
Output:
Current date is Tue Jul 12 18:35:37 IST 2016
Date represented is Wed Jan 28 02:50:23 IST 1970
Important Methods
• booleanafter(Date date) : Tests if current date is after the
given date.
• D1//current date
• D2// previous date
• D2.after(d1);//false
• booleanbefore(Date date) : Tests if current date is before
the given date.
• int compareTo(Date date) : Compares current date with
given date. Returns 0 if the argument Date is equal to the
Date; a value less than 0 if the Date is before the Date
argument; and a value greater than 0 if the Date is after
the Date argument.
• D1 Date d1=new Date();
• Date d2=new Date();
• D1.compareTo(d2)
• D2
• long getTime() : Returns the number of milliseconds
since January 1, 1970, 00:00:00 GMT represented by this
Date object.
• void setTime(long time) : Changes the current date and
time to given time.
importjava.util.*;
publicclassMain
publicstaticvoidmain(String[] args)
// Creating date
booleanb = d3.before(d2);
intc = d1.compareTo(d2);
System.out.println(c);
d2.setTime(204587433443L);
Output:
Date d3 comes after date d2: true
Date d3 comes before date d2: false
1
Miliseconds from Jan 1 1970 to date d1 is 60935500800000
Before setting Tue Jul 12 13:13:16 UTC 2016
After setting Fri Jun 25 21:50:33 UTC 1976
importjava.util.*;
publicclassCalendar1 {
publicstaticvoidmain(String args[])
{
Calendar c = Calendar.getInstance();
Output:
The Current Date is:Tue Aug 28 11:10:40 UTC 2018
Important Methods and their usage
METHOD DESCRIPTION
abstract void add(int field, It is used to add or subtract the specified amount of time to
int amount) the given calendar field, based on the calendar’s rules.
int get(int field) It is used to return the value of the given calendar field.
abstract int It is used to return the maximum value for the given
getMaximum(int field) calendar field of this Calendar instance.
abstract int It is used to return the minimum value for the given
getMinimum(int field) calendar field of this Calendar instance.
// of Calendar class
importjava.util.*;
publicclassCalendar2 {
publicstaticvoidmain(String[] args)
Output:
Current Calendar's Year: 2018
Current Calendar's Day: 28
Current MINUTE: 10
Current SECOND: 45
Program 2: Java program to demonstrate getMaximum() method.
// of Calendar class
importjava.util.*;
publicclassCalendar3 {
publicstaticvoidmain(String[] args)
intmax = calendar.getMaximum(Calendar.DAY_OF_WEEK);
max = calendar.getMaximum(Calendar.WEEK_OF_YEAR);
Output:
Maximum number of days in a week: 7
Maximum number of weeks in a year: 53
Program 3: Java program to demonstrate the getMinimum() method.
// of Calendar class
importjava.util.*;
publicclassCalendar4 {
publicstaticvoidmain(String[] args)
intmin = calendar.getMinimum(Calendar.DAY_OF_WEEK);
min = calendar.getMinimum(Calendar.WEEK_OF_YEAR);
Output:
Minimum number of days in week: 1
Minimum number of weeks in year: 1
Program 4: Java program to demonstrate add() method.
// of Calendar class
importjava.util.*;
publicclassCalendar5 {
publicstaticvoidmain(String[] args)
calendar.add(Calendar.DATE, -15);
calendar.add(Calendar.MONTH, 4);
calendar.add(Calendar.YEAR, 2);
Output:
15 days ago: Mon Aug 13 11:10:57 UTC 2018
4 months later: Thu Dec 13 11:10:57 UTC 2018
2 years later: Sun Dec 13 11:10:57 UTC 2020
class:*/
importjava.util.*;
publicclassNewClass
publicstaticvoidmain(String args[])
StringTokenizer st1 =
while(st1.hasMoreTokens())
System.out.println(st1.nextToken());
System.out.println("Using Constructor 2 - ");
StringTokenizer st2 =
while(st2.hasMoreTokens())
System.out.println(st2.nextToken());
StringTokenizer st3 =
while(st3.hasMoreTokens())
System.out.println(st3.nextToken());
Output :
Using Constructor 1 -
Hello
Geeks
How
are
you
Using Constructor 2 -
JAVA
Code
String
Using Constructor 3 -
JAVA
Class constructors
1 StringTokenizer(String str)
This constructor a string tokenizer for the specified string.
Class methods
1 int countTokens()
This method calculates the number of times that this tokenizer's nextToken
method can be called before it generates an exception.
2 booleanhasMoreElements()
This method returns the same value as the hasMoreTokens method.
3 booleanhasMoreTokens()
This method tests if there are more tokens available from this tokenizer's string.
4 Object nextElement()
This method returns the same value as the nextToken method, except that its
declared return value is Object rather than String.
5 String nextToken()
This method returns the next token from this string tokenizer.
The BitSet class creates a special type of array that holds bit values. The BitSet
array can increase in size as needed. This makes it similar to a vector of bits. This
is a legacy class but it has been completely re-engineered in Java 2, version 1.4.
The BitSet defines the following two constructors.
1 BitSet( )
This constructor creates a default object.
2 BitSet(int size)
This constructor allows you to specify its initial size, i.e., the number of bits that it
can hold. All bits are initialized to zero.
BitSet implements the Cloneable interface and defines the methods listed in the
following table −
1 void and(BitSetbitSet)
ANDs the contents of the invoking BitSet object with those specified by bitSet.
The result is placed into the invoking object.
2 void andNot(BitSetbitSet)
For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared.
3 int cardinality( )
Returns the number of set bits in the invoking object.
4 void clear( )
Zeros all bits.
7 Object clone( )
Duplicates the invoking BitSet object.
8 booleanequals(Object bitSet)
Returns true if the invoking bit set is equivalent to the one passed in bitSet.
Otherwise, the method returns false.
11 booleanget(int index)
Returns the current state of the bit at the specified index.
13 int hashCode( )
Returns the hash code for the invoking object.
14 booleanintersects(BitSetbitSet)
Returns true if at least one pair of corresponding bits within the invoking object
and bitSet are 1.
15 booleanisEmpty( )
Returns true if all bits in the invoking object are zero.
16 int length( )
Returns the number of bits required to hold the contents of the invoking BitSet.
This value is determined by the location of the last 1 bit.
17
int nextClearBit(int startIndex)
Returns the index of the next cleared bit, (that is, the next zero bit), starting from
the index specified by startIndex.
19 void or(BitSetbitSet)
ORs the contents of the invoking BitSet object with that specified by bitSet. The
result is placed into the invoking object.
25 String toString( )
Returns the string equivalent of the invoking BitSet object.
26 void xor(BitSetbitSet)
XORs the contents of the invoking BitSet object with that specified by bitSet. The
result is placed into the invoking object.
Example
The following program illustrates several of the methods supported by this data
structure −
Live Demo
importjava.util.BitSet;
publicclassBitSetDemo{
publicstaticvoidmain(Stringargs[]){
BitSet bits1 =newBitSet(16);
BitSet bits2 =newBitSet(16);
// AND bits
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);
// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}
Output
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
The BitSet class creates a special type of array that holds bit values. The BitSet
array can increase in size as needed. This makes it similar to a vector of bits. This
is a legacy class but it has been completely re-engineered in Java 2, version 1.4.
The BitSet defines the following two constructors.
1 BitSet( )
This constructor creates a default object.
2
BitSet(int size)
This constructor allows you to specify its initial size, i.e., the number of bits that it
can hold. All bits are initialized to zero.
BitSet implements the Cloneable interface and defines the methods listed in the
following table −
2 void andNot(BitSetbitSet)
For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared.
3 int cardinality( )
Returns the number of set bits in the invoking object.
4 void clear( )
Zeros all bits.
7 Object clone( )
Duplicates the invoking BitSet object.
8 booleanequals(Object bitSet)
Returns true if the invoking bit set is equivalent to the one passed in bitSet.
Otherwise, the method returns false.
11 booleanget(int index)
Returns the current state of the bit at the specified index.
12 BitSetget(int startIndex, int endIndex)
Returns a BitSet that consists of the bits from startIndex to endIndex. The
invoking object is not changed.
13 int hashCode( )
Returns the hash code for the invoking object.
14 booleanintersects(BitSetbitSet)
Returns true if at least one pair of corresponding bits within the invoking object
and bitSet are 1.
15 booleanisEmpty( )
Returns true if all bits in the invoking object are zero.
16 int length( )
Returns the number of bits required to hold the contents of the invoking BitSet.
This value is determined by the location of the last 1 bit.
17
int nextClearBit(int startIndex)
Returns the index of the next cleared bit, (that is, the next zero bit), starting from
the index specified by startIndex.
19 void or(BitSetbitSet)
ORs the contents of the invoking BitSet object with that specified by bitSet. The
result is placed into the invoking object.
24
int size( )
Returns the number of bits in the invoking BitSet object.
25 String toString( )
Returns the string equivalent of the invoking BitSet object.
26 void xor(BitSetbitSet)
XORs the contents of the invoking BitSet object with that specified by bitSet. The
result is placed into the invoking object.
Example
The following program illustrates several of the methods supported by this data
structure −
Live Demo
importjava.util.BitSet;
publicclassBitSetDemo{
publicstaticvoidmain(Stringargs[]){
BitSet bits1 =newBitSet(16);
BitSet bits2 =newBitSet(16);
// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}
Output
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
Drawback of Applet
Do You Know
o Who is responsible to manage the life cycle of an applet ?
o How to perform animation in applet ?
o How to paint like paint brush in applet ?
o How to display digital clock in applet ?
o How to display analog clock in applet ?
o How to communicate two applets ?
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subcl
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods
of applet.
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
5.5M
152
C++ vs Java
1. By html file.
2. By appletViewer tool (for testing purpose).
To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }
Note: class must be public because its object is created by Java Plugin software that resides on the
browser.
myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
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
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 to applet",150,150);
8. }
9.
10. }
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */
c:\>javac First.java
c:\>appletviewer First.java
Displaying Graphics in Applet
1. import java.applet.Applet;
2. import java.awt.*;
3.
4. public class GraphicsDemo extends Applet{
5.
6. public void paint(Graphics g){
7. g.setColor(Color.red);
8. g.drawString("Welcome",50, 50);
9. g.drawLine(20,30,20,300);
10. g.drawRect(70,100,30,30);
11. g.fillRect(170,100,30,30);
12. g.drawOval(70,200,30,30);
13.
14. g.setColor(Color.pink);
15. g.fillOval(170,200,30,30);
16. g.drawArc(90,150,30,30,30,270);
17. g.fillArc(270,150,30,30,0,180);
18.
19. }
20. }
1. <html>
2. <body>
3. <applet code="GraphicsDemo.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Applet is mostly used in games and animation. For this purpose image is required to be displayed.
The java.awt.Graphics class provide a method drawImage() to display the image.
Syntax of drawImage() method:
1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw
1. public URL getDocumentBase(): is used to return the URL of the document in which applet is embedd
2. public URL getCodeBase(): is used to return the base URL.
1. import java.awt.*;
2. import java.applet.*;
3.
4.
5. public class DisplayImage extends Applet {
6.
7. Image picture;
8.
9. public void init() {
10. picture = getImage(getDocumentBase(),"sonoo.jpg");
11. }
12.
13. public void paint(Graphics g) {
14. g.drawImage(picture, 30,30, this);
15. }
16.
17. }
In the above example, drawImage() method of Graphics class is used to display the image. The 4th argument of
is ImageObserver object. The Component class implements ImageObserver interface. So current class object
ImageObserver because Applet class indirectly extends the Component class.
myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
message, from right to left, across the applet’s window. Since the scrolling of the message
*/
import java.awt.*;
import java.applet.*;
/*
</applet>
*/
Thread t = null;
int state;
setBackground(Color.cyan);
setForeground(Color.red);
23-ch23.indd 757 14/02/14 5:12 PMCompRef_2010 / Java The Complete Reference, Ninth
Edition /Schildt / 007180 855-8
// Start thread
t = new Thread(this);
stopFlag = false;
t.start();
// Redisplay banner
for( ; ; ) {
try {
repaint();
Thread.sleep(250);
if(stopFlag)
break;
} catch(InterruptedException e) {}
stopFlag = true;
t = null;
char ch;
ch = msg.charAt(0);
msg += ch;
Let’s take a close look at how this applet operates. First, notice that SimpleBanner
extends Applet, as expected, but it also implements Runnable. This is necessary, since the
23-ch23.indd 758 14/02/14 5:12 PMCompRef_2010 / Java The Complete Reference, Ninth
Edition /Schildt / 007180 855-8
Part II
applet will be creating a second thread of execution that will be used to scroll the banner.
Inside init( ), the foreground and background colors of the applet are set.
After initialization, the run-time system calls start( ) to start the applet running. Inside
start( ), a new thread of execution is created and assigned to the Thread variable t. Then,
the boolean variable stopFlag, which controls the execution of the applet, is set to false.
Next, the thread is started by a call to t.start( ). Remember that t.start( ) calls a method
defined by Thread, which causes run( ) to begin executing. It does not cause a call to the
Inside run( ), a call to repaint( ) is made. This eventually causes the paint( ) method to
be called, and the rotated contents of msg are displayed. Between each iteration, run( )
sleeps for a quarter of a second. The net effect is that the contents of msg are scrolled right
to left in a constantly moving display. The stopFlag variable is checked on each iteration.
If a browser is displaying the applet when a new page is viewed, the stop( ) method is
called, which sets stopFlag to true, causing run( ) to terminate. This is the mechanism used
to stop the thread when its page is no longer in view. When the applet is brought back into
view, start( ) is once again called, which starts a new thread to execute the banner.
In addition to displaying information in its window, an applet can also output a message
to the status window of the browser or applet viewer on which it is running. To do so, call
showStatus( ) with the string that you want displayed. The status window is a good place to
give the user feedback about what is occurring in the applet, suggest options, or possibly
report some types of errors. The status window also makes an excellent debugging aid,
because it gives you an easy way to output information about your applet.
import java.awt.*;
import java.applet.*;
/*
</applet>
*/
setBackground(Color.cyan);
23-ch23.indd 759 14/02/14 5:12 PMCompRef_2010 / Java The Complete Reference, Ninth
Edition /Schildt / 007180 855-8
As mentioned earlier, at the time of this writing, Oracle recommends that the APPLET tag
be used to manually start an applet when JNLP is not used. An applet viewer will execute
each APPLET tag that it finds in a separate window, while web browsers will allow many
applets on a single page. So far, we have been using only a simplified form of the APPLET
The syntax for a fuller form of the APPLET tag is shown here. Bracketed items are
optional.
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
[ALIGN = alignment ]
>
...
</APPLET>
CODEBASE CODEBASE is an optional attribute that specifies the base URL of the
applet code, which is the directory that will be searched for the applet’s executable class
file (specified by the CODE tag). The HTML document’s URL directory is used as the
CODE CODE is a required attribute that gives the name of the file containing your
applet’s compiled .class file. This file is relative to the code base URL of the applet, which
// Use Parameters
import java.awt.*;
import java.applet.*;
/*
</applet>
*/
String fontName;
int fontSize;
float leading;
boolean active;
String param;
fontName = getParameter("fontName");
if(fontName == null)
param = getParameter("fontSize");
try {
if(param != null)
fontSize = Integer.parseInt(param);
else
fontSize = 0;
} catch(NumberFormatException e) {
fontSize = -1;
param = getParameter("leading");
try {
if(param != null)
leading = Float.valueOf(param).floatValue();
else
leading = 0;
} catch(NumberFormatException e) {
leading = -1;
param = getParameter("accountEnabled");
if(param != null)
active = Boolean.valueOf(param).booleanValue();
// Display parameters.
public void paint(Graphics g) {
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
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 public void addTextListener(TextListener 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){}
o public void addItemListener(ItemListener a){}
1. Within class
2. Other class
3. Anonymous class
1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent extends Frame implements ActionListener{
4. TextField tf;
5. AEvent(){
6.
7. //create components
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10. Button b=new Button("click me");
11. b.setBounds(100,120,80,30);
12.
13. //register listener
14. b.addActionListener(this);//passing current instance
15.
16. //add components and set size, layout and visibility
17. add(b);add(tf);
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21. }
22. public void actionPerformed(ActionEvent e){
23. tf.setText("Welcome");
24. }
25. public static void main(String args[]){
26. new AEvent();
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.
2) Java event handling by outer class
1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent2 extends Frame{
4. TextField tf;
5. AEvent2(){
6. //create components
7. tf=new TextField();
8. tf.setBounds(60,50,170,20);
9. Button b=new Button("click me");
10. b.setBounds(100,120,80,30);
11. //register listener
12. Outer o=new Outer(this);
13. b.addActionListener(o);//passing outer class instance
14. //add components and set size, layout and visibility
15. add(b);add(tf);
16. setSize(300,300);
17. setLayout(null);
18. setVisible(true);
19. }
20. public static void main(String args[]){
21. new AEvent2();
22. }
23. }
1. import java.awt.event.*;
2. class Outer implements ActionListener{
3. AEvent2 obj;
4. Outer(AEvent2 obj){
5. this.obj=obj;
6. }
7. public void actionPerformed(ActionEvent e){
8. obj.tf.setText("welcome");
9. }
10. }
1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent3 extends Frame{
4. TextField tf;
5. AEvent3(){
6. tf=new TextField();
7. tf.setBounds(60,50,170,20);
8. Button b=new Button("click me");
9. b.setBounds(50,120,80,30);
10.
11. b.addActionListener(new ActionListener(){
12. public void actionPerformed(){
13. tf.setText("hello");
14. }
15. });
16. add(b);add(tf);
17. setSize(300,300);
18. setLayout(null);
19. setVisible(true);
20. }
21. public static void main(String args[]){
22. new AEvent3();
23. }
24. }
item is selected.
ItemEvent Generated when a check box or list item is clicked; also occurs when
deselected.
MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or released;
TextEvent Generated when the value of a text area or text field is changed.
WindowEvent Generated when a window is activated, closed, deactivated, deiconified,
As explained, the delegation event model has two parts: sources and listeners. As it relates
to this chapter, listeners are created by implementing one or more of the interfaces defined
by the java.awt.event package. When an event occurs, the event source invokes the appropriate
method defined by the listener and provides an event object as its argument. Table 24-3 lists
Check box Generates item events when the check box is selected or deselected.
Menu item Generates action events when a menu item is selected; generates item
Scroll bar Generates adjustment events when the scroll bar is manipulated.
Text components Generates text events when the user enters a character.
Interface Description
resized, or shown.
keyboard focus.
ItemListener Defines one method to recognize when the state of an item changes.
KeyListener Defines three methods to recognize when a key is pressed, released, or typed.
MouseListener Defines five methods to recognize when the mouse is clicked, enters a
MouseWheelListener Defines one method to recognize when the mouse wheel is moved.
This interface defines the actionPerformed( ) method that is invoked when an action event
This interface defines four methods that are invoked when a component is resized, moved,
This interface defines two methods. When a component obtains keyboard focus,
This interface defines the itemStateChanged( ) method that is invoked when the state of an
This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are
invoked when a key is pressed and released, respectively. The keyTyped( ) method is
invoked
For example, if a user presses and releases the a key, three events are generated in
sequence: key pressed, typed, and released. If a user presses and releases the home key,
two key events are generated in sequence: key pressed and released.
This interface defines five methods. If the mouse is pressed and released at the same point,
mouseReleased( ) methods are invoked when the mouse is pressed and released,
respectively.
This interface defines two methods. The mouseDragged( ) method is called multiple times
as the mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse
This interface defines the mouseWheelMoved( ) method that is invoked when the mouse
This interface defines the textValueChanged( ) method that is invoked when a change
occurs in a text area or text field. Its general form is shown here:
are called when a window gains or loses input focus. Their general forms are shown here:
method is called when a window is being closed. The general forms of these methods are
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
</applet>
*/
addMouseListener(this);
addMouseMotionListener(this);
// save coordinates
mouseX = 0;
mouseY = 10;
repaint();
}
// save coordinates
mouseX = 0;
mouseY = 10;
repaint();
// save coordinates
mouseX = 0;
mouseY = 10;
repaint();
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
repaint();
// show status
}
}
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
</applet>
*/
implements KeyListener {
addKeyListener(this);
showStatus("Key Down");
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
// Display keystrokes.
g.drawString(msg, X, Y);
Adapter Classes
Java provides a special feature, called an adapter class, that can simplify the creation of
event
methods in an event listener interface. Adapter classes are useful when you want to receive
and process only some of the events that are handled by a particular event listener
interface.
You can define a new class to act as an event listener by extending one of the adapter
classes
For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
were interested in only mouse drag events, then you could simply extend
MouseMotionAdapter
Table 24-4 lists several commonly used adapter classes in java.awt.event and notes the
interface that each implements.
24-ch24.indd 791 14/02/14 5:13 PMCompRef_2010 / Java The Complete Reference, Ninth
Edition /Schildt / 007180 855-8
The following example demonstrates an adapter. It displays a message in the status bar
of an applet viewer or browser when the mouse is clicked or dragged. However, all other
mouse events are silently ignored. The program has three classes. AdapterDemo extends
Applet. Its init( ) method creates an instance of MyMouseAdapter and registers that object
to
and registers that object to receive notifications of mouse motion events. Both of the
The other mouse events are silently ignored by code inherited from the MouseAdapter
mouseDragged( ) method. The other mouse motion event is silently ignored by code
Note that both of the event listener classes save a reference to the applet. This
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
</applet>
*/
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseMotionAdapter
MouseMotionListener
WindowAdapter
WindowListener,
WindowFocusListener,
WindowStateListene
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
</applet>
*/
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
AdapterDemo adapterDemo;
this.adapterDemo = adapterDemo;
adapterDemo.showStatus("Mouse clicked");
}
class MyMouseMotionAdapter extends MouseMotionAdapter {
AdapterDemo adapterDemo;
this.adapterDemo = adapterDemo;
adapterDemo.showStatus("Mouse dragged");
Inner Classes
the basics of inner classes were explained. Here, you will see why they are
important. Recall that an inner class is a class defined within another class, or even within
an
expression. This section illustrates how inner classes can be used to simplify the code when
To understand the benefit provided by inner classes, consider the applet shown in the
following listing. It does not use an inner class. Its goal is to display the string "Mouse
Pressed"
in the status bar of the applet viewer or browser when the mouse is pressed. There are two
constructor. This reference is stored in an instance variable for later use by the
mousePressed( )
method. When the mouse is pressed, it invokes the showStatus( ) method of the applet
import java.applet.*;
import java.awt.event.*;
/*
</applet>
*/
addMouseListener(new MyMouseAdapter(this));
MousePressedDemo mousePressedDemo;
this.mousePressedDemo = mousePressedDemo;
mousePressedDemo.showStatus("Mouse Pressed.");
}
import java.applet.*;
import java.awt.event.*;
/*
</applet>
*/
addMouseListener(new MyMouseAdapter());
showStatus("Mouse Pressed");
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
14. }
15. }
Example of Swing by Association inside constructor
We can also write all the codes of creating JFrame, JButton and method call inside the
java constructor.
File: Simple.java
1. import javax.swing.*;
2. public class Simple {
3. JFrame f;
4. Simple(){
5. f=new JFrame();//creating instance of JFrame
6.
7. JButton b=new JButton("click");//creating instance of JButton
8. b.setBounds(130,100,100, 40);
9.
10. f.add(b);//adding button in JFrame
11.
12. f.setSize(400,500);//400 width and 500 height
13. f.setLayout(null);//using no layout managers
14. f.setVisible(true);//making the frame visible
15. }
16.
17. public static void main(String[] args) {
18. Simple s1=new Simple();
19. }
20. }
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that
sets the position of the button.
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. }}
Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It
inherits AbstractButton class.
Constructor Description
Output:
Java JButton Example with ActionListener
1. import java.awt.event.*;
2. import javax.swing.*;
3. public class ButtonExample {
4. public static void main(String[] args) {
5. JFrame f=new JFrame("Button Example");
6. final JTextField tf=new JTextField();
7. tf.setBounds(50,50, 150,20);
8. JButton b=new JButton("Click Here");
9. b.setBounds(50,100,95,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. }
20. }
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but a
user cannot edit it directly. It inherits JComponent class.
Constructor Description
JLabel(String s, Icon i, int horizontalAlignment) Creates a JLabel instance with the specified text, image, and h
Methods Description
void setText(String text) It defines the single line of text this component will dis
void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along the X
Icon getIcon() It returns the graphic image that the label displays.
Output:
Java JLabel Example with ActionListener
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class LabelExample extends Frame implements ActionListener{
5. JTextField tf; JLabel l; JButton b;
6. LabelExample(){
7. tf=new JTextField();
8. tf.setBounds(50,50, 150,20);
9. l=new JLabel();
10. l.setBounds(50,100, 250,20);
11. b=new JButton("Find IP");
12. b.setBounds(50,150,95,30);
13. b.addActionListener(this);
14. add(b);add(tf);add(l);
15. setSize(400,400);
16. setLayout(null);
17. setVisible(true);
18. }
19. public void actionPerformed(ActionEvent e) {
20. try{
21. String host=tf.getText();
22. String ip=java.net.InetAddress.getByName(host).getHostAddress();
23. l.setText("IP of "+host+" is: "+ip);
24. }catch(Exception ex){System.out.println(ex);}
25. }
26. public static void main(String[] args) {
27. new LabelExample();
28. }}
Output:
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but a
user cannot edit it directly. It inherits JComponent class.
Constructor Description
JLabel(String s, Icon i, int horizontalAlignment) Creates a JLabel instance with the specified text, image, and h
Methods Description
void setText(String text) It defines the single line of text this component will dis
void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along the X
Icon getIcon() It returns the graphic image that the label displays.
Output:
Output:
Constructor Description
JTextArea(String s, int row, int column) Creates a text area with the specified number of rows and columns that
Methods Description
void insert(String s, int position) It is used to insert the specified text on the specified position.
void append(String s) It is used to append the given text to the end of the document.
Output:
Output:
Constructor Description
JJCheckBox() Creates an initially unselected check box button with no text, no
JCheckBox(String text, boolean selected) Creates a check box with text and specifies whether or not it is in
JCheckBox(Action a) Creates a check box where properties are taken from the Action
Methods Description
Output:
Output:
Java JCheckBox Example: Food Order
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class CheckBoxExample extends JFrame implements ActionListener{
4. JLabel l;
5. JCheckBox cb1,cb2,cb3;
6. JButton b;
7. CheckBoxExample(){
8. l=new JLabel("Food Ordering System");
9. l.setBounds(50,50,300,20);
10. cb1=new JCheckBox("Pizza @ 100");
11. cb1.setBounds(100,100,150,20);
12. cb2=new JCheckBox("Burger @ 30");
13. cb2.setBounds(100,150,150,20);
14. cb3=new JCheckBox("Tea @ 10");
15. cb3.setBounds(100,200,150,20);
16. b=new JButton("Order");
17. b.setBounds(100,250,80,30);
18. b.addActionListener(this);
19. add(l);add(cb1);add(cb2);add(cb3);add(b);
20. setSize(400,400);
21. setLayout(null);
22. setVisible(true);
23. setDefaultCloseOperation(EXIT_ON_CLOSE);
24. }
25. public void actionPerformed(ActionEvent e){
26. float amount=0;
27. String msg="";
28. if(cb1.isSelected()){
29. amount+=100;
30. msg="Pizza: 100\n";
31. }
32. if(cb2.isSelected()){
33. amount+=30;
34. msg+="Burger: 30\n";
35. }
36. if(cb3.isSelected()){
37. amount+=10;
38. msg+="Tea: 10\n";
39. }
40. msg+="-----------------\n";
41. JOptionPane.showMessageDialog(this,msg+"Total: "+amount);
42. }
43. public static void main(String[] args) {
44. new CheckBoxExample();
45. }
46. }
Output:
ava JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option
from multiple options. It is widely used in exam systems or quiz.
Constructor Description
JRadioButton(String s, boolean selected) Creates a radio button with the specified text and selected
Methods Description
Output:
Output:
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by
user is shown on the top of a menu. It inherits JComponent class.
Constructor Description
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified arra
JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the specified Vect
Methods Description
void removeAllItems() It is used to remove all the items from the list.
Output:
Java JComboBox Example with ActionListener
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class ComboBoxExample {
4. JFrame f;
5. ComboBoxExample(){
6. f=new JFrame("ComboBox Example");
7. final JLabel label = new JLabel();
8. label.setHorizontalAlignment(JLabel.CENTER);
9. label.setSize(400,100);
10. JButton b=new JButton("Show");
11. b.setBounds(200,100,75,20);
12. String languages[]={"C","C++","C#","Java","PHP"};
13. final JComboBox cb=new JComboBox(languages);
14. cb.setBounds(50, 100,90,20);
15. f.add(cb); f.add(label); f.add(b);
16. f.setLayout(null);
17. f.setSize(350,350);
18. f.setVisible(true);
19. b.addActionListener(new ActionListener() {
20. public void actionPerformed(ActionEvent e) {
21. String data = "Programming language Selected: "
22. + cb.getItemAt(cb.getSelectedIndex());
23. label.setText(data);
24. }
25. });
26. }
27. public static void main(String[] args) {
28. new ComboBoxExample();
29. }
30. }
Output:
HTML Tutorial
BorderLayout (LayoutManagers)
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout managers.
There are following classes that represents the layout managers:
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.
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.
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.
Example of FlowLayout class
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. }
ava BoxLayout
The BoxLayout is used to arrange the components either vertically or horizontally. For this
purpose, BoxLayout provides four constants. They are as follows:
1. BoxLayout(Container c, int axis): creates a box layout that arranges the components
with the given axis.
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample2 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample2() {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. add (buttons[i]);
13. }
14.
15. setLayout (new BoxLayout(this, BoxLayout.X_AXIS));
16. setSize(400,400);
17. setVisible(true);
18. }
19.
20. public static void main(String args[]){
21. BoxLayoutExample2 b=new BoxLayoutExample2();
22. }
23. }
ava 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.
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
protected static int MINSIZE It is smallest grid that can be laid out
Useful Methods
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. GridBagLayoutgrid = 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:
Example 2