0% found this document useful (0 votes)
55 views

Java programming solve question

The document contains a series of Java programming exercises covering various concepts such as multiplication of floating-point numbers, finding prime numbers, abstraction, method overloading, exception handling, and GUI components. Each question includes a code snippet demonstrating the implementation of the respective concept, along with explanations of the functionality. The exercises range from basic programming tasks to more advanced topics like user-defined exceptions and graphical user interface creation.

Uploaded by

khannusrat8220
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)
55 views

Java programming solve question

The document contains a series of Java programming exercises covering various concepts such as multiplication of floating-point numbers, finding prime numbers, abstraction, method overloading, exception handling, and GUI components. Each question includes a code snippet demonstrating the implementation of the respective concept, along with explanations of the functionality. The exercises range from basic programming tasks to more advanced topics like user-defined exceptions and graphical user interface creation.

Uploaded by

khannusrat8220
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/ 34

1|Page

Ques.1 Java program to multiply two floating-point numbers.


import java.util.Scanner;
public class MultiplyFloats {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first floating-point number: ");
float num1 = scanner.nextFloat();

System.out.print("Enter the second floating-point number: ");


float num2 = scanner.nextFloat();

float result = num1 * num2;

System.out.println("The multiplication of " + num1 + " and " + num2 + " is:
" + result);
}
}

OUTPUT:-
2|Page

Ques.2 Java program to find all the prime numbers from 1 to N.


import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of N: ");
int N = scanner.nextInt();
System.out.println("Prime numbers from 1 to " + N + " are:");
for (int num = 2; num <= N; num++) {
if (isPrime(num)) {
System.out.print(num + " "); } } }
public static boolean isPrime(int number) {
if (number <= 1) {
return false; // Numbers <= 1 are not prime
} for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false; // Number is divisible by i, not prime
} } return true; // Number is prime
} }
Input:-

Output:-
3|Page

Ques.3 . Java Program to implement Java Abstraction.


Program:-
abstract class Animal {
abstract void makeSound();
public void sleep() {
System.out.println("This animal is sleeping."); } }
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Woof Woof"); } }
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow Meow"); } }
public class AbstractionDemo {
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
dog.makeSound(); // Calls Dog's implementation
dog.sleep(); // Calls the concrete method from Animal
cat.makeSound(); // Calls Cat's implementation
cat.sleep(); // Calls the concrete method from Animal }}
Output:-
4|Page

Ques.4 . Java Program for Method overloading By using Different Types of


Arguments.
Program:-class Calculator {
public int add(int a, int b) {
return a + b; }
public int add(int a, int b, int c) {
return a + b + c; }
public double add(double a, double b) {
return a + b; }
public String add(String a, String b) {
return a + b; } }
public class MethodOverloadingDemo {
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println("Sum of two integers: " + calculator.add(10, 20));
System.out.println("Sum of three integers: " + calculator.add(10, 20, 30));
System.out.println("Sum of two doubles: " + calculator.add(5.5, 4.5));
System.out.println("Concatenation of two strings: " +
calculator.add("Hello, ", "World!")); }}
Output:-
5|Page

Ques.5 . Write a Program to create student details.


Program:-
import java.util.Scanner;
class Student {
private int studentId;
private String name;
private int age;
private String course;
public Student(int studentId, String name, int age, String course) {
this.studentId = studentId;
this.name = name;
this.age = age;
this.course = course;
}
public void displayDetails() {
System.out.println("Student ID: " + studentId);
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Course: " + course);
}
}
public class StudentDetails {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Student ID: ");
int studentId = scanner.nextInt();
6|Page

scanner.nextLine(); // Consume the newline


System.out.print("Enter Student Name: ");
String name = scanner.nextLine();
System.out.print("Enter Student Age: ");
int age = scanner.nextInt();
scanner.nextLine(); // Consume the newline
System.out.print("Enter Student Course: ");
String course = scanner.nextLine();
// Create a Student object
Student student = new Student(studentId, name, age, course);
// Display student details
System.out.println("\nStudent Details:");
student.displayDetails();
}
}
Input:-

Output:-
7|Page

Ques.6 . Write a program to create a Abstract Class.


Program:-abstract class Shape {
abstract void draw();
public void display() {
System.out.println("This is a shape."); } }
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a Circle."); } }
class Rectangle extends Shape {
@Override
void draw() {
System.out.println("Drawing a Rectangle."); } }
public class AbstractClassDemo {
public static void main(String[] args) {
Shape circle = new Circle();
Shape rectangle = new Rectangle();
circle.display();
circle.draw();
rectangle.display();
rectangle.draw(); }
}
Output:-
8|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

return 2 * (length * width + width * height + height * length);


}
}
public class ShapeDemo {
public static void main(String[] args) {
// Create a Rectangle object
Rectangle rectangle = new Rectangle(10, 5);
System.out.println("Rectangle:");
System.out.println("Area: " + rectangle.calculateArea());
System.out.println("Perimeter: " + rectangle.calculatePerimeter());
Box box = new Box(10, 5, 8);
System.out.println("\nBox:");
System.out.println("Volume: " + box.calculateVolume());
System.out.println("Surface Area: " + box.calculateSurfaceArea());
}
}
Output:-
10 | P a g e

Ques.8 . Write a Program to find the factorial of a given number using


recursion.
Program:-import java.util.Scanner;
public class FactorialRecursion {
public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case: factorial of 0 or 1 is 1
}
return n * factorial(n - 1); // Recursive call
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to find its factorial: ");
int number = scanner.nextInt();
if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
int result = factorial(number);
System.out.println("The factorial of " + number + " is: " + result);
}
}
}
Input:-

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;

public class MultipleCatchExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();

System.out.print("Enter the second number: ");


int num2 = scanner.nextInt();

int result = num1 / num2;


System.out.println("Result: " + result);

int[] array = {10, 20, 30};


System.out.print("Enter the array index to access (0-2): ");
int index = scanner.nextInt();
System.out.println("Array element at index " + index + ": " +
array[index]);

} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} catch (ArrayIndexOutOfBoundsException e) {
12 | P a g e

System.out.println("Error: Array index is out of bounds.");


} catch (Exception e) {
System.out.println("Error: An unexpected error occurred - " +
e.getMessage());
}
System.out.println("Program execution continues...");
}
}
Input:-

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.11 . Write a Program to Drawline Function ellipse, rectangle using the


graphics method.
Program:-
import java.awt.*;
import javax.swing.*;
public class DrawShapes extends JPanel {
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawLine(50, 50, 200, 50);
g.drawRect(50, 100, 150, 100);
g.drawOval(50, 100, 150, 100); }
public static void main(String[] args) {
JFrame frame = new JFrame("Drawing Shapes");
DrawShapes panel = new DrawShapes();
frame.add(panel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}}
Output:-
15 | 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 class SimpleFrameWindow extends Frame {


Label label;
TextField textField;
Button button;
TextArea textArea;

public SimpleFrameWindow() {
setTitle("Simple UI Frame Example");
setSize(400, 300);
setLayout(new FlowLayout());

label = new Label("Enter text:");


add(label);
textField = new TextField(20);
add(textField);
button = new Button("Submit");
add(button);
textArea = new TextArea(5, 30);
textArea.setEditable(false);
add(textArea);
18 | P a g e

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

Ques.14. Write a Program to implements Listbox. import java.awt.*;


Program:-
import java.awt.*;
import java.awt.event.*;

public class ListboxExample extends Frame {


List listBox;
Button button;
TextArea textArea;
public ListboxExample() {
setLayout(new FlowLayout()); // Set the layout to FlowLayout
setTitle("Listbox Example"); // Set the title of the frame
listBox = new List();
listBox.add("Item 1");
listBox.add("Item 2");
listBox.add("Item 3");
listBox.add("Item 4");
listBox.add("Item 5");
listBox.setMultipleMode(true); // Enable multiple selection
button = new Button("Show Selected Items");
textArea = new TextArea(5, 30);
textArea.setEditable(false);
add(listBox);
add(button);
add(textArea);
button.addActionListener(new ActionListener() {
20 | P a g e

public void actionPerformed(ActionEvent e) {


String[] selectedItems = listBox.getSelectedItems(); // Corrected
StringBuilder selectedText = new StringBuilder("Selected Items:\n");
for (String item : selectedItems) {
selectedText.append(item).append("\n"); }
textArea.setText(selectedText.toString()); } });
setSize(400, 300);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0); } }); }
public static void main(String[] args) {
new ListboxExample(); // Create the frame window with Listbox }}
Output:-
21 | P a g e

Ques.15 . Write a Program to implement Choice, Checkbox, Radio button with


event Handling.
import java.awt.*;
import java.awt.event.*;

public class ChoiceCheckboxRadioButtonExample extends Frame {

Choice choice;
Checkbox checkbox;
CheckboxGroup radioGroup;
Checkbox radioButton1, radioButton2;
TextArea textArea;

public ChoiceCheckboxRadioButtonExample() {
setLayout(new FlowLayout());
setTitle("Choice, Checkbox, Radio Button Example");

choice = new Choice();


choice.add("Option 1");
choice.add("Option 2");
choice.add("Option 3");
choice.add("Option 4");
add(choice);

checkbox = new Checkbox("Accept Terms and Conditions");


add(checkbox);
22 | P a g e

radioGroup = new CheckboxGroup();


radioButton1 = new Checkbox("Option A", radioGroup, false);
radioButton2 = new Checkbox("Option B", radioGroup, false);
add(radioButton1);
add(radioButton2);

textArea = new TextArea(5, 30);


textArea.setEditable(false);
add(textArea);

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

public void itemStateChanged(ItemEvent e) {


if (radioButton1.getState()) {
updateTextArea("Radio Button 1 is selected");
}
}
});
radioButton2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (radioButton2.getState()) {
updateTextArea("Radio Button 2 is selected");
}
}
});

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 static void main(String[] args) {


new ChoiceCheckboxRadioButtonExample(); // Create the frame window
}
Output:- TextArea Output: After interacting with the components, the
TextArea will display the following:
25 | P a g e

Ques.16 . Write a Program to implement Layout Manager.


import java.awt.*;
import java.awt.event.*;

public class LayoutManagerExample extends Frame {

public LayoutManagerExample() {
// Set the title of the frame
setTitle("Layout Manager Example");

setLayout(new FlowLayout()); // This can be changed to BorderLayout,


GridLayout, etc.

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


Button button2 = new Button("Button 2");
Button button3 = new Button("Button 3");
Button button4 = new Button("Button 4");
add(button1);
add(button2);
add(button3);
add(button4);
setSize(400, 200);
setVisible(true);

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.17 . Write a Program to implement Dialog Box.


Program:-
import java.awt.*;
import java.awt.event.*;
public class DialogBoxExample extends Frame {
public DialogBoxExample() {
setTitle("Dialog Box Example");
Button showMessageButton = new Button("Show Message Dialog");
Button showInputButton = new Button("Show Input Dialog");
setLayout(new FlowLayout());
add(showMessageButton);
add(showInputButton);
showMessageButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Dialog messageDialog = new Dialog(DialogBoxExample.this,
"Message", true);
messageDialog.setSize(300, 150);
messageDialog.setLayout(new FlowLayout());
messageDialog.add(new Label("This is a message dialog!"));
Button okButton = new Button("OK");
messageDialog.add(okButton);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
messageDialog.setVisible(false); // Hide the dialog } });
messageDialog.setVisible(true); // Show the dialog
}
}); showInputButton.addActionListener(new ActionListener() {
28 | P a g e

public void actionPerformed(ActionEvent e) {


// Create an input dialog to prompt the user for input
String userInput =
JOptionPane.showInputDialog(DialogBoxExample.this, "Enter something:");
if (userInput != null) {
System.out.println("User input: " + userInput);
} else {
System.out.println("No input provided");
}
}
});
setSize(400, 200);
setVisible(true);
// Window closing event
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0); } });
}
public static void main(String[] args) {
new DialogBoxExample(); // Create and display the window } }
Output:-
29 | 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

Ques.19 . Write a Program to implement digital Clock using applets.


Program:-
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DigitalClockSwing extends JFrame implements Runnable {
private JLabel clockLabel;
private Thread clockThread;
public DigitalClockSwing() {
setTitle("Digital Clock");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

clockLabel = new JLabel("00:00:00", JLabel.CENTER);


clockLabel.setFont(new Font("Arial", Font.BOLD, 36));
clockLabel.setForeground(Color.GREEN);
clockLabel.setBackground(Color.BLACK);
clockLabel.setOpaque(true);

add(clockLabel, BorderLayout.CENTER);

setVisible(true);
startClock();
}

public void startClock() {


if (clockThread == null) {
clockThread = new Thread(this);
clockThread.start();
}
}
public void run() {
try {
while (true) {
Date now = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
String currentTime = formatter.format(now);
33 | P a g e

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

Ques. 20 . Java Program to display images using Applet.


Program:-
import java.applet.Applet;
import java.awt.*;

/*
<applet code="ImageDisplayApplet" width=500 height=500>
</applet>
*/

public class ImageDisplayApplet extends Applet {


private Image img;

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

You might also like