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

Java Programs for Basic Concepts

Uploaded by

deepakkothari832
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 views4 pages

Java Programs for Basic Concepts

Uploaded by

deepakkothari832
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

Q1 (b) Write a program for computing (n power 2).

class Square {
public static void main(String[] args) {
int n = 5;
int result = n * n;
[Link]("Square of " + n + " is: " + result);
}
}

Explanation: This program takes an integer `n` and multiplies it by itself to compute n squared (n^2).

Q2 (b) Write a program to showcase Applet HTML tag.


import [Link];
import [Link];

/* <applet code="[Link]" width=200 height=100></applet> */

public class HelloApplet extends Applet {


public void paint(Graphics g) {
[Link]("Hello Applet", 20, 20);
}
}

Explanation: This applet displays 'Hello Applet' on the screen. The HTML comment shows how to embed it

using the <applet> tag.

Q2 (e) Write a program to depict the functionality of border layout.


import [Link].*;
import [Link].*;

public class BorderLayoutExample {


public static void main(String[] args) {
JFrame f = new JFrame("BorderLayout Example");
[Link](new BorderLayout());

[Link](new JButton("North"), [Link]);


[Link](new JButton("South"), [Link]);
[Link](new JButton("East"), [Link]);
[Link](new JButton("West"), [Link]);
[Link](new JButton("Center"), [Link]);

[Link](300, 200);
[Link](true);
}
}

Explanation: This program demonstrates `BorderLayout`, placing buttons in north, south, east, west, and

center regions of the frame.


Q2 (f) Write a program to demonstrate the usage of event handling.
import [Link].*;
import [Link].*;

public class EventHandlingExample {


public static void main(String[] args) {
Frame f = new Frame("Event Handling");
Button b = new Button("Click Me");
[Link](50, 50, 80, 30);

[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked!");
}
});

[Link](b);
[Link](200, 150);
[Link](null);
[Link](true);
}
}

Explanation: This program adds an event listener to a button, and prints a message when the button is

clicked.

Q3 (a) Write a program to implement Invalid Age user defined exception for election voting

case.
class InvalidAgeException extends Exception {
InvalidAgeException(String s) {
super(s);
}
}

public class Voting {


static void checkAge(int age) throws InvalidAgeException {
if (age < 18)
throw new InvalidAgeException("Not eligible to vote");
else
[Link]("Eligible to vote");
}

public static void main(String[] args) {


try {
checkAge(16);
} catch (InvalidAgeException e) {
[Link]("Exception: " + e);
}
}
}
Explanation: A custom exception is created for invalid voting age. If age is less than 18, an exception is

thrown.

Q3 (b) Write the inter-threaded version program for producer-consumer problem.


class Q {
int num;
boolean valueSet = false;

synchronized void put(int num) {


while (valueSet) {
try { wait(); } catch (Exception e) {}
}
[Link] = num;
valueSet = true;
[Link]("Put: " + num);
notify();
}

synchronized void get() {


while (!valueSet) {
try { wait(); } catch (Exception e) {}
}
[Link]("Got: " + num);
valueSet = false;
notify();
}
}

class Producer implements Runnable {


Q q;
Producer(Q q) { this.q = q; new Thread(this, "Producer").start(); }
public void run() {
int i = 0;
while (true) [Link](i++);
}
}

class Consumer implements Runnable {


Q q;
Consumer(Q q) { this.q = q; new Thread(this, "Consumer").start(); }
public void run() {
while (true) [Link]();
}
}

public class ProducerConsumer {


public static void main(String[] args) {
Q q = new Q();
new Producer(q);
new Consumer(q);
}
}

Explanation: This program demonstrates inter-thread communication where producer puts data and

consumer gets it, using wait/notify.

Q3 (c) Write a program to print the tables of 5 and 100 using a common printable() method

with synchronization.
class Table {
synchronized void printTable(int n) {
for (int i = 1; i <= 10; i++) {
[Link](n + " x " + i + " = " + (n * i));
}
}
}

public class PrintTables extends Thread {


Table t;
int num;
PrintTables(Table t, int num) {
this.t = t;
[Link] = num;
}

public void run() {


[Link](num);
}

public static void main(String[] args) {


Table t = new Table();
PrintTables t1 = new PrintTables(t, 5);
PrintTables t2 = new PrintTables(t, 100);

[Link]();
[Link]();
}
}

Explanation: The program prints tables of 5 and 100 using synchronized method `printTable()` to avoid

conflicts between threads.

Common questions

Powered by AI

Thread coordination in the producer-consumer problem with multiple producer and consumer threads is achieved using synchronized methods combined with `wait()` and `notify()` calls. The `put()` and `get()` methods are synchronized, ensuring mutual exclusion when threads attempt to access the shared resource. If a producer finds the queue full, it calls `wait()`, relinquishing control until notified. A consumer that removes an item from the queue calls `notify()`, awakening the waiting producer. Likewise, if a consumer finds the queue empty, it waits, and a producer calls `notify()` after putting an item. This mechanism avoids busy waiting and ensures efficient usage of CPU resources, allowing smooth coordination among multiple threads .

The `wait()` and `notify()` methods are crucial for facilitating inter-thread communication in the producer-consumer problem. In this implementation, the `produce()` and `consume()` methods are synchronized, ensuring one thread can execute them at a time. When the producer thread has put a new element into the queue, it calls `notify()` to signal the consumer thread that it can proceed to get the element. Conversely, when the consumer finds the queue empty, it calls `wait()` to release the lock and leave room for the producer thread to produce a new element. These mechanisms prevent race conditions, ensuring that no thread is blocked indefinitely and data is accessed in a controlled manner .

Synchronization plays a crucial role in ensuring thread safety when printing multiplication tables by using `synchronized` methods to guard critical sections. By synchronizing the `printTable()` method, the program prevents concurrent access to the method across different threads, thereby avoiding conflicts or jumbled output, which can occur if two threads print their tables simultaneously. This synchronization mitigates race conditions, ensuring the orderly and complete execution of the print operations for both tables, reflecting accurately on the console .

The 'HelloApplet' program functions by overriding the `paint()` method of the `Applet` class to draw the string 'Hello Applet' on the applet area. When integrated into a web browser using the `<applet>` HTML tag, the applet's bytecode is loaded by the browser's Java plugin, which subsequently invokes the applet's lifecycle methods—`init()`, `start()`, and `paint()`. This lifecycle management allows the program to interact dynamically with the web browser, rendering textual graphics directly onto the applet's display area when viewed in a compatible web environment .

The custom exception class `InvalidAgeException` alters the control flow by providing a mechanism to handle errors gracefully when an invalid age is supplied. If the `checkAge()` function encounters an age less than 18, it throws an `InvalidAgeException`. This exception is then caught in the `main()` method's catch block, which prevents the normal flow from occurring and allows a specific error message to be displayed to the user. This exception handling ensures that the program continues running without crashing, as the exception is handled and not propagated further .

In the `BorderLayout` example, graphical components are added to different directional regions (North, South, East, West, Center) of a JFrame. The `BorderLayout`, a versatile layout manager, arranges components relative to the main frame, aligning them toward the specified side. The example adds buttons to these positions, with each button occupying the entire extent of the assigned region, except when multiple components are placed. The central button stretches to fill any remaining space after all directional components are placed, illustrating how `BorderLayout` uses the container's entire area efficiently .

Using a synchronized method `printTable()` is an effective approach for handling concurrent printing tasks because it ensures mutual exclusion. When one thread calls the `printTable()` method, it locks the `Table` object, preventing other threads from executing the method until the current thread completes its execution. This synchronization prevents conflicting access and ensures that each multiplication table prints accurately and completely without interleaving lines from different tables, which would occur if two threads attempted to access the method simultaneously without synchronization .

Custom exceptions, such as `InvalidAgeException`, offer several advantages over standard exceptions in specific scenarios where domain-specific error handling is needed. They enable a clearer and more descriptive error reporting mechanism tailored to particular application logic, which enhances the readability and maintainability of the code. For instance, using `InvalidAgeException` directly indicates a specific failure point related to age validation, improving semantic clarity compared to more generic exceptions such as `IllegalArgumentException`. Custom exceptions can encapsulate additional context or data relevant to the error condition, assisting in more detailed logging or debugging exploration .

The use of anonymous inner classes in event handling, as seen in the Button example, contributes positively to code organization and readability by localizing the event handling logic within the component that triggers it, such as the Button. This approach reduces the need for separate, named implementations or inner classes elsewhere in the code, which can obscure flow and context. Instead, the event handling code is directly associated with the component in question, making it clear what actions are taken when the button is clicked and improving readability by keeping related logic together .

The Java applet example highlights several differences from standalone applications. Applets are designed to run within a browser or applet viewer, which brings implications such as greater restrictions on their execution environment for security reasons, including limitations on file system access and network capabilities. This sandbox model contrasts with standalone applications, which have fewer restrictions, offering broader access to system resources. Additionally, applets require a browser plugin to execute, a requirement that has lowered their usability with modern browsers moving away from plugin-based architectures .

You might also like