Q1. Write a Java Program of Even odd number.

Problem Explanation

This program takes a number as input and determines whether it is even or odd using the modulo operator. A number is even if it is divisible by 2, odd otherwise.

Step-By-Step Instructions

  • Import Scanner class for user input
  • Create a Scanner object to read integer input
  • Check if number % 2 == 0
  • Display "Even" if condition is true
  • Display "Odd" if condition is false

Code

Java
import java.util.Scanner;

public class EvenOdd {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number:");
        int num = sc.nextInt();
        
        if (num % 2 == 0) {
            System.out.println(num + " is Even");
        } else {
            System.out.println(num + " is Odd");
        }
    }
}

Output

Expected Output:
Input: 10 Output: 10 is Even Input: 7 Output: 7 is Odd

Key Concept

The modulo operator (%) returns the remainder of division. For any number, if remainder when divided by 2 is 0, it's even, otherwise odd. This is a fundamental concept in number classification.

Q2. Write a Java Program Of given Number is Palindrome or Not.

Problem Explanation

A palindrome is a number that reads the same forwards and backwards. This program reverses a number and compares it with the original.

Step-By-Step Instructions

  • Store the original number
  • Reverse the number using modulo and division
  • Compare reversed with original
  • Display result

Code

Java
import java.util.Scanner;

public class Palindrome {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number:");
        int num = sc.nextInt();
        int original = num;
        int reversed = 0;
        
        while (num > 0) {
            int digit = num % 10;
            reversed = reversed * 10 + digit;
            num = num / 10;
        }
        
        if (original == reversed) {
            System.out.println(original + " is a Palindrome");
        } else {
            System.out.println(original + " is not a Palindrome");
        }
    }
}

Output

Expected Output:
Input: 121 Output: 121 is a Palindrome Input: 123 Output: 123 is not a Palindrome

Key Concept

Palindrome checking involves number reversal. We extract digits using modulo, reconstruct the reversed number, and compare with the original. This technique is useful in string/number validation.

Q3. Write a Java Program to find LCM of two Numbers.

Problem Explanation

LCM (Least Common Multiple) is the smallest number that is a multiple of both numbers. We can find it using the formula: LCM = (a * b) / GCD(a, b)

Step-By-Step Instructions

  • Take two numbers as input
  • Calculate GCD (Greatest Common Divisor)
  • Use formula: LCM = (a * b) / GCD
  • Display the LCM

Code

Java
import java.util.Scanner;

public class LCM {
    static int findGCD(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
    
    static int findLCM(int a, int b) {
        return (a * b) / findGCD(a, b);
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter first number:");
        int num1 = sc.nextInt();
        System.out.println("Enter second number:");
        int num2 = sc.nextInt();
        
        System.out.println("LCM of " + num1 + " and " + num2 + " is " + findLCM(num1, num2));
    }
}

Output

Expected Output:
Input: 12, 18 Output: LCM of 12 and 18 is 36 Input: 10, 15 Output: LCM of 10 and 15 is 30

Key Concept

LCM is found using GCD through Euclidean algorithm. This is useful in solving fraction problems, scheduling tasks, and finding common time intervals. The formula LCM(a,b) = (a*b)/GCD(a,b) is fundamental.

Q4. Calculate The Income Tax Of Employee.

Problem Explanation

This program calculates income tax based on salary slabs. Different tax rates apply to different income ranges. Example: 0-100000: 0%, 100001-300000: 10%, 300001+: 20%

Step-By-Step Instructions

  • Input employee salary
  • Define tax slabs and rates
  • Calculate tax based on salary bracket
  • Display tax amount and net salary

Code

Java
import java.util.Scanner;

public class IncomeTax {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter salary:");
        double salary = sc.nextDouble();
        
        double tax = 0;
        if (salary <= 100000) {
            tax = 0;
        } else if (salary <= 300000) {
            tax = (salary - 100000) * 0.10;
        } else {
            tax = (200000 * 0.10) + ((salary - 300000) * 0.20);
        }
        
        double netSalary = salary - tax;
        System.out.println("Gross Salary: " + salary);
        System.out.println("Tax: " + tax);
        System.out.println("Net Salary: " + netSalary);
    }
}

Output

Expected Output:
Input: 250000 Gross Salary: 250000.0 Tax: 15000.0 Net Salary: 235000.0 Input: 400000 Gross Salary: 400000.0 Tax: 40000.0 Net Salary: 360000.0

Key Concept

Tax calculations use conditional logic to apply different rates to different salary brackets. Understanding progressive taxation helps in real-world payroll calculations. This demonstrates practical use of if-else chains.

Q5. Write a Java Program To Display Following Pattern.

Problem Explanation

Pattern printing is a fundamental exercise in loop control. This program displays pyramid patterns using nested loops. The outer loop controls rows, inner loop controls columns.

Step-By-Step Instructions

  • Use nested for loops for pattern creation
  • Outer loop for number of rows
  • Inner loop for printing characters/spaces
  • Control spacing for alignment

Code

Java
public class Pattern {
    public static void main(String[] args) {
        int rows = 5;
        
        // Pyramid pattern
        for (int i = 1; i <= rows; i++) {
            // Print spaces
            for (int j = rows - i; j > 0; j--) {
                System.out.print(" ");
            }
            // Print stars
            for (int k = 1; k <= 2*i-1; k++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Output

Expected Output:
* *** ***** ******* *********

Key Concept

Pattern printing develops nested loop understanding. Stars increase (2*i-1) with each row while spaces decrease (rows-i). This teaches loop nesting, counter management, and output formatting.

Q6. Write a Program to input 3 numbers on Command line Argument and Find Maximum of them.

Problem Explanation

Command-line arguments allow passing data to programs without interactive input. This program compares three numbers and finds the maximum using Math.max() or conditional statements.

Step-By-Step Instructions

  • Accept 3 numbers via command-line arguments
  • Convert String arguments to integers
  • Compare all three numbers
  • Display the maximum value

Code

Java
public class MaxNumber {
    public static void main(String[] args) {
        if (args.length < 3) {
            System.out.println("Enter 3 numbers");
            return;
        }
        
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int c = Integer.parseInt(args[2]);
        
        int max = Math.max(a, Math.max(b, c));
        System.out.println("Maximum: " + max);
    }
}

Output

Expected Output:
Command: java MaxNumber 10 20 15 Output: Maximum: 20 Command: java MaxNumber 50 30 40 Output: Maximum: 50

Key Concept

Command-line arguments are passed as String array to main method. Integer.parseInt() converts Strings to integers. This demonstrates argument validation, type conversion, and using built-in Math methods.

Q7. Create a person inherits two classes provide Constructer and calculate salary and display functions.

Problem Explanation

Java allows a class to extend only one class (single inheritance). This program demonstrates creating a Person class with constructors and methods for calculating and displaying salary information.

Step-By-Step Instructions

  • Create base class with common properties
  • Create derived class inheriting from base
  • Define constructors in both classes
  • Implement salary calculation method
  • Implement display method

Code

Java
class Employee {
    String name;
    int id;
    
    Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }
}

class Manager extends Employee {
    double salary;
    double bonus;
    
    Manager(String name, int id, double salary, double bonus) {
        super(name, id);
        this.salary = salary;
        this.bonus = bonus;
    }
    
    double calculateTotalSalary() {
        return salary + bonus;
    }
    
    void display() {
        System.out.println("Name: " + name);
        System.out.println("ID: " + id);
        System.out.println("Salary: " + salary);
        System.out.println("Bonus: " + bonus);
        System.out.println("Total Salary: " + calculateTotalSalary());
    }
}

public class InheritanceDemo {
    public static void main(String[] args) {
        Manager m = new Manager("John", 101, 50000, 5000);
        m.display();
    }
}

Output

Expected Output:
Name: John ID: 101 Salary: 50000.0 Bonus: 5000.0 Total Salary: 55000.0

Key Concept

Inheritance allows code reuse through extends keyword. The super() keyword calls parent constructor. This demonstrates constructor chaining, method overriding, and single inheritance in Java.

Q8. Write a Program to count objects of a class running in memory.

Problem Explanation

This program uses a static variable to track the number of instances created from a class. Each time a constructor is called, the counter increments.

Step-By-Step Instructions

  • Create a static counter variable
  • Increment counter in constructor
  • Create a static method to get count
  • Create multiple objects and track count

Code

Java
class Student {
    static int count = 0;
    String name;
    
    Student(String name) {
        this.name = name;
        count++;
    }
    
    static void displayCount() {
        System.out.println("Total Students: " + count);
    }
}

public class ObjectCounter {
    public static void main(String[] args) {
        Student s1 = new Student("John");
        Student.displayCount();
        
        Student s2 = new Student("Jane");
        Student.displayCount();
        
        Student s3 = new Student("Mike");
        Student.displayCount();
    }
}

Output

Expected Output:
Total Students: 1 Total Students: 2 Total Students: 3

Key Concept

Static variables are shared among all instances of a class. Static methods can access static variables without creating objects. This technique is useful for tracking metrics like object counts.

Q9. Create Abstract Class employee, having its properties and abstract functions.

Problem Explanation

Abstract classes define the contract for derived classes without complete implementation. This program creates an abstract Employee class with abstract methods that derived classes must implement.

Step-By-Step Instructions

  • Create abstract class Employee
  • Add properties (name, id, salary)
  • Define abstract methods (calculateTax, display)
  • Create concrete subclasses
  • Implement abstract methods in subclasses

Code

Java
abstract class Employee {
    String name;
    int id;
    double salary;
    
    Employee(String name, int id, double salary) {
        this.name = name;
        this.id = id;
        this.salary = salary;
    }
    
    abstract double calculateTax();
    abstract void display();
}

class Manager extends Employee {
    Manager(String name, int id, double salary) {
        super(name, id, salary);
    }
    
    double calculateTax() {
        return salary * 0.15;
    }
    
    void display() {
        System.out.println("Manager: " + name);
        System.out.println("Salary: " + salary);
        System.out.println("Tax: " + calculateTax());
    }
}

public class AbstractDemo {
    public static void main(String[] args) {
        Manager m = new Manager("John", 101, 50000);
        m.display();
    }
}

Output

Expected Output:
Manager: John Salary: 50000.0 Tax: 7500.0

Key Concept

Abstract classes cannot be instantiated. They force subclasses to implement abstract methods. This provides a template/contract ensuring consistent implementation across derived classes.

Q10. Write a java program to create interface Shape get area() method create three classes Rectangle, Circle, and Triangle the shape interface.

Problem Explanation

Interfaces define contracts for multiple implementations. This program creates a Shape interface with an area() method and implements it in three different shape classes.

Step-By-Step Instructions

  • Create interface Shape with area() method
  • Create Rectangle class implementing Shape
  • Create Circle class implementing Shape
  • Create Triangle class implementing Shape
  • Implement area calculation for each shape

Code

Java
interface Shape {
    double area();
}

class Rectangle implements Shape {
    double length, width;
    
    Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }
    
    public double area() {
        return length * width;
    }
}

class Circle implements Shape {
    double radius;
    
    Circle(double radius) {
        this.radius = radius;
    }
    
    public double area() {
        return Math.PI * radius * radius;
    }
}

class Triangle implements Shape {
    double base, height;
    
    Triangle(double base, double height) {
        this.base = base;
        this.height = height;
    }
    
    public double area() {
        return 0.5 * base * height;
    }
}

public class ShapeDemo {
    public static void main(String[] args) {
        Rectangle r = new Rectangle(10, 5);
        Circle c = new Circle(7);
        Triangle t = new Triangle(8, 6);
        
        System.out.println("Rectangle Area: " + r.area());
        System.out.println("Circle Area: " + c.area());
        System.out.println("Triangle Area: " + t.area());
    }
}

Output

Expected Output:
Rectangle Area: 50.0 Circle Area: 153.93804... Triangle Area: 24.0

Key Concept

Interfaces enable polymorphism. Multiple classes implement the same interface differently. This allows treating different objects uniformly through the interface type, demonstrating the power of polymorphism.

Q11. write a java program to two threads one prints HELLO and another print HI.

Problem Explanation

Multithreading allows concurrent execution of tasks. This program creates two threads that run simultaneously, each printing different messages.

Step-By-Step Instructions

  • Create class extending Thread
  • Override run() method with task
  • Create two thread instances
  • Start threads using start() method

Code

Java
class HelloThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("HELLO");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class HiThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("HI");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class MultithreadingDemo {
    public static void main(String[] args) {
        HelloThread t1 = new HelloThread();
        HiThread t2 = new HiThread();
        
        t1.start();
        t2.start();
    }
}

Output

Expected Output (Interleaved):
HELLO HI HI HELLO HELLO HI HI HELLO HI HELLO (Output may vary due to thread scheduling)

Key Concept

Threads are independent execution paths. The run() method contains the task. start() begins execution, not run(). Thread.sleep() pauses execution. Output order varies due to scheduler.

Q12. Write a java program Display Num Thread.

Problem Explanation

This program creates a thread that displays thread information like name, ID, and priority. It demonstrates thread lifecycle and properties.

Step-By-Step Instructions

  • Create thread class
  • Get current thread reference using Thread.currentThread()
  • Display thread properties (name, ID, priority)
  • Run and observe thread information

Code

Java
public class DisplayThread extends Thread {
    public void run() {
        Thread t = Thread.currentThread();
        System.out.println("Thread Name: " + t.getName());
        System.out.println("Thread ID: " + t.getId());
        System.out.println("Thread Priority: " + t.getPriority());
        System.out.println("Thread State: " + t.getState());
    }
    
    public static void main(String[] args) {
        DisplayThread t1 = new DisplayThread();
        t1.setName("MyThread");
        t1.setPriority(Thread.MAX_PRIORITY);
        t1.start();
    }
}

Output

Expected Output:
Thread Name: MyThread Thread ID: 11 Thread Priority: 10 Thread State: RUNNABLE

Key Concept

Thread properties include name, ID, priority (1-10), and state (RUNNABLE, WAITING, TERMINATED, etc.). Thread.currentThread() gets current executing thread. setName() and setPriority() customize thread behavior.

Q13. Write a java program create a method that takes an interger as parameter and throws exception if the number is odd.

Problem Explanation

Exception handling allows programs to handle errors gracefully. This program throws a custom exception when an odd number is encountered.

Step-By-Step Instructions

  • Create custom exception class
  • Create method that checks number
  • Throw exception if odd
  • Catch exception in main method

Code

Java
class OddNumberException extends Exception {
    public OddNumberException(String message) {
        super(message);
    }
}

public class ExceptionDemo {
    static void checkEvenOdd(int num) throws OddNumberException {
        if (num % 2 != 0) {
            throw new OddNumberException("Number is odd: " + num);
        } else {
            System.out.println("Number is even: " + num);
        }
    }
    
    public static void main(String[] args) {
        try {
            checkEvenOdd(10);
            checkEvenOdd(7);  // This will throw exception
        } catch (OddNumberException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }
}

Output

Expected Output:
Number is even: 10 Exception caught: Number is odd: 7

Key Concept

Custom exceptions extend Exception class. throw keyword raises exception. throws specifies that method may throw exception. try-catch handles exceptions. This provides robust error management.

Q14. write a java program design GUI FIR Temprature converter using appropriate components.

Problem Explanation

This program creates a graphical interface using Swing components for temperature conversion between Celsius and Fahrenheit. GUI components include JFrame, JLabel, JTextField, and JButton.

Step-By-Step Instructions

  • Create JFrame for window
  • Add JLabel and JTextField for input
  • Add JButton for conversion
  • Add ActionListener for button
  • Display result in output field

Code

Java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TempConverter extends JFrame {
    JTextField tfCelsius, tfFahrenheit;
    JButton btnConvert;
    
    TempConverter() {
        setTitle("Temperature Converter");
        setSize(400, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        
        add(new JLabel("Celsius:"));
        tfCelsius = new JTextField(10);
        add(tfCelsius);
        
        add(new JLabel("Fahrenheit:"));
        tfFahrenheit = new JTextField(10);
        tfFahrenheit.setEditable(false);
        add(tfFahrenheit);
        
        btnConvert = new JButton("Convert");
        btnConvert.addActionListener(e -> convert());
        add(btnConvert);
        
        setVisible(true);
    }
    
    void convert() {
        double celsius = Double.parseDouble(tfCelsius.getText());
        double fahrenheit = (celsius * 9/5) + 32;
        tfFahrenheit.setText(String.valueOf(fahrenheit));
    }
    
    public static void main(String[] args) {
        new TempConverter();
    }
}

Output

Expected Output:
GUI window with: - Input field for Celsius - Convert button - Output field showing Fahrenheit Example: 25°C = 77°F

Key Concept

Swing provides GUI components. JFrame is the main window. FlowLayout arranges components. ActionListener handles button clicks. Event-driven programming responds to user interactions.

Q15. write a java program display previous number in second textfield and next number in the third textfield.

Problem Explanation

This program creates a GUI with three text fields: one for input and two for displaying the previous (n-1) and next (n+1) numbers based on input.

Step-By-Step Instructions

  • Create JFrame with three JTextFields
  • First field for user input
  • Second field for previous number
  • Third field for next number
  • Use KeyListener or DocumentListener for real-time update

Code

Java
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;

public class NumberNavigator extends JFrame {
    JTextField tfInput, tfPrevious, tfNext;
    
    NumberNavigator() {
        setTitle("Number Navigator");
        setSize(400, 150);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        
        add(new JLabel("Enter Number:"));
        tfInput = new JTextField(10);
        add(tfInput);
        
        add(new JLabel("Previous:"));
        tfPrevious = new JTextField(10);
        tfPrevious.setEditable(false);
        add(tfPrevious);
        
        add(new JLabel("Next:"));
        tfNext = new JTextField(10);
        tfNext.setEditable(false);
        add(tfNext);
        
        tfInput.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) { update(); }
            public void removeUpdate(DocumentEvent e) { update(); }
            public void changedUpdate(DocumentEvent e) { update(); }
            
            void update() {
                try {
                    int num = Integer.parseInt(tfInput.getText());
                    tfPrevious.setText(String.valueOf(num - 1));
                    tfNext.setText(String.valueOf(num + 1));
                } catch (NumberFormatException ex) {
                    tfPrevious.setText("");
                    tfNext.setText("");
                }
            }
        });
        
        setVisible(true);
    }
    
    public static void main(String[] args) {
        new NumberNavigator();
    }
}

Output

Expected Output:
GUI window showing: Input: 10 Previous: 9 Next: 11 Input: 100 Previous: 99 Next: 101 (Updates in real-time as you type)

Key Concept

DocumentListener detects text changes in real-time. insertUpdate(), removeUpdate(), and changedUpdate() handle different editing operations. This provides immediate feedback without clicking a button.

Q16. write a java program create simple calculator.

Problem Explanation

This program creates a simple calculator GUI that performs basic arithmetic operations (addition, subtraction, multiplication, division) on two numbers.

Step-By-Step Instructions

  • Create JFrame with layout
  • Add input fields for two numbers
  • Add buttons for operations (+, -, *, /)
  • Add result field
  • Implement action listeners for buttons

Code

Java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Calculator extends JFrame {
    JTextField tf1, tf2, tfResult;
    JButton btnAdd, btnSub, btnMul, btnDiv;
    
    Calculator() {
        setTitle("Simple Calculator");
        setSize(400, 250);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        
        add(new JLabel("Number 1:"));
        tf1 = new JTextField(10);
        add(tf1);
        
        add(new JLabel("Number 2:"));
        tf2 = new JTextField(10);
        add(tf2);
        
        btnAdd = new JButton("+");
        btnAdd.addActionListener(e -> calculate('+'));
        add(btnAdd);
        
        btnSub = new JButton("-");
        btnSub.addActionListener(e -> calculate('-'));
        add(btnSub);
        
        btnMul = new JButton("*");
        btnMul.addActionListener(e -> calculate('*'));
        add(btnMul);
        
        btnDiv = new JButton("/");
        btnDiv.addActionListener(e -> calculate('/'));
        add(btnDiv);
        
        add(new JLabel("Result:"));
        tfResult = new JTextField(10);
        tfResult.setEditable(false);
        add(tfResult);
        
        setVisible(true);
    }
    
    void calculate(char op) {
        try {
            double n1 = Double.parseDouble(tf1.getText());
            double n2 = Double.parseDouble(tf2.getText());
            double result = 0;
            
            switch (op) {
                case '+': result = n1 + n2; break;
                case '-': result = n1 - n2; break;
                case '*': result = n1 * n2; break;
                case '/': result = n1 / n2; break;
            }
            tfResult.setText(String.valueOf(result));
        } catch (NumberFormatException ex) {
            tfResult.setText("Invalid Input");
        }
    }
    
    public static void main(String[] args) {
        new Calculator();
    }
}

Output

Expected Output:
Number 1: 10 Number 2: 5 Click + button: Result = 15.0 Click * button: Result = 50.0 Click / button: Result = 2.0

Key Concept

Calculator demonstrates event handling with multiple buttons. Each button performs different operations. ParseDouble converts string input to numbers. try-catch handles invalid input gracefully.