Untitled Presentation
Untitled Presentation
Practical 7
// Base class (Parent) // Base class (Grandparent)
class Animal { class Animal {
void eat() {
void eat() {
System.out.println("This animal eats
System.out.println("This animal eats food."); food.");
} }
} }
// Constructor
BoxRoom(double l, double w, double h) {
super(l, w); // Call constructor of Room
height = h;
}
Practical 8
1 2 3
Practical 10
class MyThread extends Thread {
// Thread 1: Grinding beans // Main class public MyThread(String name) {
class Grinder extends Thread { public class Coffee Machine { super(name);
public void run() {
public static void main(String[] }
System.out.println("Grinding coffee
beans..."); args) {
try { Grinder grinder = new public void run() {
Thread.sleep(2000); // Simulate time Grinder(); for (int i = 1; i <= 5; i++) {
} catch (InterruptedException e) { Heater heater = new Heater(); System.out.println(getName() + " is running
System.out.println("Grinding Brewer brewer = new with priority " + getPriority() + ": Count " + i);
interrupted"); Brewer(); try {
}
System.out.println("Beans are ground.");
Thread.sleep(100); // To better see the
} // Start all tasks simultaneously output
} grinder.start(); } catch (InterruptedException e) {
heater.start(); System.out.println(getName() + "
// Thread 2: Heating water interrupted.");
class Heater extends Thread { try { }
public void run() { grinder.join(); // Wait for }
System.out.println("Heating water...");
grinding to complete }
try {
Thread.sleep(3000); // Simulate time heater.join(); // Wait for }
} catch (InterruptedException e) { heating to complete
System.out.println("Heating } catch (InterruptedException public class ThreadPriorityExample {
interrupted"); e) { public static void main(String[] args) {
} System.out.println("Main // Create three threads
System.out.println("Water is hot."); interrupted"); MyThread t1 = new MyThread("Thread-1
}
} (Low)");
}
MyThread t2 = new MyThread("Thread-2
// Thread 3: Brewing coffee // Start brewing after grinding (Medium)");
class Brewer extends Thread { and heating are done MyThread t3 = new MyThread("Thread-3
public void run() { brewer.start(); (High)");
System.out.println("Brewing coffee..."); }
try { } // Set priorities
Thread.sleep(1500); // Simulate time
} catch (InterruptedException e) {
t1.setPriority(Thread.MIN_PRIORITY); //
System.out.println("Brewing Priority 1
interrupted"); t2.setPriority(Thread.NORM_PRIORITY); //
} Priority 5
System.out.println("Coffee is ready! t3.setPriority(Thread.MAX_PRIORITY); //
☕"); Priority 10
}
}
// Start all threads
t1.start();
t2.start();
t3.start();}} 2 2
Practical 11
import java.util.Scanner;
// Step 1: Define your own exception
// Custom Exception
class
class AuthenticationFailureException extends Exception
class MyOwnException extends
{
Exception {
public AuthenticationFailureException(String
public My Own Exception(String
message) {
message) {
super(message);
super(message);
}
}
}
}
public class PasswordChecker {
// Step 2: Class with a method that
throws the custom exception
// Method to authenticate password
public class Custom Exception Demo {
public static void authenticate(String inputPassword)
throws AuthenticationFailureException {
// Method to check age for voting
String correctPassword = "Secret123"; //
static void checkAge(int age) throws
Hardcoded correct password for demo
IOException {
if (age < 18) {
if (!inputPassword.equals(correctPassword)) {
throw new IOException("Age
throw new
must be 18 or older to vote.");
AuthenticationFailureException("Authentication failed:
} else {
Incorrect password!");
System.out.println("You are
} else {
eligible to vote.");
System.out.println("Access granted ✅");
}
}
}
}
// Main method
// Main method
public static void main(String[] args) {
public static void main(String[] args) {
int userAge = 16; // You can
Scanner scanner = new Scanner(System.in);
change this to test
System.out.print("Enter your password: ");
try {
String userPassword = scanner.nextLine();
checkAge(userAge);
} catch (My Own Exception e) {
try {
System.out.println("Exception
authenticate(userPassword);
caught: " + e.getMessage());
} catch (AuthenticationFailureException e) {
}
System.out.println(e.getMessage());
}
}
}
Practical 12 Practical 13
scanner.close();
// Checkboxes for hobbies
import java.applet.Applet;
music = new Checkbox("Music");
import java.awt.*;
sports = new Checkbox("Sports");
import java.awt.event.*;
reading = new Checkbox("Reading");
/* <applet code="RadioCheckDemo" width="400"
add(new Label("Select Hobbies:"));
height="300"></applet> */
add(music);
add(sports);
public class RadioCheckDemo extends Applet
add(reading);
implements ItemListener {
String gender = "";
music.addItemListener(this);
String hobbies = "";
sports.addItemListener(this);
reading.addItemListener(this);
CheckboxGroup genderGroup;
}
Checkbox male, female;
public void itemStateChanged(ItemEvent e) {
Checkbox music, sports, reading;
// Handle gender selection
gender =
public void init() {
genderGroup.getSelectedCheckbox().getLabel(
// Set layout
);
setLayout(new FlowLayout());
// Handle hobbies selection
// Radio Buttons (using CheckboxGroup)
hobbies = "";
genderGroup = new CheckboxGroup();
if (music.getState()) hobbies += "Music ";
male = new Checkbox("Male",
if (sports.getState()) hobbies += "Sports ";
genderGroup, false);
if (reading.getState()) hobbies += "Reading
female = new Checkbox("Female",
";
genderGroup, false);
repaint();
// Add gender checkboxes
}
add(new Label("Select Gender:"));
add(male);
public void paint(Graphics g) {
add(female);
g.drawString("Selected Gender: " +
gender, 20, 200);
// Register item listeners
g.drawString("Selected Hobbies: " +
male.addItemListener(this);
hobbies, 20, 220);
female.addItemListener(this);
}
}
Practical 14
import java.awt.*; // Handle window close
import java.awt.event.*; addWindowListener(new
WindowAdapter() {
public class ButtonDemo extends Frame public void
implements ActionListener { windowClosing(WindowEvent e) {
Button okButton, resetButton, cancelButton; dispose();
Label messageLabel; }
});
public ButtonDemo() { }
// Set layout
setLayout(new FlowLayout()); // Handle button clicks
public void actionPerformed(ActionEvent
// Create buttons e) {
okButton = new Button("OK"); String command =
resetButton = new Button("Reset"); e.getActionCommand();
cancelButton = new Button("Cancel");
if (command.equals("OK")) {
// Add buttons to the frame messageLabel.setText("You clicked
add(okButton); OK.");
add(resetButton); } else if (command.equals("Reset")) {
add(cancelButton); messageLabel.setText("Form
reset.");
// Create and add a label } else if (command.equals("Cancel")) {
messageLabel = new Label("Click a button."); messageLabel.setText("Operation
add(messageLabel); cancelled.");
}
// Register listeners }
okButton.addActionListener(this);
resetButton.addActionListener(this); // Main method
cancelButton.addActionListener(this); public static void main(String[] args) {
new ButtonDemo();
// Frame settings }
setTitle("Button Example"); }
setSize(300, 150);
setVisible(true);
Practical 14
import java.awt.*; // Handle window close
import java.awt.event.*; addWindowListener(new
WindowAdapter() {
public class ButtonDemo extends Frame public void
implements ActionListener { windowClosing(WindowEvent e) {
Button okButton, resetButton, cancelButton; dispose();
Label messageLabel; }
});
public ButtonDemo() { }
// Set layout
setLayout(new FlowLayout()); // Handle button clicks
public void actionPerformed(ActionEvent
// Create buttons e) {
okButton = new Button("OK"); String command =
resetButton = new Button("Reset"); e.getActionCommand();
cancelButton = new Button("Cancel");
if (command.equals("OK")) {
// Add buttons to the frame messageLabel.setText("You clicked
add(okButton); OK.");
add(resetButton); } else if (command.equals("Reset")) {
add(cancelButton); messageLabel.setText("Form
reset.");
// Create and add a label } else if (command.equals("Cancel")) {
messageLabel = new Label("Click a button."); messageLabel.setText("Operation
add(messageLabel); cancelled.");
}
// Register listeners }
okButton.addActionListener(this);
resetButton.addActionListener(this); // Main method
cancelButton.addActionListener(this); public static void main(String[] args) {
new ButtonDemo();
// Frame settings }
setTitle("Button Example"); }
setSize(300, 150);
setVisible(true);
Practical 15
import java.awt.*; // Disable Black menu item if (command.equals("Red")) {
import java.awt.event.*; blackItem.setEnabled(false); setBackground(Color.RED);
statusLabel.setText("Selected
public class ColorMenuDemo extends // Add menu to menu bar Color: Red");
Frame implements ActionListener { menuBar.add(colorMenu); } else if (command.equals("Green"))
MenuBar menuBar; {
Menu colorMenu; // Set menu bar to the frame setBackground(Color.GREEN);
MenuItem redItem, greenItem, setMenuBar(menuBar); statusLabel.setText("Selected
blueItem, blackItem; Color: Green");
Label statusLabel; // Add action listeners } else if (command.equals("Blue")) {
redItem.addActionListener(this); setBackground(Color.BLUE);
public ColorMenuDemo() { statusLabel.setText("Selected
// Create the label to show greenItem.addActionListener(this); Color: Blue");
selected color blueItem.addActionListener(this); }
statusLabel = new Label("Select a }
color from the menu."); // Frame settings
add(statusLabel, setTitle("Color Menu Demo"); // Main method
BorderLayout.SOUTH); setSize(300, 150); public static void main(String[] args) {
setLayout(new BorderLayout()); new ColorMenuDemo();
// Create menu bar and menu setVisible(true); }
menuBar = new MenuBar(); }
colorMenu = new Menu("Colors"); // Handle window close
addWindowListener(new
// Create menu items WindowAdapter() {
redItem = new MenuItem("Red"); public void
greenItem = new windowClosing(WindowEvent e) {
MenuItem("Green"); dispose();
blueItem = new MenuItem("Blue"); }
blackItem = new });
MenuItem("Black"); }
Practical 15
Practical 16
import java.awt.*; Answer 3:- import java.awt.*;
import java.awt.event.*; import java.awt.event.*;
public class GridDemo extends Frame { public class NumberButtons extends Frame
{