Java Assignment Solutions - Assignment 1
1. Write a program to print "Hello JAVA".
public class HelloJava {
public static void main(String[] args) {
System.out.println("Hello JAVA");
2. Write a program to print the value given by the user using command-line arguments.
public class CommandLineValue {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("Value entered: " + args[0]);
} else {
System.out.println("No value entered!");
3. Write a program to print the sum of two numbers given by the user using command-line
arguments.
public class SumCommandLine {
public static void main(String[] args) {
if (args.length == 2) {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
System.out.println("Sum: " + (num1 + num2));
} else {
System.out.println("Please provide two numbers as arguments.");
4. Write a program to print the sum of two numbers given by the user using the Scanner
class.
import java.util.Scanner;
public class SumScanner {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
System.out.println("Sum: " + (num1 + num2));
scanner.close();
}
}
5. Write a program to illustrate the concept of default constructor.
class DefaultConstructor {
DefaultConstructor() {
System.out.println("Default constructor called!");
public static void main(String[] args) {
new DefaultConstructor();
6. Write a program to illustrate the concept of parameterized and object parameterized
constructors.
class ParameterizedConstructor {
int value;
ParameterizedConstructor(int value) {
this.value = value;
System.out.println("Parameterized constructor called with value: " + value);
ParameterizedConstructor(ParameterizedConstructor obj) {
this.value = obj.value;
System.out.println("Object parameterized constructor called. Copied value: "
+ value);
public static void main(String[] args) {
ParameterizedConstructor obj1 = new ParameterizedConstructor(10);
ParameterizedConstructor obj2 = new ParameterizedConstructor(obj1);
7. Write a program to illustrate the concept of this keyword.
class ThisKeyword {
int value;
ThisKeyword(int value) {
this.value = value;
void display() {
System.out.println("Value is: " + this.value);
public static void main(String[] args) {
ThisKeyword obj = new ThisKeyword(20);
obj.display();
8. Write a program to demonstrate static and instance data members and methods.
class StaticInstanceDemo {
static int staticValue = 10;
int instanceValue;
StaticInstanceDemo(int instanceValue) {
this.instanceValue = instanceValue;
static void staticMethod() {
System.out.println("Static method called. Static value: " + staticValue);
void instanceMethod() {
System.out.println("Instance method called. Instance value: " +
instanceValue);
public static void main(String[] args) {
StaticInstanceDemo obj = new StaticInstanceDemo(20);
staticMethod();
obj.instanceMethod();
9. Write a program to implement the concept of importing classes from a user-defined
package and creating packages.
// Save this file as MyClass.java inside the mypackage folder
package mypackage;
public class MyClass {
public void displayMessage() {
System.out.println("Message from user-defined package!");
// Main.java
import mypackage.MyClass;
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.displayMessage();
}
10. Write a program which illustrates the concept of inheritance.
class Parent {
void display() {
System.out.println("This is the parent class.");
class Child extends Parent {
void show() {
System.out.println("This is the child class.");
public class InheritanceExample {
public static void main(String[] args) {
Child obj = new Child();
obj.display();
obj.show();
11. Write a program to demonstrate the concept of method overloading and overriding.
class Overload {
void display(int num) {
System.out.println("Number: " + num);
void display(String text) {
System.out.println("Text: " + text);
class Override extends Overload {
@Override
void display(int num) {
System.out.println("Overridden number: " + num);
public class MethodDemo {
public static void main(String[] args) {
Override obj = new Override();
obj.display(10);
obj.display("Hello");
12. Write a program to demonstrate the use of a nested class.
class Outer {
private int value = 10;
class Inner {
void display() {
System.out.println("Value from Outer class: " + value);
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();
13. Write a program illustrating the concept of super keyword at variable and method level.
class Parent {
int value = 10;
void display() {
System.out.println("Parent class method.");
class Child extends Parent {
int value = 20;
void display() {
super.display();
System.out.println("Child class method. Parent value: " + super.value + ",
Child value: " + value);
public class SuperExample {
public static void main(String[] args) {
Child obj = new Child();
obj.display();
14. Write a program to calculate the sum of two integers and two floats using an abstract
method sum().
abstract class SumCalculator {
abstract void sum(int a, int b);
abstract void sum(float a, float b);
class Calculator extends SumCalculator {
@Override
void sum(int a, int b) {
System.out.println("Sum of integers: " + (a + b));
@Override
void sum(float a, float b) {
System.out.println("Sum of floats: " + (a + b));
public class AbstractExample {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.sum(10, 20);
calc.sum(10.5f, 20.5f);
15. Write a program to demonstrate the use of implementing and extending interfaces.
interface A {
void methodA();
interface B extends A {
void methodB();
}
class C implements B {
@Override
public void methodA() {
System.out.println("Method A from interface A.");
@Override
public void methodB() {
System.out.println("Method B from interface B.");
public class InterfaceDemo {
public static void main(String[] args) {
C obj = new C();
obj.methodA();
obj.methodB();
16. Write a program to demonstrate the use of the final keyword.
class FinalDemo {
final int VALUE = 10;
void display() {
System.out.println("Final value: " + VALUE);
public class Main {
public static void main(String[] args) {
FinalDemo obj = new FinalDemo();
obj.display();
}
Java Assignment Solutions - Assignment 2
1. Write a program to implement the concept of Exception Handling using predefined
Exception.
public class PredefinedExceptionHandling {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
2. Write a program to implement the concept of Exception Handling using throw keyword.
public class ThrowExample {
static void validate(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age not valid for voting.");
} else {
System.out.println("Welcome to vote!");
}
public static void main(String[] args) {
try {
validate(16);
} catch (IllegalArgumentException e) {
System.out.println("Exception caught: " + e.getMessage());
3. Write a program to write a string in a text file using IO package.
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("output.txt")) {
writer.write("Hello, this is written to a file!");
System.out.println("Successfully written to the file.");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
4. Write a program to draw different shapes in an applet using graphic class.
import java.applet.Applet;
import java.awt.Graphics;
public class DrawShapes extends Applet {
public void paint(Graphics g) {
g.drawLine(10, 10, 50, 10);
g.drawRect(60, 10, 50, 50);
g.drawOval(120, 10, 50, 50);
5. Write a program using Applet to display a message in the Applet.
import java.applet.Applet;
import java.awt.Graphics;
public class DisplayMessage extends Applet {
public void paint(Graphics g) {
g.drawString("Hello, Applet!", 20, 20);
6. Write a java program which will create a window and an empty area within that window
(extends Frame class).
import java.awt.Frame;
public class CreateWindow extends Frame {
CreateWindow() {
setTitle("My Window");
setSize(400, 300);
setVisible(true);
public static void main(String[] args) {
new CreateWindow();
7. Write a Java Program to demonstrate Keyboard event.
import java.awt.*;
import java.awt.event.*;
public class KeyboardEventDemo extends Frame implements KeyListener {
Label label;
KeyboardEventDemo() {
label = new Label();
label.setBounds(50, 50, 200, 20);
add(label);
addKeyListener(this);
setSize(400, 300);
setLayout(null);
setVisible(true);
public void keyPressed(KeyEvent e) {
label.setText("Key Pressed: " + e.getKeyChar());
public void keyReleased(KeyEvent e) {
label.setText("Key Released: " + e.getKeyChar());
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new KeyboardEventDemo();
8. Write a Java Program to demonstrate Mouse event.
import java.awt.*;
import java.awt.event.*;
public class MouseEventDemo extends Frame implements MouseListener {
Label label;
MouseEventDemo() {
label = new Label();
label.setBounds(50, 50, 200, 20);
add(label);
addMouseListener(this);
setSize(400, 300);
setLayout(null);
setVisible(true);
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked at X: " + e.getX() + ", Y: " + e.getY());
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public static void main(String[] args) {
new MouseEventDemo();
}
9. Write a program to enter two numbers in two different text fields, add a button, and display
their sum in a third non-editable text field.
import java.awt.*;
import java.awt.event.*;
public class SumCalculatorGUI extends Frame implements ActionListener {
TextField tf1, tf2, tf3;
Button addButton;
SumCalculatorGUI() {
tf1 = new TextField();
tf1.setBounds(50, 50, 150, 20);
tf2 = new TextField();
tf2.setBounds(50, 100, 150, 20);
tf3 = new TextField();
tf3.setBounds(50, 150, 150, 20);
tf3.setEditable(false);
addButton = new Button("Add");
addButton.setBounds(50, 200, 80, 30);
addButton.addActionListener(this);
add(tf1);
add(tf2);
add(tf3);
add(addButton);
setSize(400, 300);
setLayout(null);
setVisible(true);
public void actionPerformed(ActionEvent e) {
int num1 = Integer.parseInt(tf1.getText());
int num2 = Integer.parseInt(tf2.getText());
tf3.setText(String.valueOf(num1 + num2));
public static void main(String[] args) {
new SumCalculatorGUI();
}
Java Assignment Solutions - Assignment 3
1. Write a program to print text into Text Area using JTextArea.
import javax.swing.*;
public class JTextAreaExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTextArea Example");
JTextArea textArea = new JTextArea("Hello, JTextArea!");
textArea.setBounds(20, 20, 300, 200);
frame.add(textArea);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
2. Create this frame using JFrame.
import javax.swing.*;
public class JFrameExample {
public static void main(String[] args) {
JFrame frame = new JFrame("My JFrame Example");
JLabel label = new JLabel("This is a JFrame.");
label.setBounds(50, 50, 200, 30);
frame.add(label);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
3. Write a program to display selected item from JComboBox in a label on click of Show
button.
import javax.swing.*;
import java.awt.event.*;
public class JComboBoxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JComboBox Example");
String[] items = {"Item 1", "Item 2", "Item 3"};
JComboBox<String> comboBox = new JComboBox<>(items);
comboBox.setBounds(50, 50, 150, 30);
JLabel label = new JLabel("Selected: ");
label.setBounds(50, 150, 200, 30);
JButton button = new JButton("Show");
button.setBounds(50, 100, 80, 30);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("Selected: " +
comboBox.getItemAt(comboBox.getSelectedIndex()));
});
frame.add(comboBox);
frame.add(label);
frame.add(button);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
4. Create a swing application to display a menu bar where each menu item should display a
dialog box to show its working.
import javax.swing.*;
import java.awt.event.*;
public class MenuBarExample {
public static void main(String[] args) {
JFrame frame = new JFrame("MenuBar Example");
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem open = new JMenuItem("Open");
JMenuItem save = new JMenuItem("Save");
JMenuItem exit = new JMenuItem("Exit");
open.addActionListener(e -> JOptionPane.showMessageDialog(frame, "Open
clicked!"));
save.addActionListener(e -> JOptionPane.showMessageDialog(frame, "Save
clicked!"));
exit.addActionListener(e -> System.exit(0));
menu.add(open);
menu.add(save);
menu.add(exit);
menuBar.add(menu);
frame.setJMenuBar(menuBar);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
5. Create this frame message that will show according to the radio button clicked.
import javax.swing.*;
import java.awt.event.*;
public class RadioButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("RadioButton Example");
JRadioButton rb1 = new JRadioButton("Option 1");
rb1.setBounds(50, 50, 100, 30);
JRadioButton rb2 = new JRadioButton("Option 2");
rb2.setBounds(50, 100, 100, 30);
ButtonGroup group = new ButtonGroup();
group.add(rb1);
group.add(rb2);
JLabel label = new JLabel();
label.setBounds(50, 150, 200, 30);
rb1.addActionListener(e -> label.setText("Option 1 Selected"));
rb2.addActionListener(e -> label.setText("Option 2 Selected"));
frame.add(rb1);
frame.add(rb2);
frame.add(label);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
6. Create this food ordering system.
import javax.swing.*;
import java.awt.event.*;
public class FoodOrderingSystem {
public static void main(String[] args) {
JFrame frame = new JFrame("Food Ordering System");
JLabel label = new JLabel("Select your food:");
label.setBounds(50, 50, 200, 30);
JCheckBox pizza = new JCheckBox("Pizza - $10");
pizza.setBounds(50, 100, 200, 30);
JCheckBox burger = new JCheckBox("Burger - $5");
burger.setBounds(50, 150, 200, 30);
JCheckBox sandwich = new JCheckBox("Sandwich - $7");
sandwich.setBounds(50, 200, 200, 30);
JButton button = new JButton("Order");
button.setBounds(50, 250, 80, 30);
JLabel result = new JLabel("");
result.setBounds(50, 300, 300, 30);
button.addActionListener(e -> {
int total = 0;
StringBuilder order = new StringBuilder("You ordered: ");
if (pizza.isSelected()) {
order.append("Pizza ");
total += 10;
}
if (burger.isSelected()) {
order.append("Burger ");
total += 5;
if (sandwich.isSelected()) {
order.append("Sandwich ");
total += 7;
order.append("- Total: $").append(total);
result.setText(order.toString());
});
frame.add(label);
frame.add(pizza);
frame.add(burger);
frame.add(sandwich);
frame.add(button);
frame.add(result);
frame.setSize(400, 400);
frame.setLayout(null);
frame.setVisible(true);
7. Write a program to implement the concept of threading by extending Thread Class.
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread running: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
public class ThreadExample {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
8. Write a program to implement the concept of threading by implementing Runnable
Interface.
class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Runnable running: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
public class RunnableExample {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
9. Write a Java program that connects to a database using JDBC.
import java.sql.*;
public class DatabaseConnection {
public static void main(String[] args) {
try {
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username",
"password");
System.out.println("Connected to the database successfully!");
conn.close();
} catch (SQLException e) {
System.out.println("An error occurred: " + e.getMessage());
10. Write a program to enter the details of an employee in a window and add the record to the
database on button click.
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
public class EmployeeDetails {
public static void main(String[] args) {
JFrame frame = new JFrame("Employee Details");
JLabel nameLabel = new JLabel("Name:");
nameLabel.setBounds(50, 50, 100, 30);
JTextField nameField = new JTextField();
nameField.setBounds(150, 50, 150, 30);
JButton button = new JButton("Add");
button.setBounds(150, 100, 80, 30);
JLabel result = new JLabel("");
result.setBounds(50, 150, 300, 30);
button.addActionListener(e -> {
String name = nameField.getText();
try (Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username",
"password")) {
String query = "INSERT INTO employees (name) VALUES (?)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, name);
stmt.executeUpdate();
result.setText("Employee added successfully!");
} catch (SQLException ex) {
result.setText("Error: " + ex.getMessage());
});
frame.add(nameLabel);
frame.add(nameField);
frame.add(button);
frame.add(result);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);