Java programming solve question
Java programming solve question
System.out.println("The multiplication of " + num1 + " and " + num2 + " is:
" + result);
}
}
OUTPUT:-
2|Page
Output:-
3|Page
Output:-
7|Page
Ques.7 Write a program to create a simple class to find out the area and
parimeter of rectangle and box using super and this keyword.
class Rectangle {
protected double length;
protected double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double calculateArea() {
return length * width;
}
public double calculatePerimeter() {
return 2 * (length + width);
}
}
class Box extends Rectangle {
private double height;
public Box(double length, double width, double height) {
super(length, width); // Call the constructor of Rectangle
this.height = height; // Assign height using this
}
public double calculateVolume() {
return length * width * height;
}
public double calculateSurfaceArea() {
9|Page
Output:-
11 | P a g e
Ques.9 . Write a program to handle the exception using try and multiple catch
block.
Program:-
import java.util.Scanner;
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} catch (ArrayIndexOutOfBoundsException e) {
12 | P a g e
Output:-
Input:-
Ouput:-
13 | P a g e
Ques.10 . Write a Program to handle the user defined Exception using throw
and throws keyword.
Program:-
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message); }}
public class UserDefinedExceptionExample {
public static void checkAge(int age) throws InvalidAgeException {
if (age < 18) { throw new InvalidAgeException("Age must be 18 or older.");
} else { System.out.println("Age is valid: " + age); } }
public static void main(String[] args) {
try { int age = 15; // You can change this value to test different ages
checkAge(age); // Calling the method that may throw the exception
} catch (InvalidAgeException e) {
System.out.println("Error: " + e.getMessage()); }
System.out.println("Program execution continues..."); } }
Input:-
Output:-
Input:-
Output:-
14 | P a g e
Ques .12 . Write a code in java to generate single calculator using classes and
accepting the two integers and operator will all methods to inputs, displays,
add, subtract, product and division.
Program:-
import java.util.Scanner;
class Calculator {
private int num1, num2;
private char operator;
private double result;
public void inputValues() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first number: ");
num1 = sc.nextInt();
System.out.print("Enter the second number: ");
num2 = sc.nextInt();
System.out.print("Enter the operator (+, -, *, /): ");
operator = sc.next().charAt(0); }
public void calculate() {
switch (operator) { case '+':
result = add();
break;
case '-':
result = subtract();
break;
case '*':
result = multiply();
break;
16 | P a g e
case '/':
if (num2 != 0) {
result = divide();
} else { System.out.println("Error: Division by zero is not
allowed.");
Return; }
break;
default:
System.out.println("Invalid operator!");
return; } }
public int add() {
return num1 + num2; }
public int subtract() {
return num1 - num2; }
public int multiply() {
return num1 * num2;}
public double divide() { return (double) num1 / num2; }
public void displayResult() { System.out.println("Result: " + result); } }
public class SimpleCalculator { public static void main(String[] args) {
Calculator calc = new Calculator();
calc.inputValues(); // Accept inputs for numbers and operator
calc.calculate(); // Perform the calculation
calc.displayResult(); // Display the result }}
Output:-
17 | P a g e
Ques 13. WAP to create UI Components on Frame Window Using Frame Class.
Program:-
import java.awt.*;
import java.awt.event.*;
public SimpleFrameWindow() {
setTitle("Simple UI Frame Example");
setSize(400, 300);
setLayout(new FlowLayout());
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String inputText = textField.getText();
textArea.append("Entered Text: " + inputText + "\n");
textField.setText(""); // Clear the TextField after input
}
});
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new SimpleFrameWindow(); // Create the frame window
}
}
Output:-
19 | P a g e
Choice choice;
Checkbox checkbox;
CheckboxGroup radioGroup;
Checkbox radioButton1, radioButton2;
TextArea textArea;
public ChoiceCheckboxRadioButtonExample() {
setLayout(new FlowLayout());
setTitle("Choice, Checkbox, Radio Button Example");
choice.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
String selectedChoice = "Selected Choice: " +
choice.getSelectedItem();
updateTextArea(selectedChoice);
}
});
checkbox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
String checkboxStatus = checkbox.getState() ? "Checkbox is checked"
: "Checkbox is unchecked";
updateTextArea(checkboxStatus);
}
});
radioButton1.addItemListener(new ItemListener() {
23 | P a g e
setSize(400, 300);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
private void updateTextArea(String text) {
textArea.setText(text);
}
24 | P a g e
public LayoutManagerExample() {
// Set the title of the frame
setTitle("Layout Manager Example");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0); }
26 | P a g e
}); }
public void setBorderLayout() {
setLayout(new BorderLayout());
add(new Button("North Button"), BorderLayout.NORTH);
add(new Button("South Button"), BorderLayout.SOUTH);
add(new Button("East Button"), BorderLayout.EAST);
add(new Button("West Button"), BorderLayout.WEST);
add(new Button("Center Button"), BorderLayout.CENTER); }
public void setGridLayout() {
setLayout(new GridLayout(2, 2)); // 2 rows, 2 columns
add(new Button("Button 1"));
add(new Button("Button 2"));
add(new Button("Button 3"));
add(new Button("Button 4")); }
public static void main(String[] args) {
LayoutManagerExample layoutExample = new LayoutManagerExample();
method
}
}
Output:-
27 | P a g e
Ques. 18. Write a Program to create Frame that display the student
information
Program:-
import java.awt.*;
import java.awt.event.*;
public class StudentInfoFrame extends Frame {
Label nameLabel, rollLabel, gradeLabel, infoLabel;
TextField nameField, rollField, gradeField;
Button submitButton, clearButton;
TextArea outputArea;
public StudentInfoFrame() {
setLayout(new FlowLayout());
setTitle("Student Information");
setSize(400, 400);
nameLabel = new Label("Name:");
nameField = new TextField(20);
rollLabel = new Label("Roll Number:");
rollField = new TextField(20);
gradeLabel = new Label("Grade:");
gradeField = new TextField(20);
submitButton = new Button("Submit");
clearButton = new Button("Clear");
outputArea = new TextArea(5, 30);
outputArea.setEditable(false);
infoLabel = new Label("Student Information:");
add(nameLabel);
30 | P a g e
add(nameField);
add(rollLabel);
add(rollField);
add(gradeLabel);
add(gradeField);
add(submitButton);
add(clearButton);
add(infoLabel);
add(outputArea);
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String roll = rollField.getText();
String grade = gradeField.getText();
if (name.isEmpty() || roll.isEmpty() || grade.isEmpty()) {
outputArea.setText("Please fill in all fields.");
} else { outputArea.setText("Student Details:\n");
outputArea.append("Name: " + name + "\n");
outputArea.append("Roll Number: " + roll + "\n");
outputArea.append("Grade: " + grade + "\n"); } } });
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
nameField.setText("");
rollField.setText("");
gradeField.setText("");
outputArea.setText(""); } });
31 | P a g e
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose(); }
}); setVisible(true); } public static void main(String[] args) {
new StudentInfoFrame(); } }
32 | P a g e
add(clockLabel, BorderLayout.CENTER);
setVisible(true);
startClock();
}
clockLabel.setText(currentTime);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new DigitalClockSwing());
}
}
34 | P a g e
/*
<applet code="ImageDisplayApplet" width=500 height=500>
</applet>
*/
@Override
public void init() {
// Load the image from the current directory or a URL
img = getImage(getDocumentBase(), "image.jpg"); // Replace "image.jpg"
with your image file name
}
@Override
public void paint(Graphics g) {
// Check if the image is loaded
if (img != null) {
// Draw the image at position (50, 50) with its original size
g.drawImage(img, 50, 50, this);
} else {
g.drawString("Image not found", 50, 50);
}
}
}