0% found this document useful (0 votes)
4 views28 pages

Java Thread Life Cycle and Communication

The document contains a question bank for a Java programming course, focusing on topics such as thread life cycle, inter-thread communication, collection framework, and data structures like HashMap and TreeMap. It provides detailed explanations and example code for concepts like producer-consumer problem, thread priorities, and the differences between various collection types. Each question is associated with a specific mark allocation, indicating its importance in the assessment.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views28 pages

Java Thread Life Cycle and Communication

The document contains a question bank for a Java programming course, focusing on topics such as thread life cycle, inter-thread communication, collection framework, and data structures like HashMap and TreeMap. It provides detailed explanations and example code for concepts like producer-consumer problem, thread priorities, and the differences between various collection types. Each question is associated with a specific mark allocation, indicating its importance in the assessment.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

4 & 8 MARKS (QUESTION BANK) Mid – 2

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
...

Q25: Differentiate between multi-tasking and multi threading. (4M)


Q26: Explain Thread priorities with example. (4M)
Ans: In java programming language, every thread has a property called priority. Most of the scheduling
algorithms use the thread priority to schedule the execution sequence.
In java, the thread priority range from 1 to 10. Priority 1 is considered as the lowest priority, and priority 10
is considered as the highest priority. The thread with more priority allocates the processor first.
The java programming language Thread class provides two methods setPriority(int), and getPriority( ) to
handle thread priorities.
The Thread class also contains three constants that are used to set the thread priority. They are:
• MAX_PRIORITY - It has the value 10 and indicates highest priority.
• NORM_PRIORITY - It has the value 5 and indicates normal priority.
• MIN_PRIORITY - It has the value 1 and indicates lowest priority.

The default priority of any thread is 5 (i.e. NORM_PRIORITY).

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:

Q29: Differentiate between HashSet and TreeSet. (4M)


Q30: Explain PriorityQueue. (4M)
Ans: PriorityQueue is also class that is defined in the collection framework that gives us a way for
processing the objects on the basis of priority. It is already described that the insertion and deletion of
objects follows FIFO pattern in the Java queue. However, sometimes the elements of the queue are needed
to be processed according to the priority, that's where a PriorityQueue comes into action.
PriorityQueue Class Declaration
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
Example Code:
import [Link].*;

class TestCollection12 {
public static void main(String args[]) {
// Create a PriorityQueue of Strings
PriorityQueue<String> queue = new PriorityQueue<String>();

// Add elements to the queue


[Link]("Amit"); OUTPUT:
[Link]("Vijay");
[Link]("Karan"); head:Amit
[Link]("Jai"); head:Amit
[Link]("Rahul"); iterating the queue elements:
Amit
Jai
// Display the head of the queue
Karan
[Link]("head: " + [Link]()); Vijay
[Link]("head: " + [Link]()); Rahul
after removing two elements:
// Iterate through the queue elements Jai
[Link]("Iterating the queue elements:"); Rahul
Iterator<String> itr = [Link](); Karan
while ([Link]()) { Vijay
[Link]([Link]());
}

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]());
}
}
}

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)
Q32: Explain Hashtable and Dictionary. (4M)
Ans: Hashtable
Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary class and
implements the Map interface.
Points to remember

• A Hashtable is an array of a list. Each list is known as a bucket.


• The position of the bucket is identified by calling the hashcode() method.
• A Hashtable contains values based on the key.
• Java Hashtable class contains unique elements.
• Java Hashtable class doesn't allow null key or value.
• Java Hashtable class is synchronized.
• The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
Hashtable class declaration
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable
Methods
• clear()
• clone()
• String toString()
• Collection values()
• boolean contains(Object value)
• boolean containsValue(Object value)
• boolean containsKey(Object key)
• boolean isEmpty()
• int size(), entrySet(), elements(), hashCode(), keys(), keySet(), equals(Object o)
Dictionary
Dictionary is an abstract class that represents a key/value storage repository and operates much like Map.
Given a key and value, you can store the value in a Dictionary object. Once the value is stored, you can
retrieve it by using its key. Thus, like a map, a dictionary can be thought of as a list of key/value pairs.
Methods
• Enumeration elements( )
• Object get(Object key)
• boolean isEmpty( )
• Enumeration keys( )
• Object put(Object key, Object value)
• Object remove(Object key)
• int size( )
Note: The Dictionary class is obsolete (out of date). You should implement the Map interface to obtain
key/value storage functionality.
Q33: Explain Map interface its classes and sub interfaces (HashMap, TreeMap). (8M)
Ans: Java Map Interface :-
A map contains values on the basis of key, i.e. key and value
pair. Each key and value pair is known as an entry. A Map
contains unique keys.
A Map is useful if you have to search, update or delete
elements on the basis of a key.

Hash Map:

• Java HashMap contains values based on the key.


• Java HashMap contains only unique keys.
• Java HashMap may have one null key and multiple null values.
• Java HashMap is non synchronized.
• Java HashMap maintains no order.
• The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

HashMap class declaration


public class HashMap<K,V> extends AbstractMap<K,V> implements Map <K,V>, Cloneable, Serializable
K: It is the type of keys maintained by this map.
V: It is the type of mapped values.

Example:
import [Link];

public class HashMapExample {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
[Link]("Alice", 30);
[Link]("Bob", 25);
[Link]("Charlie", 35);
OUTPUT:
[Link]("Age of Alice: " + [Link]("Alice")); Age of Alice: 30
[Link]("All keys: " + [Link]()); All keys: [Alice, Charlie, Mahesh]
[Link]("All values: " + [Link]()); All values: [30, 35, 25]

}
}
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.

TreeMap Class Declaration


1. public class TreeMap<k ,v> extends AbstractMap<k ,v> implements
NavigableMap<k ,v>, Cloneable, Serializable
2. </k></k></k>
• K: It is the type of keys maintained by this map. & V: It is the type of
mapped values.

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.

LinkedHashMap class declaration


public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
o K: It is the type of keys maintained by this map.
o V: It is the type of mapped values.
Example:
METHODS:
import [Link]; V get(Object key)
public class LinkedHashMapExample { void clear()
boolean containsValue(Object value)
public static void main(String[] args) { Set<[Link]<K,V>> entrySet()
Set<K> keySet()
LinkedHashMap<String, Integer> map = new Collection<V> values()
LinkedHashMap<>();
[Link]("Alice", 30);
[Link]("Bob", 25);
[Link]("Charlie", 35); OUTPUT:
[Link]("Insertion Order: " + map); Insertion Order: {Alice=30, Bob=25, Charlie=35}
}
}

Q34: Analyze Legacy classes with example. (8M)


Ans: Steps to Analyze Legacy Classes
1. Understand the Existing Code: Read and understand the purpose of the class and its interactions
with other parts of the system.
2. Document: If documentation is lacking, add comments and document the code as you understand
it.
3. Write Tests: Capture the current behavior by writing unit tests before making any changes.
4. Identify Refactoring Opportunities: Look for improvements such as removing code duplication,
simplifying methods, and improving naming conventions.
5. Refactor the Code: Incrementally refactor the code while ensuring that tests pass.
6. Review and Validate: Collaborate with your team to review changes and ensure that the refactored
code meets the original requirements.
Example: Refactoring a Legacy Class
Original Legacy Class (Before Refactoring)
public class LegacyCalculator {
public double calculate(String operation, double a, double b) {
if ("add".equals(operation)) {
return a + b;
} else if ("subtract".equals(operation)) {
return a - b;
} else if ("multiply".equals(operation)) {
return a * b;
} else if ("divide".equals(operation)) {
if (b != 0) {
return a / b;
} else {
return [Link]; // Error: Division by zero
}
} else {
return [Link]; // Error: Unsupported operation
}
}
}

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].*;

public class LegacyCalculatorTest {

private final LegacyCalculator calculator = new LegacyCalculator();

@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 {

public double add(double a, double b) {


return a + b;
}

public double subtract(double a, double b) {


return a - b;
}

public double multiply(double a, double b) {


return a * b;
}

public double divide(double a, double b) {


if (b != 0) {
return a / b;
} else {
return [Link]; // Error: Division by zero
}
}
public double calculate(String operation, double a, double b) {
switch (operation) {
case "add":
return add(a, b);
case "subtract":
return subtract(a, b);
case "multiply":
return multiply(a, b);
case "divide":
return divide(a, b);
default:
return [Link]; // Error: Unsupported operation
}
}}
Q35: Illustrate Collection Framework with LIST and SET Interface. (8M)
Ans: The Collection framework represents a unified architecture for storing and manipulating a group of
objects. It enhances code efficiency and readability by offering various data structures, including arrays,
linked lists, trees, and hash tables, tailored to different programming needs. It has:
• Interfaces and its implementations, i.e., classes
• Algorithm

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];

public class ListExample {


public static void main(String[] args) {
// Using ArrayList METHODS:
ArrayList<String> arrayList = new ArrayList<>(); add(int index, E element)
[Link]("Apple"); add(E e)
[Link]("Banana"); clear()
[Link]("Apple"); // Allows duplicate equals(Object o)
hashCode()
[Link]("ArrayList: " + arrayList); get(int index)
isEmpty()
contains(Object o)
// Using LinkedList
remove(int index)
LinkedList<String> linkedList = new LinkedList<>(); remove(Object o)
[Link]("Car");
[Link]("Bike");
[Link]("Car"); // Allows duplicate

[Link]("LinkedList: " + linkedList);


}
}

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

[Link]("LinkedHashSet: " + linkedHashSet);

// 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.

Swing Class Hierarchy Overview

1. [Link]: The root class of all Java classes.


2. [Link]: Defines the basic graphical characteristics of components (e.g., size, shape, etc.).
3. [Link]: Extends Component to hold and manage other components.
4. [Link]: A subclass of Container that provides additional features like pluggable look
and feel, double buffering, etc.
5. Swing Components: Derived from JComponent, providing UI elements.

Class Hierarchy in Detail

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.

Features of Swing Class Hierarchy

1. Lightweight Components: Unlike AWT,


Swing components are not dependent on
native OS.
2. Pluggable Look and Feel: Customize UI
appearance.
3. Event-Driven Architecture: Handles user
interactions through listeners.
Q38: Differentiate between Applet and Application. (4M)
Ans:
Q39: Implement a Java Program for mouse events. (4M)
import [Link];
import [Link];
import [Link];

import [Link].*;

class App extends JFrame implements MouseListener {


JFrame actualWindow;
JLabel message;
App() {
Font myFont = new Font("Verdana",[Link], 30);
actualWindow = new JFrame("Mouse Tracking");
message = new JLabel("Mouse Events");

[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.

Commonly used Methods of AbstractButton class:


• void setText(String s) - Set text on button
• String getText() - Return text of the button
• void setEnabled(boolean b) - Enable or Disable the button
• void setIcon(Icon b) - Set icon on button
• Icon getIcon() - Get icon on button
• void setMnemonic(int a) - set mnemonic on button
• void addActionListener(ActionListener a) - add action listener to this object
Q41: Explain Graphics class with suitable example. (4M)
Ans: The Graphics class is part of the [Link] package and is used to draw shapes, text, and images on
components like panels, frames, and canvases in Java. It provides a variety of methods to perform basic
drawing operations.
Commonly used methods of Graphics class:
• public abstract void drawString(String str, int x, int y)
• public void drawRect(int x, int y, int width, int height)
• public abstract void fillRect(int x, int y, int width, int height)
• public abstract void drawOval(int x, int y, int width, int height)
• public abstract void fillOval(int x, int y, int width, int height)
• public abstract void drawLine(int x1, int y1, int x2, int y2)
• public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)
• public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
• public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
• public abstract void setColor(Color c)
• public abstract void setFont(Font font)
Example:
import [Link];
import [Link].*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
[Link]([Link]);
[Link]("Welcome",50, 50);
[Link](20,30,20,300);
[Link](70,100,30,30);
[Link](170,100,30,30);
[Link](70,200,30,30);
[Link]([Link]);
[Link](170,200,30,30);
[Link](90,150,30,30,30,270);
[Link](270,150,30,30,0,180);
}
}
[Link]
1. <html>
2. <body>
3. <applet code="[Link]" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Q42: What is an applet?Explain the life cycle of applet?Implement the parameter passing technique for
applets. (8M)
Ans: 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.

Lifecycle methods for Applet:


The [Link] class 4 life cycle methods and [Link] class provides 1
life cycle methods for an applet.

[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.

Java Plug-in software is responsible to manage life cycle of an Applet.


Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class provides a
method named getParameter(). Syntax:
1. public String getParameter(String parameterName)
Example of using parameter in Applet:
import [Link];
import [Link];
public class UseParam extends Applet{
public void paint(Graphics g){
[Link]("welcome",150,150);
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>

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](b1, [Link]); // b1 will be placed in the North Direction


[Link](b2, [Link]);
[Link](b3, [Link]);
[Link](b4, [Link]);
[Link](b5, [Link]);

[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);

// setting grid layout of 3 rows and 3 columns


[Link](new GridLayout(3,3));
[Link](300,300);
[Link](true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Q44: Discuss the following swing Buttons: a. JButton [Link] [Link] [Link]. (8M)
Ans:

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()

You might also like