[go: up one dir, main page]

0% found this document useful (0 votes)
3 views14 pages

Untitled Presentation

The document contains multiple Java code examples demonstrating various programming concepts such as character manipulation, constructors, inheritance, threading, exception handling, and GUI components. Each section illustrates specific functionalities like creating classes, using wrapper classes, implementing multilevel inheritance, and handling user input through graphical interfaces. Overall, it serves as a practical guide for understanding fundamental Java programming techniques.

Uploaded by

Rehaan Shaikh 9A
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)
3 views14 pages

Untitled Presentation

The document contains multiple Java code examples demonstrating various programming concepts such as character manipulation, constructors, inheritance, threading, exception handling, and GUI components. Each section illustrates specific functionalities like creating classes, using wrapper classes, implementing multilevel inheritance, and handling user input through graphical interfaces. Overall, it serves as a practical guide for understanding fundamental Java programming techniques.

Uploaded by

Rehaan Shaikh 9A
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
You are on page 1/ 14

public class Character Wrapper Demo { public class Integer Conversion Demo {

public static void main(String[] args) {


public static void main(String[] args) {
// Declare and initialize a primitive char
char ch = 'A'; // Create an Integer object
Integer intObj = Integer.valueOf(100);
// Create a Character object (wrapper class)
Character charObj = ch; // Convert to byte
byte byteValue = intObj.byteValue();
// Check if the character is a letter
System.out.println(ch + " is a letter? " + // Convert to short
Character.isLetter(ch));
short shortValue =
// Check if the character is a digit intObj.shortValue();
char digit Char = '5';
System.out.println(digitChar + " is a digit? " + // Convert to double
Character.isDigit(digitChar)); double doubleValue =
intObj.doubleValue();
// Convert to lowercase
char lower = Character.toLowerCase(ch);
// Display the results
System.out.println("Lowercase of " + ch + " is " + lower);
System.out.println("Integer object: " +
// Convert to uppercase intObj);
char small = 'b'; System.out.println("Converted to
char upper = Character.toUpperCase(small); byte: " + byteValue);
System.out.println("Uppercase of " + small + " is " + upper); System.out.println("Converted to
short: " + shortValue);
// Check if the character is whitespace System.out.println("Converted to
char spaceChar = ' ';
double: " + doubleValue);
System.out.println("Is space a whitespace? " +
Character.isWhitespace(spaceChar)); }
}
// Check if a character is a defined Unicode character
System.out.println(ch + " is defined in Unicode? " +
Character.isDefined(ch));

// Checking for special character


char special Char = '@';
System.out.println(special Char + " is a letter or digit? " +
Character.isLetterOrDigit(special Char));
}
Practical 6
}
public class Student { # Define a function to add two complex numbers
// Data members def add_complex(c1, c2):
String name; return c1 + c2
int age;
# Input complex numbers from the user
// Default constructor real1 = float(input("Enter real part of first complex
Student() { number: "))
name = "Unknown"; imag1 = float(input("Enter imaginary part of first
age = 0; complex number: "))
System.out.println("Default constructor called."); real2 = float(input("Enter real part of second
} complex number: "))
imag2 = float(input("Enter imaginary part of
// Parameterized constructor second complex number: "))
Student(String studentName, int studentAge) {
name = studentName; # Create complex numbers
age = studentAge; complex 1 = complex(real1, imag1)
System.out.println("Parameterized constructor called."); complex 2 = complex(real2, imag2)
}
# Perform addition
// Method to display student details result = add_complex(complex 1, complex 2)
void display() {
System.out.println("Name: " + name + ", Age: " + age); # Display the result
} print(f"The sum of {complex 1} and {complex 2} is
{result}")
// Main method to test constructors
public static void main(String[] args) {
// Using default constructor
Student student1 = new Student();
student1.display();

// Using parameterized constructor


Student student2 = new Student("Alice", 20);
student2.display();
}
}

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.");
} }
} }

// Derived class (Child) // Intermediate class (Parent)


class Dog extends Animal { class Dog extends Animal {
void bark() { void bark() {
System.out.println("The dog barks."); System.out.println("The dog barks.");
}
}
}
}
// Derived class (Child)
// Main class to run the program class Puppy extends Dog {
public class SingleInheṣṣritanceDemo { void weep() {
public static void main(String[] args) { System.out.println("The puppy
Dog ṣ= new Dog(); weeps.");
}
// Call method of base class }
myṣDog.eat();
// Main class to run the program
public class Multilevel Inheritance Demo {
// Call method of derived class public static void main(String[] args) {
myṣDog.bark(); Puppy my Puppy = new Puppy();
}
} // Call method of base class
my Puppy.eat();

// Call method of intermediate class


my Puppy.bark();

// Call method of derived class


my Puppy.weep(); Practical 8
}
// Base class // Main class
classRoom { public class RoomCalculation {
double length; public static void main(String[] args) {
double width; // Create an object of Box Room
Box Room my Room = new Box
// Constructor Roomṣ(5.0, 4.0, 3.0);
Room(double l, double w) {
length = l; // Calculate area and volume
width = w; double area = myRoom.calculate
} Area();
double volume = myRoom.calculate
// Method to calculate area Volume();
double calculateArea() {
return length * width; // Display results
} System.out.println("Area of the room:
} " + area + " square meters");
System.out.println("Volume of the
// Derived class room: " + volume + " cubic meters");
class BoxRoom extends Room { }
double height; }

// Constructor
BoxRoom(double l, double w, double h) {
super(l, w); // Call constructor of Room
height = h;
}

// Method to calculate volume


double calculate Volume() {
return length * width * height;
}
}

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"); }

// Add menu items to menu // Handle menu item clicks


colorMenu.add(redItem); public void
colorMenu.add(greenItem); actionPerformed(ActionEvent e) {
colorMenu.add(blueItem); String command =
colorMenu.add(blackItem); e.getActionCommand();

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
{

public GridDemo() { public NumberButtons() {


// Set the layout to 5 rows and 5 columns // Use FlowLayout or GridLayout for
setLayout(new GridLayout(5, 5)); better alignment
setLayout(new FlowLayout());

// Add 25 buttons to the frame // Create and add buttons labeled 0 to


for (int i = 1; i <= 25; i++) { 5
add(new Button("Button " + i)); for (int i = 0; i <= 5; i++) {
Button btn = new
} Button(String.valueOf(i));
add(btn);
// Frame settings }
setTitle("5x5 Grid Layout");
// Frame settings
setSize(400, 400); setTitle("Number Buttons (0 to 5)");
setVisible(true); setSize(300, 100);
setVisible(true);
// Close operation
// Close the window on click
addWindowListener(new WindowAdapter() { addWindowListener(new
public void windowClosing(WindowEvent WindowAdapter() {
we) { public void
dispose(); windowClosing(WindowEvent we) {
dispose();
} }
}); });
} }

public static void main(String[] args) {


public static void main(String[] args) { new NumberButtons();
new GridDemo(); }
} }
} Practical 17
import java.awt.*;
import java.awt.event.*; import java.awt.*;
import java.awt.event.*;
public class KeyEventDemo extends Frame
implements KeyListener { public class MouseMotionDemo extends Frame implements
MouseMotionListener {

String message = ""; String message = "";


int x = 0, y = 0;
public KeyEventDemo() {
setTitle("Key Event Demo"); public MouseMotionDemo() {
// Set frame layout and size
setTitle("Mouse Motion Listener Demo");
// Set size and layout setSize(400, 300);
setSize(300, 200); setVisible(true);
setLayout(new FlowLayout());
// Add mouse motion listener
// Add key listener to frame addMouseMotionListener(this);
addKeyListener(this);
// Close operation
addWindowListener(new WindowAdapter() {
setVisible(true); public void windowClosing(WindowEvent e) {
dispose();
// Close the window when clicked }
addWindowListener(new });
WindowAdapter() { }
public void // Called when mouse is dragged
windowClosing(WindowEvent we) { public void mouseDragged(MouseEvent e) {
dispose(); x = e.getX();
} y = e.getY();
}); message = "Dragging at (" + x + ", " + y + ")";
} repaint();
}

// KeyListener methods // Called when mouse is moved


public void keyPressed(KeyEvent e) { public void mouseMoved(MouseEvent e) {
message = "Key Pressed"; x = e.getX();
repaint(); // Triggers paint method to y = e.getY();
display message message = "Moving at (" + x + ", " + y + ")";
repaint();
} }

public void keyReleased(KeyEvent e) {} // Paint the message


public void keyTyped(KeyEvent e) {} public void paint(Graphics g) {
g.drawString(message, x, y);
// Paint method to display message }
public void paint(Graphics g) { public static void main(String[] args) {
g.drawString(message, 100, 100); new MouseMotionDemo();
} }
}
Practical 18 public static void main(String[] args) {
Practical 20
new KeyEventDemo();
}
Practical 24
Practical 25

You might also like