[go: up one dir, main page]

0% found this document useful (0 votes)
20 views37 pages

Important Questions

Uploaded by

rakeshkolupuru9
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)
20 views37 pages

Important Questions

Uploaded by

rakeshkolupuru9
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/ 37

Handle exceptions with program :

1st way:

public class TryCatch

public static void main(String[] args)

try {

// Statements in the try block

System.out.println("Statement 1");

System.out.println("Statement 2");

System.out.println("Statement 3");

System.out.println("Statement 4");

// The 5th statement that causes a runtime exception

int result = 10 / 0;

// Statements after the exception-causing statement

System.out.println("Statement 6");

System.out.println("Statement 7");

System.out.println("Statement 8");

System.out.println("Statement 9");

System.out.println("Statement 10");

catch (ArithmeticException e)

// Handling the runtime exception

System.err.println("ArithmeticException caught: " + e.getMessage());

}
// Remaining statements after the catch block

System.out.println("Remaining statements after catch block");

Output:

Statement 1

Statement 2

Statement 3

Statement 4

ArithmeticException caught: / by zero

Remaining statements after catch block

2nd way:

import java.util.Scanner;

public class ThrowsHandling

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

try

System.out.print("Enter a number: ");

int userInput = readUserInput(scanner);

System.out.println("You entered: " + userInput);

catch (NumberFormatException e)
{

System.out.println("Invalid number format. Please enter a valid number.");

public static int readUserInput(Scanner scanner) throws NumberFormatException

String userInput = scanner.nextLine();

return Integer.parseInt(userInput);

Output:

>java ThrowsHandling

Enter a number: 4

You entered: 4

>java ThrowsHandling

Enter a number: f

Invalid number format. Please enter a valid number.

User Defined Exception :

// Custom exception class

class InvalidAgeException extends Exception

public InvalidAgeException(String message)

super(message);

}
// Class with a method that throws the custom exception

class AgeValidator

public static void validateAge(int age) throws InvalidAgeException

if (age < 0 || age > 120)

throw new InvalidAgeException("Invalid age. Age must be between 0 and 120.");

} else

System.out.println("Valid age: " + age);

// Main class to demonstrate the user-defined exception

public class UserException

public static void main(String[] args)

try

// Example usage: try to validate an age

int userAge = -5; // Replace with the user's input

AgeValidator.validateAge(userAge);

catch (InvalidAgeException e)

System.out.println("Exception caught: " + e.getMessage());


}

Output;

java UserException

Exception caught: Invalid age. Age must be between 0 and 120.

Get the thread priority & set priority


Get the thread name & set the name of the thread

class MyThread extends Thread

public MyThread(String name)

super(name);

public void run()

// Print thread information

printThreadInfo();

public void printThreadInfo()

System.out.println("Thread Name: " + getName());

System.out.println("Thread Priority: " + getPriority());


System.out.println("--------------------------");

public class Threading

public static void main(String[] args)

// Creating threads

MyThread thread1 = new MyThread("Thread 1");

MyThread thread2 = new MyThread("Thread 2");

// Getting and printing initial thread information

System.out.println("Initial Thread Information:");

thread1.printThreadInfo();

thread2.printThreadInfo();

// Setting thread priorities

thread1.setPriority(Thread.MAX_PRIORITY);

thread2.setPriority(Thread.MIN_PRIORITY);

// Setting thread names

thread1.setName("High Priority Thread");

thread2.setName("Low Priority Thread");

// Getting and printing updated thread information

System.out.println("Updated Thread Information:");

thread1.printThreadInfo();

thread2.printThreadInfo();
// Starting the threads

thread1.start();

thread2.start();

Output:

Initial Thread Information:

Thread Name: Thread 1

Thread Priority: 5

--------------------------

Thread Name: Thread 2

Thread Priority: 5

--------------------------

Updated Thread Information:

Thread Name: High Priority Thread

Thread Priority: 10

--------------------------

Thread Name: Low Priority Thread

Thread Priority: 1

--------------------------

Thread Name: High Priority Thread

Thread Name: Low Priority Thread

Thread Priority: 1

--------------------------

Thread Priority: 10

11)PRODUCER-CONSUMER PROBLEM SOLVING WITH INTER-THREAD COMMUNCATION


class SharedResource

private int buffer;

private boolean isFull = false;

public synchronized void produce(int item) throws InterruptedException

while (isFull)

wait(); // Wait if the buffer is full

buffer = item;

isFull = true;

System.out.println("Produced: " + item);

notify(); // Notify waiting consumers

public synchronized int consume() throws InterruptedException

while (!isFull)

wait(); // Wait if the buffer is empty

int consumedItem = buffer;

isFull = false;

System.out.println("Consumed: " + consumedItem);


notify(); // Notify waiting producers

return consumedItem;

class Producer extends Thread

private SharedResource sharedResource;

public void setSharedResource(SharedResource sharedResource)

this.sharedResource = sharedResource;

@Override

public void run()

for (int i = 1; i <= 5; i++)

try

sharedResource.produce(i);

Thread.sleep(1000); // Simulate production time

catch (InterruptedException e)

Thread.currentThread().interrupt();

}
class Consumer extends Thread

private SharedResource sharedResource;

public void setSharedResource(SharedResource sharedResource)

this.sharedResource = sharedResource;

@Override

public void run()

for (int i = 0; i < 5; i++)

try

int consumedItem = sharedResource.consume();

Thread.sleep(1500); // Simulate consumption time

catch (InterruptedException e)

Thread.currentThread().interrupt();

public class PCWithITC

public static void main(String[] args)


{

SharedResource sharedResource = new SharedResource();

Producer producerThread = new Producer();

Consumer consumerThread = new Consumer();

producerThread.setSharedResource(sharedResource);

consumerThread.setSharedResource(sharedResource);

producerThread.start();

consumerThread.start();

Output:

Produced: 1

Consumed: 1

Produced: 2

Consumed: 2

Produced: 3

Consumed: 3

Produced: 4

Consumed: 4

Produced: 5

Consumed: 5
Inter Thread Communication through Wait () and Notify () methods.

class Rupdate extends Thread


{

int total = 0;

public void run()


{

synchronized(this)
{
for (int i = 1; i < 100; i++)
{
total=total+i;
this.notify();
}
}
}
}
class Interthread
{
public static void main(String[] args) throws InterruptedException
{
Rupdate r=new Rupdate();
r.start();
synchronized(r)
{
r.wait();
System.out.println(r.total);

}
}
}

Output:

>java Interthread
4950

Alive() , sleep() , join() methods :

public class Alive1 extends Thread


{
public void run()
{
for (int i = 0; i < 5; i++)
{
System.out.println(" child Working...");

}
}

public static void main(String[] args)throws InterruptedException


{
Alive1 t = new Alive1();
// Check if the thread is alive
System.out.println("Is the thread alive? " + t.isAlive());

// Start the thread


t.start();

for (int i = 0; i < 5; i++)


{
System.out.println("main Working...");

}
// Check again after the thread has finished
System.out.println("Is the thread alive? " + t.isAlive());
}
}

Output:
>java Alive1
Is the thread alive? false
main Working...
main Working...
child Working...
child Working...
main Working...
main Working...
main Working...
child Working...
child Working...
Is the thread alive? true
child Working...

class MyThread extends Thread


{
static Thread r;
public void run()

{
for(int i=0;i<5;i++)
{
System.out.println("child thread");
try
{

r.join();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class JoinThread
{
public static void main(String[] args)throws InterruptedException
{
MyThread.r=Thread.currentThread();

MyThread t = new MyThread();


t.start();
for(int i=0;i<5;i++)
{
System.out.println("main thread");
try
{

Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}

Output:

>java JoinThread
main thread
child thread
main thread
main thread
main thread
main thread
child thread
child thread
child thread
child thread

public class SleepThread


{

public static void main(String[] args)


{
System.out.println("Program started.");

for (int i = 1; i <= 5; i++)


{
System.out.println("Countdown: " + i);

try
{

Thread.sleep(1000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("Program completed.");
}
}

Output:

>java SleepThread
Program started.
Countdown: 1
Countdown: 2
Countdown: 3
Countdown: 4
Countdown: 5
Program completed.

Creating three threads using the class Thread and then run

class MyThread extends Thread {

public MyThread(String name) {


super(name);
}

public void run() {


for (int i = 1; i <= 5; i++) {
System.out.println(getName() + ": Count " + i);
try {
Thread.sleep(500); // Simulate some work by sleeping
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

public class ConcurrentThreadExample {


public static void main(String[] args) {
// Creating three threads
MyThread thread1 = new MyThread("Thread A");
MyThread thread2 = new MyThread("Thread B");
MyThread thread3 = new MyThread("Thread C");

// Running threads concurrently


thread1.start();
thread2.start();
thread3.start();
}
}

Output:
>java ThreeThread
Thread A: Count 1
Thread B: Count 1
Thread C: Count 1
Thread A: Count 2
Thread B: Count 2
Thread C: Count 2
Thread A: Count 3
Thread B: Count 3
Thread C: Count 3
Thread A: Count 4
Thread B: Count 4
Thread C: Count 4
Thread A: Count 5
Thread B: Count 5
Thread C: Count 5

three threads using the Runnable interface and then run

class MyRunnable implements Runnable {

private String name;

public MyRunnable(String name) {


this.name = name;
}

public void run() {


for (int i = 1; i <= 5; i++) {
System.out.println(name + ": Count " + i);
try {
Thread.sleep(500); // Simulate some work by sleeping
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

public class ConcurrentRunnableExample {


public static void main(String[] args) {
// Creating three Runnable instances
MyRunnable myRunnable1 = new MyRunnable("Thread X");
MyRunnable myRunnable2 = new MyRunnable("Thread Y");
MyRunnable myRunnable3 = new MyRunnable("Thread Z");

// Creating three Thread instances and associating them with Runnable instances
Thread thread1 = new Thread(myRunnable1);
Thread thread2 = new Thread(myRunnable2);
Thread thread3 = new Thread(myRunnable3);

// Running threads concurrently


thread1.start();
thread2.start();
thread3.start();
}
}

Output:

>java ThreeRunnable
Thread X: Count 1
Thread Z: Count 1
Thread Y: Count 1
Thread X: Count 2
Thread Z: Count 2
Thread Y: Count 2
Thread Z: Count 3
Thread X: Count 3
Thread Y: Count 3
Thread X: Count 4
Thread Y: Count 4
Thread Z: Count 4
Thread X: Count 5
Thread Y: Count 5
Thread Z: Count 5
Registration Form With Swing Components :

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class RegistrationForm extends JFrame {

private JTextField firstNameField, lastNameField, emailField, addressField;

private JPasswordField passwordField;

private JRadioButton maleRadioButton, femaleRadioButton;

private ButtonGroup genderButtonGroup;

private JTextArea displayArea;

public RegistrationForm() {

initializeUI();

private void initializeUI() {

setTitle("Registration Form");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(500, 300);

// Create panels to divide the frame

JPanel inputPanel = new JPanel(new GridLayout(7, 2));

JPanel displayPanel = new JPanel(new BorderLayout());

// Create input fields and labels

JLabel firstNameLabel = new JLabel("First Name:");

JLabel lastNameLabel = new JLabel("Last Name:");


JLabel emailLabel = new JLabel("Email:");

JLabel passwordLabel = new JLabel("Password:");

JLabel genderLabel = new JLabel("Gender:");

JLabel addressLabel = new JLabel("Address:");

firstNameField = new JTextField();

lastNameField = new JTextField();

emailField = new JTextField();

passwordField = new JPasswordField();

addressField = new JTextField();

maleRadioButton = new JRadioButton("Male");

femaleRadioButton = new JRadioButton("Female");

genderButtonGroup = new ButtonGroup();

genderButtonGroup.add(maleRadioButton);

genderButtonGroup.add(femaleRadioButton);

// Add input fields and labels to the input panel

inputPanel.add(firstNameLabel);

inputPanel.add(firstNameField);

inputPanel.add(lastNameLabel);

inputPanel.add(lastNameField);

inputPanel.add(emailLabel);

inputPanel.add(emailField);

inputPanel.add(passwordLabel);

inputPanel.add(passwordField);

inputPanel.add(genderLabel);

inputPanel.add(maleRadioButton);

inputPanel.add(new JLabel()); // Empty label for spacing

inputPanel.add(femaleRadioButton);

inputPanel.add(addressLabel);
inputPanel.add(addressField);

// Create display area and add it to the display panel

displayArea = new JTextArea();

displayArea.setEditable(false);

JScrollPane scrollPane = new JScrollPane(displayArea);

displayPanel.add(scrollPane, BorderLayout.CENTER);

// Create a button to submit the form

JButton submitButton = new JButton("Submit");

submitButton.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

submitForm();

});

// Add components to the frame

getContentPane().setLayout(new GridLayout(1, 2));

getContentPane().add(inputPanel);

getContentPane().add(displayPanel);

getContentPane().add(submitButton);

setLocationRelativeTo(null); // Center the frame

private void submitForm() {

// Get entered data

String firstName = firstNameField.getText();

String lastName = lastNameField.getText();

String email = emailField.getText();


char[] passwordChars = passwordField.getPassword();

String password = new String(passwordChars);

String gender = maleRadioButton.isSelected() ? "Male" : "Female";

String address = addressField.getText();

// Display entered data in the text area

String displayText = "First Name: " + firstName + "\n" +

"Last Name: " + lastName + "\n" +

"Email: " + email + "\n" +

"Password: " + password + "\n" +

"Gender: " + gender + "\n" +

"Address: " + address;

displayArea.setText(displayText);

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

new RegistrationForm().setVisible(true);

});

Output:
Applet total syllabus ( all topics)
Registration Form With AWT Components :

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class RegistrationFormAWT extends Frame {

private TextField firstNameField, lastNameField, emailField, addressField;

private TextField passwordField;

private CheckboxGroup genderCheckboxGroup;

private Checkbox maleCheckbox, femaleCheckbox;

private TextArea displayArea;

public RegistrationFormAWT() {

initializeUI();

private void initializeUI() {

setTitle("Registration Form");

setSize(500, 300);

// Create panels to divide the frame

Panel inputPanel = new Panel();

inputPanel.setLayout(new GridLayout(7, 2, 5, 5));

Panel displayPanel = new Panel(new BorderLayout());

// Create input fields and labels

Label firstNameLabel = new Label("First Name:");

Label lastNameLabel = new Label("Last Name:");


Label emailLabel = new Label("Email:");

Label passwordLabel = new Label("Password:");

Label genderLabel = new Label("Gender:");

Label addressLabel = new Label("Address:");

firstNameField = new TextField();

lastNameField = new TextField();

emailField = new TextField();

passwordField = new TextField();

addressField = new TextField();

genderCheckboxGroup = new CheckboxGroup();

maleCheckbox = new Checkbox("Male", genderCheckboxGroup, false);

femaleCheckbox = new Checkbox("Female", genderCheckboxGroup, false);

// Add input fields and labels to the input panel

addComponents(inputPanel, firstNameLabel, firstNameField);

addComponents(inputPanel, lastNameLabel, lastNameField);

addComponents(inputPanel, emailLabel, emailField);

addComponents(inputPanel, passwordLabel, passwordField);

addComponents(inputPanel, genderLabel, createGenderPanel());

addComponents(inputPanel, addressLabel, addressField);

// Create a button to submit the form

Button submitButton = new Button("Submit");

submitButton.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

submitForm();

});
// Add components to the display panel

displayArea = new TextArea();

displayArea.setEditable(false);

displayPanel.add(displayArea, BorderLayout.CENTER);

// Create a panel for the submit button

Panel buttonPanel = new Panel(new FlowLayout(FlowLayout.RIGHT));

buttonPanel.add(submitButton);

// Add components to the frame

setLayout(new GridLayout(1, 2));

add(inputPanel);

add(displayPanel);

add(buttonPanel);

setLocationRelativeTo(null); // Center the frame

// Handling window close event

addWindowListener(new java.awt.event.WindowAdapter() {

public void windowClosing(java.awt.event.WindowEvent windowEvent) {

System.exit(0);

});

private Panel createGenderPanel() {

Panel genderPanel = new Panel();

genderPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

genderPanel.add(maleCheckbox);

genderPanel.add(femaleCheckbox);
return genderPanel;

private void addComponents(Panel panel, Component label, Component field) {

panel.add(label);

panel.add(field);

private void submitForm() {

// Get entered data

String firstName = firstNameField.getText();

String lastName = lastNameField.getText();

String email = emailField.getText();

String password = passwordField.getText();

String gender = maleCheckbox.getState() ? "Male" : "Female";

String address = addressField.getText();

// Display entered data in the text area

String displayText = "First Name: " + firstName + "\n" +

"Last Name: " + lastName + "\n" +

"Email: " + email + "\n" +

"Password: " + password + "\n" +

"Gender: " + gender + "\n" +

"Address: " + address;

displayArea.setText(displayText);

public static void main(String[] args) {

RegistrationFormAWT registrationForm = new RegistrationFormAWT();

registrationForm.setVisible(true);
}

Output:
Differ Btw AWT and Swing

Delegation event model

Event Classes

EventListener Interfaces

EventListenerInterface Methods

FRAME WITH AWT COMPONENTS:

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class FrameExample extends Frame {

private TextField textField;

private TextArea textArea;

private Checkbox checkbox;

private Choice choice;

private List list;

public FrameExample()

// Set layout manager for the frame

setLayout(new FlowLayout());

// Create components
createComponents();

// Set frame properties

setTitle("Frame Example");

setSize(1500, 1200);

setVisible(true);

// Handle window close event

addWindowListener(new java.awt.event.WindowAdapter() {

public void windowClosing(java.awt.event.WindowEvent windowEvent)

System.exit(0);

});

private void createComponents()

// Components for the frame

Button button1 = new Button("Button 1");

textField = new TextField(20);

textArea = new TextArea(10, 30);

textArea.setEditable(false);

textArea.setFont(new Font("Courier New", Font.PLAIN, 12));

checkbox = new Checkbox("Check Me");

choice = new Choice();

// Add items to choice and list

choice.add("rose");
choice.add("lilly");

choice.add("jasmine");

// Add components to the frame

add(button1);

add(textField);

add(textArea);

add(checkbox);

add(choice);

// Add ActionListener for button1

button1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

String text = textField.getText();

textArea.append("Button 1 Clicked: " + text + "\n");

});

// Add ItemListener for checkbox

checkbox.addItemListener(e -> {

boolean isChecked = checkbox.getState();

textArea.append("Checkbox Checked: " + isChecked + "\n");

});

// Add ItemListener for choice

choice.addItemListener(e -> {

String selectedOption = choice.getSelectedItem();

textArea.append("Choice Selected: " + selectedOption + "\n");


});

public static void main(String[] args) {

new FrameExample();

Output:

MOUSE EVENT: KEYEVENT: WINDOWEVENT:

ACTION EVENT AND INTERFACE: Button , Menu

Layout Mechanisms ALL With Programs

Adapter classes by Example :

Window Adapter , keyadapter , mouse adapter …..

JScrollPane , JSplitPane, JList Programs

You might also like