[go: up one dir, main page]

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

New Thread State

The document provides a comprehensive overview of Java threading, including the thread life cycle, synchronization, console I/O, applet life cycle, AWT components, and layout managers. It details the various states of a thread, methods for thread synchronization, and the functionalities of Java I/O for reading and writing data. Additionally, it explains the operations of collections like HashSet and HashMap, highlighting their key features and common operations.

Uploaded by

emickghimire
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views16 pages

New Thread State

The document provides a comprehensive overview of Java threading, including the thread life cycle, synchronization, console I/O, applet life cycle, AWT components, and layout managers. It details the various states of a thread, methods for thread synchronization, and the functionalities of Java I/O for reading and writing data. Additionally, it explains the operations of collections like HashSet and HashMap, highlighting their key features and common operations.

Uploaded by

emickghimire
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

CO3

Home Assignment

Answer all the following.

1. Explain thread life cycle in detail.


Thread Life Cycle A thread in Java goes through multiple states during its lifetime. The
Java Virtual Machine (JVM) manages the transition between these states.

New Thread State


● When a thread object is created using the Thread class, it remains in the new state.
● It is just an instance of the Thread class but has not started execution yet.
Runnable State
● The thread enters the runnable state when the start() method is invoked.
● It is ready for execution but may not be running immediately, as CPU scheduling
determines when it runs.
Running State
● The thread transitions from runnable to running when the CPU selects it for execution.
● The code inside the run() method begins to execute.
Blocked State
● A thread enters the blocked state if it tries to access a locked resource.
● It will remain blocked until the resource becomes available.
Waiting State
● A thread moves to the waiting state when it waits indefinitely for another thread’s
signal.
● This happens when calling wait().
Timed Waiting State
● A thread enters the timed waiting state when it waits for a specified time.
● This happens when calling Thread.sleep(milliseconds) or wait(milliseconds).
Terminated State
● Once the execution of run() is completed, the thread enters the terminated state.
● A terminated thread cannot be restarted.

2. Illustrate thread synchronization.

Thread Synchronization is used to coordinate and ordering of the execution of the


threads in a multi-threaded program. There are two types of thread synchronization are
mentioned below:

 Mutual Exclusive

 Cooperation (Inter-thread communication in Java)

import java.io.*;
import java.util.*;
class Counter {

private int count = 0;


// synchronized method
public synchronized void increment() {
count++;
}
public int getCount() {

return count;

public class SyncExample {


public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
// Creating two threads

Thread t1 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}

});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}

});

t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Count is: " + counter.getCount());
}
}
3. Illustrate the ways of taking input from console input device and writing output to the
console output device
Java I/O is a mechanism for efficiently handling input and output operations. It uses
streams to read and write data. The java.io package contains all necessary classes for
performing I/O operations, including file handling. (p.290)
Console Input and Output in Java:
Method /
Purpose Example
Class

Input System.in int i = System.in.read(); (reads a byte)

System.out.println("Message"); (standard
Output System.out
output)

Error System.err System.err.println("Error"); (standard error)

System.out.println("Simple message");
System.err.println("Error message");

// Reading input from console (reads one character as ASCII)


int i = System.in.read();
System.out.println((char) i);
Explanation:
 System.in: Reads input from the keyboard (console).
 System.out: Writes output to the screen (console).
 System.err: Writes error messages to the console.
4. Explain Applet life cycle.
Applet Lifecycle
An applet in Java follows a well-defined life cycle consisting of five key stages:
● Initialization: The applet is initialized when it is first loaded.
● Starting: The applet starts execution.
● Painting: The applet performs graphical operations.
● Stopping: The applet stops execution when needed.
● Destruction: The applet is removed from memory.

Method 1: init()
Syntax
public void init()
{
// To initialize objects
}
 This is the first method that is being called
 All the variables are initialized here
 This method is only called once during the run time
 It is generally invoked during the time of initialization
Method 2: start()
Syntax
public void start()
{
// To start the applet code
}
 It is called after the init method
 Used for starting an applet
 It is also used for restarting an applet in case it is stopped
Method 3: paint()
Syntax
public void paint(Graphics graphics)
{
// Any shape's code
}
 This method is used for painting various shapes like squares, rectangles, etc.
 It has parameter of type graphic class, which enables the feature of painting in the
applet.
 The graphics class parameter contains graphics context which is used for displaying the
output of the applet.
Method 4: stop()
Syntax
public void stop()
{
// To stop the applet code
}
 This method is invoked whenever the browser is stopped, minimized, or because of
abrupt failure within an application.
 Generally after the stop method, the start method can be used.
 It deals with the cleaning of the code, the method is called when the browser leaves the
HTML document when the applet is running.
Method 5: destroy()
Syntax
public void destroy()
{
// To destroy the applet
}
 Once we are done with the applet work, this method destroys the application and is
invoked only once.
 Once the applet is destroyed, it can’t be restored.
 It is called when the environment determines that the applet needs to be completely
removed from the memory.
import java.applet.Applet;
import java.awt.Graphics;
public class LifeCycleDemo extends Applet {
public void init() {
System.out.println("Applet Initialized");
}
public void start() {
System.out.println("Applet Started");
}
public void paint(Graphics g) {
g.drawString("Applet Life Cycle Demo", 50, 100);
}
public void stop() {
System.out.println("Applet Stopped");
}
public void destroy() {
System.out.println("Applet Destroyed");
}
}

Answer all the following.

1. List and explain the AWT components and containers.


Java Abstract Window Toolkit (AWT) is a foundational API for developing graphical user
interfaces (GUI) and window-based applications in Java. It is part of the Java Foundation
Classes (JFC) and provides a means to create platform-independent graphical applications.
AWT Components
AWT provides various built-in components that help in building graphical user interfaces, such
as:
● Buttons: Clickable elements that trigger actions.
● Labels: Used to display text or messages.
● TextFields & TextAreas: Input fields for user text entry.
● Checkboxes & Radio Buttons: Selection controls for user choices.
● Lists & Choice Components: Used for dropdowns and selectable lists.
● Scrollbars: Allow users to navigate significant content.
● Canvases & Panels: Containers used for grouping UI elements and custom drawing
4.2.4 Java AWT Containers
The classes that extend the Container class are known as containers.
Containers act as layers that can hold other AWT components, allowing developers to organise
and
group UI elements within application windows.
There are four primary types of containers in Java AWT
● Window
● Panel
● Frame
● Dialog

Benefits of Using Containers


● Organisation: Containers enable the creation of a well-structured and organised graphical
user interface (GUI) by grouping related components together.
● Reusability: Developers can create reusable panels that encapsulate specific functionalities,
making applications modular and maintainable.
● Layout Management: Layout managers simplify arranging components within containers,
ensuring a consistent and responsive layout across different screen sizes.
AWT Containers: Frame
● A Frame is a top-level container representing a graphical window or dialog box.
● It typically includes a title bar, border, and menu bar.
Ways to Create an AWT Frame
By Extending the Frame Class (Inheritance)
public class MyFrame extends Frame {
// Frame implementation
}
By Creating an Object of the Frame Class (Association)
Frame myFrame = new Frame()
AWT Containers: Panel
● A Panel is a lightweight container for grouping related UI components within a Frame or
another container.
● It is often used to organise UI elements within a Frame.
Syntax for Creating a Panel
Panel myPanel = new Panel();
AWT Containers: Window
● A Window is a top-level container similar to a Frame but lacks a title bar and border.
● Although Window is a separate class, additional windows in AWT applications are often
implemented using the Frame class.
● Like other containers, a Window can hold various UI components.
Syntax for Creating a Window
Frame myWindow = new Frame("My Application Window");
AWT Containers: Dialog
● A Dialog is a temporary window to retrieve user input or display important information.
● It includes a title bar and border and can contain interactive elements like buttons.
Types of Dialogs in AWT
● Generic Dialog: A modal dialog that prevents interaction with the parent window until the
user interacts with the dialog.
Dialog myDialog = new Dialog(parentFrame, "Dialog Title");
● FileDialog: A platform-specific dialog used for opening or saving files.
FileDialog fileDialog = new FileDialog(parentFrame, "Open File");

2. Illustrate the functionalities offered by swing layout managers.


Layout managers play a crucial role in Java Swing applications by determining
how visual components are arranged within a container. They help in
managing the size, position, and alignment of components dynamically,
ensuring a structured and responsive user interface.

Types of Layout Managers in Java

Java provides six primary layout managers, each offering a unique way to
organize components within a container.

FlowLayout

The FlowLayout arranges components in a container similarly to how words


appear on a page, filling the top row from left to right and wrapping to the next
line when necessary.

Key Features

● Components are displayed in the order they are added.


● If the container’s width is insufficient, the components wrap to the next line.

● The vertical and horizontal gaps between components can be customised.

● Components can be aligned to the left, center, or right.

BorderLayout

The BorderLayout arranges components along the edges of a container or in


the central area. It divides the container into five regions: North (top), South
(bottom), East (right), West (left), and Center (middle).

Key Features

● Components placed in the North or South get their preferred height but
stretch to match the container’s width.

● Components placed in the East or West receive their preferred width but
adjust their height according to available space.

● The Center component occupies the remaining space without retaining its
preferred height or width.

GridLayout

The GridLayout organises components in a grid-like structure with equal-sized


cells. Components are

added from left to right, row by row.

Key Features

● Each component occupies exactly one grid cell.

● All cells are equal in size and adjust automatically when the container is
resized.

● The order of components in the grid is based on the sequence in which they
are added.

GridBagLayout
The GridBagLayout is a more flexible and powerful grid-based layout manager
that allows components to span multiple rows or columns while maintaining
proportional resizing.

Key Features

● Unlike GridLayout, cells can have different sizes depending on the


component requirements.

● Horizontal and vertical gaps between components remain uniform.

● Developers can define custom alignment rules for components within the
grid.

BoxLayout

The BoxLayout arranges components in a single row (horizontally) or a single


column (vertically). It does not support both orientations simultaneously.

Key Features

● If arranged horizontally, all components have the same height, which is


equal to the height of the tallest component.

● If arranged vertically, all components have the same width, which is equal to
the width of the

widest component.

● Useful for structuring toolbars, side panels, or menu sections.

CardLayout

The CardLayout stacks multiple components on top of each other, similar to a


deck of cards, where only the topmost component is visible at any given time.

Key Features

● Each component is treated as a card in a deck.

● The first added component appears on top by default.


● Cards can be displayed horizontally or vertically.

● There are no gaps between the edges of the container and the cards.
● It is useful for creating tabbed interfaces or step-by-step navigation screens.
3. Demonstrate the working of available methods to perform read
and write operations on a file.
To demonstrate the working of file read and write operations in Java, we use classes
from the java.io package such as FileWriter, FileReader, BufferedWriter, BufferedReader,
FileInputStream, and FileOutputStream.
1. Using FileWriter and FileReader (Character Streams)
FileWriter
FileWriter is useful to create a file writing characters into it.
 This class inherits from the OutputStream class
 FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a
FileOutputStream.
 FileWriter creates the output file if it is not present already.

FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
 This class inherited from the InputStreamReader Class.
 FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a
FileInputStream.

import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
public class FileReadWriteExample {
public static void main(String[] args) {
// Writing to file
try {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello, this is a file writing example using FileWriter.");
writer.close();
System.out.println("Data written successfully.");
} catch (IOException e) {
System.out.println("An error occurred during writing.");
e.printStackTrace();
}
// Reading from file
try {
FileReader reader = new FileReader("example.txt");
int ch;
while ((ch = reader.read()) != -1) {
System.out.print((char) ch);
}
reader.close();
} catch (IOException e) {
System.out.println("An error occurred during reading.");
e.printStackTrace();
}
}
}
2. Using BufferedWriter and BufferedReader
Definition:
BufferedWriter is used to write text to a character output stream, buffering
characters to provide efficient writing.
Definition:
BufferedReader is used to read text from an input stream efficiently, buffering
characters to enable efficient reading of lines or arrays.
import java.io.*;
public class BufferedReadWriteExample {
public static void main(String[] args) {
// Writing with BufferedWriter
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("buffered.txt"));
writer.write("Buffered writing example.");
writer.newLine();
writer.write("Second line of text.");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}

// Reading with BufferedReader


try {
BufferedReader reader = new BufferedReader(new FileReader("buffered.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Class/Method Operation Stream Type
FileWriter.write() Write Character
FileReader.read() Read Character
BufferedWriter.write() Write Character (Buffered)
BufferedReader.readLine() Read line by line Character (Buffered)
FileOutputStream.write() Write bytes Byte
FileInputStream.read() Read bytes Byte
Class/Method Operation Stream Type

4. Explain the operation available with the collections: HashSet and


HashMap
The HashMap class implements the Map interface and is used to store key-value pairs. It
employs hashing techniques to provide efficient data access. ● Hashing allows the conversion
of large objects or strings into compact values for easy retrieval. ● The HashMap class is
widely used in applications dealing with large datasets. ● Internally, the HashSet class uses
HashMap to store elements uniquely.
A HashMap stores data in key-value pairs. It:
 Allows null keys and values.
 Does not guarantee order.
 Provides fast access via keys.

✅ Common Operations:
Operation Description

put(key, value) Inserts a key-value pair.

get(key) Returns the value for the key.

remove(key) Removes the key and its value.

containsKey(key) Checks if the key exists.

containsValue(value) Checks if the value exists.

Example
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
// Creating a HashMap
Map<String, Integer> map = new HashMap<>();

// Adding key-value pairs


map.put("Alice", 10);
map.put("Bob", 20);
map.put("Charlie", 30);

// Retrieving a value
System.out.println("Value for 'Alice': " + map.get("Alice"));

// Iterating over key-value pairs


for (Map.Entry<String, Integer> entry : map.entrySet()) {
Object-Oriented Programming
460
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + ": " + value);
}

// Removing a key-value pair


map.remove("Charlie");

// Checking the presence of a key


if (map.containsKey("Bob")) {
System.out.println("Map contains key 'Bob'.");
}
}
}
The HashSet class implements the Set interface.
● It utilises a hash table to store elements, ensuring that unique values are maintained.
● Since it uses hashing, the retrieval operations are faster.
A HashSet is a collection that:
 Stores unique elements (no duplicates).
 Does not maintain insertion order.
 Is part of the java.util package.
✅ Common Operations:

Operation Description

add(element) Adds an element to the set.

remove(element) Removes the element from the set.


Operation Description

contains(element) Checks if the element exists in the set.

isEmpty() Returns true if the set is empty.

Example
import java.util.*;
public class TestJavaCollection7 {
public static void main(String args[]) {
HashSet<String> set = new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");

Iterator<String> itr = set.iterator();


while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}

You might also like