Java Thread Life Cycle and Communication
Java Thread Life Cycle and Communication
UNIT - 3
Q23. Analyze the impact of thread life cycle on the execution of Thread in Java. (4M)
Ans:
New / Born
When a thread object is created using new, then the thread is said to be in the New state.
This state is also known as Born state. Thread t1 = new Thread();
Runnable / Ready
When a thread calls start( ) method, then the thread is said to be in the Runnable state.
This state is also known as a Ready state. [Link]();
Running
When a thread calls run( ) method, then the thread is said to be Running. The run( ) method of a thread
called automatically by the start( ) method.
Blocked / Waiting
A thread in the Running state may move into the blocked state due to various reasons like sleep( ) method
called, wait( ) method called, suspend( ) method called, and join( ) method called, etc.
When a thread is in the blocked or waiting state, it may move to Runnable state due to reasons like sleep
time completed, waiting time completed, notify( ) or notifyAll( ) method called, resume( ) method called,
etc.
Dead / Terminated
A thread in the Running state may move into the dead state due to either its execution completed or the
stop( ) method called. The dead state is also known as the terminated state.
Q24: Developa Java Program that demonstrates inter thread communication or producer-consumer
problem with example? (4M)
Ans:
class ItemQueue {
int item;
boolean valueSet = false;
class Producer implements Runnable {
synchronized int getItem() { ItemQueue itemQueue;
while (!valueSet) {
try { Producer(ItemQueue itemQueue) {
wait(); [Link] = itemQueue;
} catch (InterruptedException e) { new Thread(this, "Producer").start();
[Link]("InterruptedException caught"); }
}
} public void run() {
[Link]("Consumed: " + item); int i = 0;
valueSet = false; while (true) {
try { [Link](i++);
[Link](1000); }
} catch (InterruptedException e) { }
[Link]("InterruptedException caught"); }
}
notify(); class Consumer implements Runnable {
return item; ItemQueue itemQueue;
}
Consumer(ItemQueue itemQueue) {
synchronized void putItem(int item) { [Link] = itemQueue;
while (valueSet) { new Thread(this, "Consumer").start();
try { }
wait();
} catch (InterruptedException e) { public void run() {
[Link]("InterruptedException caught"); while (true) {
} [Link]();
} }
[Link] = item; }
valueSet = true; }
[Link]("Produced: " + item);
try { class ProducerConsumer {
[Link](1000); public static void main(String[] args) {
} catch (InterruptedException e) { ItemQueue itemQueue = new ItemQueue();
[Link]("InterruptedException caught"); new Producer(itemQueue);
} new Consumer(itemQueue);
notify(); }
} }
}
The producer produces the item and the consumer consumes the same. But here, the consumer can not
consume until the producer produces the item, and producer can not produce until the consumer
consumes the item that already been produced.
So here, the consumer has to wait until the producer produces the item, and the producer also needs to
wait until the consumer consumes the same. Here we use the inter-thread communication to implement
the producer and consumer problem.
All the methods wait( ), notify( ), and notifyAll( ) can be used only inside the synchronized methods only
Output:
Produced: 0
Consummed: 0
Produced: 1
Consummed: 1
Produced: 2
Consummed: 2
Produced: 3
Consummed: 3
...
Example:
class SampleThread extends Thread{
public void run() {
[Link]("Inside SampleThread");
[Link]("Current Thread: " + [Link]().getName());
}
}
public class My_Thread_Test {
public static void main(String[] args) {
SampleThread obj1 = new SampleThread();
SampleThread obj2 = new SampleThread();
[Link]("first");
[Link]("second");
[Link](4);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}
}
Output:
Inside SampleThread
Current Thread: second
Inside SampleThread
Current Thread: first
UNIT - 4
Q27: Explain Collection Framework. (4M)
Ans: The Collection framework represents a unified architecture for storing and manipulating a group
of objects. It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm
Interfaces
• Collection: The root interface of the framework, representing a group of objects. Key sub-interfaces
include List, Set, and Queue.
• List: An ordered collection (sequence) that allows duplicate elements. Common implementations
are ArrayList, LinkedList, and Vector.
• Set: A collection that does not allow duplicate elements. Common implementations are HashSet,
LinkedHashSet, and TreeSet.
• Queue: A collection designed for holding elements prior to processing, typically following FIFO
(First-In-First-Out). Common implementations are LinkedList and PriorityQueue.
• Map: An interface for storing key-value pairs, not extending Collection but part of the framework.
Common implementations are HashMap, LinkedHashMap, and TreeMap.
Classes
• ArrayList: Implements List interface, resizable array. Can have duplicates. Maintains Insertion Order.
Non-Synchronized.
• LinkedList: Implements List and Deque interfaces, doubly linked list.
• PriorityQueue: Implements queue. But it does not orders the elements in FIFO manner. It inherits
AbstractQueue class.
• ArrayDeque: Implements Deque, Re-sizeable array. We can add or remove elements from both
sides. Null elements are not allowed. Non-synchronized.
• HashSet: Implements Set interface, uses a hash table for storage to create collection.
• TreeSet: Implements NavigableSet interface. Uses Tree for storage.
• Stack: Subclass of Vector. Implements LIFO data structure.
• HashMap: Implements Map interface, hash table-based implementation.
• TreeMap: Implements NavigableMap interface, sorted map backed by a tree.
Algorithms
• Java Collections Framework provides algorithms to perform operations like sorting, searching, and
manipulating collections. These are mainly static methods in the Collections class.
Q28: Differentiate between Array and Arraylist. (4M)
Ans:
class TestCollection12 {
public static void main(String args[]) {
// Create a PriorityQueue of Strings
PriorityQueue<String> queue = new PriorityQueue<String>();
METHODS OF PriorityQueue:
// Remove elements from the queue
[Link]();
• boolean add(object)
[Link]();
• boolean offer(object)
• Object remove()
// Display the queue elements after removal • Object poll()
[Link]("After removing two elements:"); • Object element()
Iterator<String> itr2 = [Link](); • Object peek()
while ([Link]()) {
[Link]([Link]());
}
}
}
Q31: Explain HashMap. (4M)
Ans: Java HashMap class implements the Map interface which allows us to store key and value pair, where
keys should be unique. Doesn’t maintain any order.
• If you try to insert the duplicate key, it will replace the element of the
corresponding key.
• It is easy to perform operations using the key index like updation, deletion,
etc.
• HashMap class is found in the [Link] package.
• HashMap in Java is like the legacy Hashtable class, but it is not synchronized.
• It allows us to store only 1 null element.
• Since Java 5, it is denoted as HashMap<K,V>, where K stands for key and V for
value. It inherits the AbstractMap class and implements the Map interface.
Points to remember
1. Java HashMap contains values based on the key.
2. Java HashMap contains only unique keys.
3. Java HashMap may have one null key and multiple null values.
4. Java HashMap is non synchronized.
5. Java HashMap maintains no order.
6. The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
Example Code:
import [Link].*;
class MapExample2 {
public static void main(String args[]) {
Map<Integer, String> map = new HashMap<Integer, String>();
[Link](100, "Amit");
[Link](101, "Vijay"); OUTPUT:
[Link](102, "Rahul"); 100 Amit
101 Vijay
// Elements can traverse in any order
for ([Link] m : [Link]()) { 102 Rahul
[Link]([Link]() + " " + [Link]());
}
}
}
Hash Map:
Example:
import [Link];
}
}
Methods of HashMap class:
void clear(), boolean isEmpty(), Object clone(), Set entrySet(), Set keySet(), V put(Object key, Object value),
void putAll(Map map), V remove(Object key), boolean containsValue(Object value), boolean
containsKey(Object key), boolean equals(Object o) V get(Object key), V replace(K key, V value)
Tree Map:-
o Java TreeMap contains values based on the key. It implements the
NavigableMap interface and extends AbstractMap class.
o Java TreeMap contains only unique elements.
o Java TreeMap cannot have a null key but can have multiple null values.
o Java TreeMap is non synchronized.
o Java TreeMap maintains ascending order.
METHODS:
Example: clear(), clone()
import [Link]; comparator()
keySet()
public class TreeMapExample { lastEntry()
firstKey()
public static void main(String[] args) {
get(Object key)
TreeMap<String, Integer> map = new TreeMap<>(); lastKey()
[Link]("Charlie", 35); remove(Object key)
[Link]("Alice", 30); entrySet()
[Link]("Bob", 25); size()
values()
[Link]("Sorted Order: " + map);
} OUTPUT:
} Sorted Order: {Alice=30, Bob=25, Charlie=35}
LinkedListMap:
LinkedHashMap is the implementation of Map. It inherits HashMap class. It maintains insertion order.
o Java LinkedHashMap contains values based on the key.
o Java LinkedHashMap contains unique elements.
o Java LinkedHashMap may have one null key and multiple null values.
o Java LinkedHashMap is non synchronized.
o Java LinkedHashMap maintains insertion order.
o The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
Steps to Refactor
1. Understand and Document: Document the methods and expected behavior.
2. Write Tests: Create tests to cover all operations.
import [Link];
import static [Link].*;
@Test
public void testAdd() {
assertEquals(5, [Link]("add", 2, 3));
}
@Test
public void testSubtract() {
assertEquals(3, [Link]("subtract", 5, 2));
}
@Test
public void testMultiply() {
assertEquals(12, [Link]("multiply", 3, 4));
}
@Test
public void testDivide() {
assertEquals(5, [Link]("divide", 10, 2));
assertTrue([Link]([Link]("divide", 10, 0)));
}
@Test
public void testUnsupportedOperation() {
assertTrue([Link]([Link]("mod", 10, 2)));
}
}
3. Refactor: Break the logic into smaller methods.
Refactored Legacy Class (After Refactoring)
public class RefactoredCalculator {
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.
To instantiate the List interface, we must use :
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();
Example:
import [Link];
import [Link];
Output:
ArrayList: [Apple, Banana, Apple]
LinkedList: [Car, Bike, Car]
Set Interface
Set Interface in Java is present in [Link] package. It extends the Collection interface. It represents the
unordered set of elements which doesn't allow us to store the duplicate items. We can store at most one
null value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.
Set can be instantiated as:
Set<data-type> s1 = new HashSet<data-type>();
Set<data-type> s2 = new LinkedHashSet<data-type>();
Set<data-type> s3 = new TreeSet<data-type>();
Example:
import [Link];
METHODS:
import [Link]; • add(element)
import [Link]; • addAll(collection)
• clear()
public class SetExample { • contains(element)
public static void main(String[] args) { • containsAll(collection)
// Using HashSet • hashCode()
HashSet<String> hashSet = new HashSet<>(); • isEmpty()
[Link]("Dog"); • iterator()
• remove(element)
[Link]("Cat");
• removeAll(collection)
[Link]("Dog"); // Duplicate, will not be added
• retainAll(collection)
• size()
[Link]("HashSet: " + hashSet); • toArray()
// Using LinkedHashSet
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
[Link]("Red");
[Link]("Blue");
[Link]("Red"); // Duplicate, will not be added
// Using TreeSet
TreeSet<Integer> treeSet = new TreeSet<>();
[Link](5);
[Link](2);
[Link](5); // Duplicate, will not be added
[Link](1);
[Link]("TreeSet: " + treeSet); // Sorted order
}
}
Output:
HashSet: [Cat, Dog]
LinkedHashSet: [Red, Blue]
TreeSet: [1, 2, 5]
UNIT - 5
Q36: Write the implementation of Anonymous Inner class. (4M)
Ans: A class that has no name is known as an anonymous inner class in Java.
It should be used if you have to override a method of class or interface. Java Anonymous inner class can be
created in two ways:
1. Class (may be abstract or concrete).
2. Interface
Example using class
abstract class Person {
abstract void eat();
}
class TestAnonymousInner {
public static void main(String args[]) {
Person p = new Person() {
void eat() {
[Link]("nice fruits");
}
};
[Link]();
}
}
1. A class is created but its name is decided by the compiler which extends the Person class and provides
the implementation of the eat() method.
2. An object of Anonymous class is created that is referred by p reference variable of Person type.
Output
nice fruits
Example using Interface
interface Eatable {
void eat();
}
class TestAnnonymousInner1 {
public static void main(String args[]) {
Eatable e = new Eatable() {
public void eat() {
[Link]("nice fruits");
}
};
[Link]();
}
}
Output
nice fruits
Q37: Explain Java Swing class hierarchy. (4M)
Ans:
Java Swing Class Hierarchy:
Java Swing is a part of the Java Foundation Classes (JFC) used for building graphical user interfaces (GUIs).
It provides lightweight components that are platform-independent.
1. Top-Level Containers:
These are the main building blocks of any Swing application:
o JFrame: Represents a window.
o JDialog: Represents a dialog box.
o JApplet: Represents applets in a Swing application.
2. Intermediate Containers:
Used for organizing and managing layouts:
o JPanel: A generic container to hold components.
o JSplitPane, JScrollPane, etc.
3. Atomic Components:
Basic UI elements:
o Buttons: JButton, JRadioButton, JCheckBox.
o Text Components: JTextField, JTextArea, JPasswordField.
o Labels: JLabel.
o Menus: JMenuBar, JMenu, JMenuItem.
4. Specialized Containers:
For advanced layouts and data representation:
o JTable: Displays tabular data.
o JTree: Displays hierarchical data.
o JList: Displays a list of items.
import [Link].*;
[Link](this);
[Link](myFont);
[Link]([Link]);
[Link](message);
[Link](500, 500);
[Link](true);
}
@Override
public void mouseClicked(MouseEvent arg0) {
[Link]("Mouse Clicked");
}
@Override
public void mouseEntered(MouseEvent arg0) {
[Link]("Mouse Entered");
}
@Override
public void mouseExited(MouseEvent arg0) {
[Link]("Mouse Exited");
}
@Override
public void mousePressed(MouseEvent arg0) { public class MouseEventsExample {
[Link]("Mouse Pressed");
} public static void main(String[] args) {
@Override new App();
public void mouseReleased(MouseEvent arg0) { }
[Link]("Mouse Released");
} }
Q40: Explain Swing components like ,JCombobox, JButton. (4M)
Ans: 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.
JComboBox class declaration:
public class JComboBox extends JComponent implements ItemSelectable, ListDataListener,
ActionListener, Accessible
Commonly used Constructors:
JComboBox(): Creates a JComboBox with a default data model.
JComboBox(Object[] items): Creates a JComboBox that contains the elements in thespecified array.
JComboBox(Vector<?>items): Creates a JComboBox that contains the elements in thespecified Vector.
Commonly used Methods:
• void addItem(Object anObject)
• void removeItem(Object anObject)
• void removeAllItems()
• void setEditable(boolean b)
• void addActionListener(ActionListener a)
• void addItemListener(ItemListener i)
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.
JButton class declaration
public class JButton extends AbstractButton implements Accessible
Commonly used Constructors:
JButton(): It creates a button with no text and icon.
JButton(String s): It creates a button with the specified text.
JButton(Icon i): It creates a button with the specified icon object.
[Link] class
For creating any applet [Link] 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.
[Link] class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
Q43: Define Layout. Explain Different layout managers available in Java with neat sketch. (8M)
Ans:
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. [Link]
6. [Link]
2. [Link]
7. [Link]
3. [Link]
8. [Link]
4. [Link]
9. [Link] etc.
5. [Link]
Java BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south, east, west and center.
Each region (area) may contain one component only. It is the default layout of frame or window. The
BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
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.
import [Link].*;
import [Link].*;
public class Border {
JFrame f;
Border() {
f = new JFrame();
// creating buttons
JButton b1 = new JButton("NORTH"); // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");
JButton b3 = new JButton("EAST");
JButton b4 = new JButton("WEST");
JButton b5 = new JButton("CENTER");
[Link](300, 300);
[Link](true);
}
public static void main(String[] args) {
new Border();
}
}
Java GridLayout:
The Java GridLayout class is used to arrange the components in a rectangular grid. One component is
displayed in each rectangle.
Constructors of GridLayout class
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 along with given horizontal and vertical gaps.
import [Link].*;
import [Link].*;
public class MyGridLayout {
JFrame f;
MyGridLayout() {
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
// adding buttons to the frame
[Link](b1); [Link](b2); [Link](b3);
[Link](b4); [Link](b5); [Link](b6);
[Link](b7); [Link](b8); [Link](b9);
a. 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.
JButton class declaration
public class JButton extends AbstractButton implements Accessible
Constructors:
• JButton()
• JButton(String s)
• JButton(Icon i)
• JButton(String s, Icon i)
Methods
• void setText(String s)
• String getText()
• void setEnabled(boolean b)
• void setIcon(Icon b)
• Icon getIcon()
• void setMnemonic(int a)
• void addActionListener(ActionListener a)
b. 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.
JCheckBox class declaration
public class JCheckBox extends JToggleButton implements Accessible
Constructors:
• JCheckBox()
• JCheckBox(String text)
• JCheckBox(String text, boolean selected)
• JCheckBox(Action a)
Methods
• AccessibleContext getAccessibleContext()
• protected String paramString()
c. Java JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a scroll
pane to display a large component or a component whose size can change dynamically.
Constructors:
• JScrollPane()
• JScrollPane(Component)
• JScrollPane(int, int)
• JScrollPane(Component, int, int)
Methods
• setColumnHeaderView(Component)
• setRowHeaderView(Component)
• setCorner(String, Component)
d. JDialogs
The JDialog control represents a top level window with a border and a title used to take some form of input
from the user. It inherits the Dialog class.
Unlike JFrame, it doesn't have maximize and minimize buttons.
JDialog class declaration
1. public class JDialog extends Dialog implements WindowConstants, Accessible, Root PaneContainer
Constructors:
• JDialog()
• JDialog(Frame owner)
• JDialog(Frame owner, String title, boolean modal)
Methods:
• setLayout(LayoutManager m)
• setJMenuBar(JMenuBar m)
• add(Component c)
• isVisible(boolean b)
• update(Graphics g)
• remove(Component c)
• getGraphics()
• getLayeredPane()
• setContentPane(Container c)
• setLayeredPane(JLayeredPane l)
• setRootPane(JRootPane r)
• getJMenuBar()