This is Not AD.
Join Our Telegram Channel To Get OUR all Material Up to Date.
Don't Worry Your All Info Will Be Secured
Home About Us Services Materials Contact Us
Home About Services Materials Contact
‹
›
Home
Home > JAVA | PAPER [1]

JAVA | PAPER [1]

(1) Full form of JDK.
--> Java Development Kit.

(2) Full form of IDE.
--> Integrated Development Environment.

(3) Full form of JRE.
--> Java Resource Environment.

(4) Full form of JVM.
--> Java Virtual Machine.
(1) What is Whitespace?
--> Whitespace in Java refers to any character that represents empty space, such as spaces, tabs, and newlines. They are used to separate tokens and make code readable. The compiler ignores extra whitespace.

(2) What is Literal?
--> A Literal is a constant value appearing directly in the program without calculation. It is a fixed value assigned to a variable.
Examples: 10, 4.5, 'A', "Java", true.

(1) Write a program in Java to generate first n prime numbers.
-->
    import java.util.Scanner;
    public class PrimeNumbers {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter the value of n: ");
        int n = sc.nextInt();
        int count = 0, num = 2;

        System.out.println("The first " + n + " prime numbers are:");
        while (count < n) {
            boolean isPrime = true;
            for (int i = 2; i <= Math.sqrt(num); i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                System.out.print(num + " ");
                count++;
            }
            num++;
        }
    }
}


(2) What is Command Line Argument? Explain with example.
--> * Definition:
A Command Line Argument is the information passed to a Java program at the time of its execution via the console. These arguments are stored as strings in the 'String args[]' parameter of the main() method.

Example: If we run a program as: java MyProg Hello 123 - args[0] will store "Hello" - args[1] will store "123"

Sample Code Snippet:
    public static void main(String[] args) {
        System.out.println("First Argument: " + args[0]);
    }


(1) Write a program of Jagged Array and explain it.
--> * EXPLANATION:

- A Jagged Array is an array of arrays where each member array can have a different number of columns (length).

- Unlike a standard 2D array (matrix), it does not have a rectangular shape.

- It is also known as a "Ragged Array."

- Memory is allocated dynamically for each row separately.

    
public class JaggedArrayDemo {
    public static void main(String[] args) {
        // Declare a jagged array with 3 rows
        int[][] jagged = new int[3][];

        // Define different column sizes for each row
        jagged[0] = new int[2]; // Row 0 has 2 columns
        jagged[1] = new int[4]; // Row 1 has 4 columns
        jagged[2] = new int[3]; // Row 2 has 3 columns
        
        // Initializing and Printing
        int val = 1;
        for (int i = 0; i < jagged.length; i++) {
            for (int j = 0; j < jagged[i].length; j++) {
                jagged[i][j] = val++;
                System.out.print(jagged[i][j] + " ");
            }
            System.out.println(); // Move to next line for each row
        }
    }
}


(2) Explain the Java Loop Statement and Write a program in java that calculate sum of 1 to 10 using do while loop.
--> * EXPLANATION:

Looping statements in Java are used to execute a block of code repeatedly as long as a specified condition is true.

Types of Loops in Java:

1. for loop: Used when the number of iterations is known.

2. while loop: An entry-controlled loop; checks condition first.

3. do-while loop: An exit-controlled loop; executes the body at least once before checking the condition.

4. for-each loop: Specifically used to iterate through arrays/collections.
public class DoWhileSum {
    public static void main(String[] args) {
        int sum = 0;
        int i = 1; // Initialization

        do {
            sum += i; // Add i to sum
            i++;      // Increment
        } while (i <= 10); // Condition check at the end

        System.out.println("The sum of numbers from 1 to 10 is: " + sum);
    }
}


(1) Which keyword must be used to inherit a class?
--> extends

(2) A class member declared protected becomes a member of subclass of which type?
--> It becomes a protected member of the subclass (accessible within the subclass and the same package).

(3) The class that is being inherited or subclasses is called ________.
--> Superclass (or Base class / Parent class).

(4) Java language supports ________ type of inheritance.
--> Single, Multilevel, and Hierarchical (Multiple inheritance is supported only through interfaces, not classes).
(1) Explain any four string function in java.
-->
1. length(): Returns the number of characters in the string.
2. charAt(int index): Returns the character at the specified index.
3. toLowerCase(): Converts all characters in the string to lower case.
4. toUpperCase(): Converts all characters in the string to upper case.

(2) Why Wrapper Class is needed? Explain with Example.
--> Wrapper classes provide a way to use primitive data types (int, boolean, etc.) as objects. They are essential because Java's Collection framework (like ArrayList, Vector) only stores objects, not primitive types.

Example:
    int num = 5; // Primitive
    Integer obj = Integer.valueOf(num); // Converting into Wrapper Object (Autoboxing)


(1) Write an application that illustrates method overriding in the different packages.
-->
// File 1: Animal.java inside package 'pack1'
package pack1;
public class Animal {
    public void makeSound() {
        System.out.println("Generic Animal Sound");
    }
}

// File 2: Dog.java inside package 'pack2'
package pack2;
import pack1.Animal;

public class Dog extends Animal {
    // Overriding the method from the superclass in a different package
    @Override
    public void makeSound() {
        System.out.println("Dog Barks: Woof Woof");
    }

    public static void main(String[] args) {
        Animal myDog = new Dog();
        myDog.makeSound(); // Output: Dog Barks: Woof Woof
    }
}


(2) Explain Concept of User Defined Package in brief.
--> A package in Java is used to group related classes, interfaces, and sub-packages. A User-Defined Package is created by the programmer to logically organize their own code.

* How to create: Use the package keyword at the very top of the Java source file.
* Advantages:
  1. Prevents naming conflicts (two classes can have the same name in different packages).
  2. Provides access protection (using default and protected modifiers).
  3. Makes searching and locating classes easier.

Example: package mycompany.utilities;

(1) Write a java program to demonstrate multiple inheritances using interface.
-->
// First Interface
interface Printable {
    void print();
}

// Second Interface
interface Showable {
    void show();
}

// Class implementing both interfaces to achieve multiple inheritance
public class MultipleInheritanceDemo implements Printable, Showable {
    
    // Providing implementation for Printable
    public void print() {
        System.out.println("Hello, I am Printing.");
    }

    // Providing implementation for Showable
    public void show() {
        System.out.println("Welcome, I am Showing.");
    }

    public static void main(String[] args) {
        MultipleInheritanceDemo obj = new MultipleInheritanceDemo();
        obj.print();
        obj.show();
    }
}


(2) Write a program to calculate area of circle using Constructor.
-->
import java.util.Scanner;

public class Circle {
    double radius;
    double area;

    // Parameterized Constructor to calculate area
    public Circle(double r) {
        radius = r;
        // Area formula: π * r^2
        area = Math.PI * radius * radius; 
    }

    public void displayArea() {
        System.out.println("The area of the circle with radius " 
                           + radius + " is: " + area);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the radius of the circle: ");
        double rad = sc.nextDouble();

        // Object creation calls the constructor automatically
        Circle myCircle = new Circle(rad); 
        myCircle.displayArea();
    }
}


(1) Which of the following handles the exception when a catch is not used?
--> The Default Exception Handler (provided by the JVM).

(2) When does Exceptions in Java arises in code sequence?
--> Exceptions arise during the execution of a program (at runtime) when an abnormal event occurs that disrupts the normal flow of instructions.

(3) Which keywords is used to manually throw an exception?
--> The throw keyword.

(4) Which exceptions are thrown by the JVM?
--> Unchecked exceptions (or System exceptions) like NullPointerException, ArrayIndexOutOfBoundsException, and OutOfMemoryError are implicitly thrown by the JVM.
(1) What is Thread Life cycle? Explain it.
--> The thread lifecycle describes the various states a thread goes through from its creation to its termination.



States:
1. New: A thread is in this state when an instance of the Thread class is created but start() is not yet called.
2. Runnable: After start() is invoked, the thread is ready to run and waiting for CPU time.
3. Running: The thread scheduler allocates CPU time, and the thread's run() method executes.
4. Blocked/Waiting: The thread is temporarily inactive (e.g., waiting for I/O, a lock, or sleeping).
5. Terminated (Dead): The thread has completed execution of its run() method.

(2) What is Daemon Thread?
--> A Daemon thread in Java is a low-priority background thread that provides services to user threads.

Its life depends on the user threads; if all user threads finish their execution, the JVM automatically terminates the daemon thread, regardless of whether it has finished its task.
Example: The Garbage Collector (GC) is a daemon thread.

(1) Explain Synchronization in Thread.
--> Synchronization in Java is the capability to control the access of multiple threads to any shared resource.

In a multithreaded environment, if multiple threads try to read and write shared data at the same time, it can lead to data inconsistency (Thread Interference). By using the synchronized keyword (on methods or blocks), we ensure that only one thread can execute a particular section of code at a given time, keeping the data consistent.

(2) Explain Try ... Catch Statement with suitable example.
--> The try...catch statement is used for handling exceptions in Java.
- The try block encloses the code that might generate an exception.
- The catch block handles the exception if it is thrown, preventing the program from crashing.
public class ExceptionDemo {
    public static void main(String[] args) {
        try {
            // Code that may throw an exception
            int result = 100 / 0; 
        } catch (ArithmeticException e) {
            // Handling the exception
            System.out.println("Error: Cannot divide a number by zero.");
        }
        System.out.println("Program continues normally...");
    }
}


(1) Write a program that executes two threads. One thread will print the even numbers and the another thread will print odd numbers from 1 to 50.
-->
class EvenThread extends Thread {
    public void run() {
        for (int i = 2; i <= 50; i += 2) {
            System.out.println("Even Thread: " + i);
        }
    }
}

class OddThread extends Thread {
    public void run() {
        for (int i = 1; i <= 50; i += 2) {
            System.out.println("Odd Thread: " + i);
        }
    }
}

public class PrintNumbersDemo {
    public static void main(String[] args) {
        EvenThread t1 = new EvenThread();
        OddThread t2 = new OddThread();
        
        t1.start(); // Starts EvenThread
        t2.start(); // Starts OddThread
    }
}


(2) Write a program in Java to create, write, modify, read operations on a Text file.
-->
import java.io.*;
import java.util.Scanner;

public class FileOperations {
    public static void main(String[] args) {
        String fileName = "sample.txt";

        try {
            // 1. Create and Write to file
            FileWriter writer = new FileWriter(fileName);
            writer.write("Hello! This is the initial text.\n");
            writer.close();
            System.out.println("File created and written successfully.");

            // 2. Modify (Append) file
            // Passing 'true' to FileWriter enables append mode
            FileWriter appender = new FileWriter(fileName, true);
            appender.write("This text is appended (modified).\n");
            appender.close();
            System.out.println("File modified successfully.");

            // 3. Read from file
            File myFile = new File(fileName);
            Scanner reader = new Scanner(myFile);
            System.out.println("\n--- Reading File Contents ---");
            while (reader.hasNextLine()) {
                String data = reader.nextLine();
                System.out.println(data);
            }
            reader.close();

        } catch (IOException e) {
            System.out.println("An error occurred during file operations.");
            e.printStackTrace();
        }
    }
}


(1) Which functions is called to display the output of an applet?
--> The paint() method.

(2) Which methods can be used to output a string in an applet?
--> The drawString() method (from the Graphics class).

(3) Default layout manager for subclasses of 'Window' is
--> BorderLayout.

(4) Which is the default Layout Manager for an Applet?
--> FlowLayout.
(1) What is Graphics class?
--> The Graphics class is an abstract base class in Java AWT that provides the graphics context for drawing components. It allows an application to draw shapes (lines, rectangles, ovals), text, and images onto the screen or off-screen images. Objects of this class are typically passed as arguments to the paint() method.

(2) What is NO LAYOUT Manager?
--> "No Layout Manager" (or Absolute Positioning) means setting a container's layout manager to null using setLayout(null);. When this is done, the programmer must manually specify the exact X and Y coordinates, as well as the width and height of every component using the setBounds(x, y, width, height) method.

(1) Explain Applet Life Cycle in detail.
--> An Applet undergoes several states from its creation to its destruction. The java.applet.Applet class provides specific methods corresponding to these states.



Life Cycle Methods:
1. init(): Called exactly once to initialize the applet (similar to a constructor).
2. start(): Called after init(), and every time the applet is revisited by the user. It starts the applet's execution.
3. paint(Graphics g): Called to draw the applet's interface on the screen. It is called every time the applet needs to be redrawn.
4. stop(): Called when the user leaves the web page or minimizes the browser. It pauses the applet.
5. destroy(): Called exactly once when the browser is closed or memory needs to be reclaimed. It performs final cleanup.

(2) Explain types of Layout Manager in detail.
--> Layout Managers in Java automatically arrange components within a Container.



Common Types:
1. FlowLayout: The default for Applets and Panels. It arranges components in a line, one after another (left to right). If the line is full, it moves to the next line.
2. BorderLayout: The default for Windows and Frames. It divides the container into five regions: North, South, East, West, and Center.
3. GridLayout: Arranges components in a rectangular grid defined by a specific number of rows and columns. All components are of equal size.
4. CardLayout: Treats components as a stack of cards, where only one "card" (component) is visible at a time.
5. GridBagLayout: The most flexible and complex layout manager. It places components in a grid, but allows components to span multiple rows or columns and vary in size.

(1) Write a Java program compute factorial value using Applet.
-->
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/*
<applet code="FactorialApplet" width="300" height="200">
</applet>
*/

public class FactorialApplet extends Applet implements ActionListener {
    TextField t1;
    Button b1;
    Label l1, l2;

    public void init() {
        l1 = new Label("Enter a Number: ");
        t1 = new TextField(10);
        b1 = new Button("Calculate Factorial");
        l2 = new Label("Result will appear here.");

        add(l1);
        add(t1);
        add(b1);
        add(l2);

        b1.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == b1) {
            try {
                int num = Integer.parseInt(t1.getText());
                long fact = 1;
                for (int i = 1; i <= num; i++) {
                    fact = fact * i;
                }
                l2.setText("Factorial of " + num + " is " + fact);
            } catch (NumberFormatException ex) {
                l2.setText("Please enter a valid integer.");
            }
        }
    }
}


(2) Explain GridBagLayout with GridBagConstraints in detail.
--> GridBagLayout is the most flexible layout manager in AWT. It aligns components in a dynamic grid, but unlike GridLayout, components can vary in size and span multiple rows or columns.

To use it effectively, you must configure a GridBagConstraints object for each component to dictate how it should be placed in the grid.



Key GridBagConstraints Properties:
* gridx, gridy: Specifies the cell at the upper left of the component's display area, where (0,0) is the top-left.
* gridwidth, gridheight: Specifies the number of columns or rows the component occupies (spanning).
* fill: Determines how the component fills its display area if the area is larger than the component's requested size (e.g., HORIZONTAL, VERTICAL, BOTH, NONE).
* ipadx, ipady: Specifies internal padding (spacing added inside the component).
* insets: Specifies external padding (margins around the component).
* weightx, weighty: Used to determine how to distribute extra, empty space horizontally or vertically when the window is resized.
* anchor: Determines where to place the component within its display area when the component is smaller than its area (e.g., NORTH, CENTER, WEST).

(1) The size of a frame on the screen is measured in ______.
--> Pixels.

(2) Which methods can be used to know which key is pressed?
--> getKeyCode() and getKeyChar() methods of the KeyEvent class.

(3) Which package provides many event classes and Listener interfaces for event handling?
--> java.awt.event

(4) By which method you can set or change the text in a Label?
--> setText(String text)
(1) Difference between JFrame, JPanel.
-->
* JFrame: It is a top-level container that provides a window with a title bar, border, and close buttons. It is an independent container that cannot be added inside other containers.
* JPanel: It is a lightweight, invisible middle-tier container used to group smaller components (like buttons and text fields) together. It does not have a title bar and must be added to a top-level container (like a JFrame) to be visible.

(2) Difference between AWT and Swing Components.
-->
1. Platform Dependency: AWT components are platform-dependent (they look different on Windows, Mac, Linux). Swing components are platform-independent (look the same everywhere).
2. Weight: AWT components are Heavyweight (rely on the underlying OS). Swing components are Lightweight (written entirely in Java).
3. MVC Pattern: Swing supports the Model-View-Controller design pattern; AWT does not.
4. Naming: Swing components generally start with 'J' (e.g., JButton, JLabel), whereas AWT components do not (e.g., Button, Label).



(1) Explain Event Delegation Model in detail.
--> The Event Delegation Model is the standard mechanism in Java for handling UI events. It relies on a "source" and "listener" relationship to separate the user interface code from the logic that handles events.



Key Components:
1. Event Source: The UI component (e.g., a Button) that generates an event when the user interacts with it.
2. Event Object: An object that encapsulates the details of the event that occurred (e.g., ActionEvent).
3. Event Listener: An interface (e.g., ActionListener) containing methods that receive and process the event object.

How it works: The Source delegates the event handling to the Listener. The Listener must be registered with the Source (e.g., button.addActionListener(this)). When the event occurs, the Source invokes the appropriate method on the registered Listener, passing the Event Object.

(2) What is Adapter Classes? Explain Adapter Classes in detail.
--> An Adapter Class is an abstract class in Java that provides default, empty implementations for all methods of a corresponding Event Listener interface.

Why it is used: Many Listener interfaces (like WindowListener or MouseListener) have multiple methods. If you implement the interface directly, you are forced to override all its methods, even if you only need one (leaving the rest with empty bodies). By extending an Adapter Class (like WindowAdapter), you only need to override the specific method you care about, keeping the code clean and readable.

Example: Extending MouseAdapter allows you to only override mouseClicked() without having to write empty methods for mouseEntered(), mouseExited(), etc.

(1) Write a calculator program using Java swing.
-->
import javax.swing.*;
import java.awt.event.*;

public class SimpleCalculator implements ActionListener {
    JFrame frame;
    JTextField t1, t2, result;
    JButton bAdd, bSub;

    SimpleCalculator() {
        frame = new JFrame("Calculator");
        
        t1 = new JTextField();
        t1.setBounds(50, 50, 150, 20);
        
        t2 = new JTextField();
        t2.setBounds(50, 100, 150, 20);
        
        result = new JTextField();
        result.setBounds(50, 150, 150, 20);
        result.setEditable(false);
        
        bAdd = new JButton("+");
        bAdd.setBounds(50, 200, 50, 50);
        
        bSub = new JButton("-");
        bSub.setBounds(120, 200, 50, 50);
        
        bAdd.addActionListener(this);
        bSub.addActionListener(this);
        
        frame.add(t1); frame.add(t2); frame.add(result);
        frame.add(bAdd); frame.add(bSub);
        
        frame.setSize(300, 350);
        frame.setLayout(null);
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        String s1 = t1.getText();
        String s2 = t2.getText();
        int a = Integer.parseInt(s1);
        int b = Integer.parseInt(s2);
        int c = 0;
        
        if (e.getSource() == bAdd) {
            c = a + b;
        } else if (e.getSource() == bSub) {
            c = a - b;
        }
        result.setText(String.valueOf(c));
    }

    public static void main(String[] args) {
        new SimpleCalculator();
    }
}


(2) Write a Program to demonstrate the menu using swing.
-->
import javax.swing.*;

public class SwingMenuDemo {
    public static void main(String[] args) {
        // 1. Create the top-level container
        JFrame frame = new JFrame("Menu Demonstration");

        // 2. Create the Menu Bar
        JMenuBar menuBar = new JMenuBar();

        // 3. Create a Menu
        JMenu fileMenu = new JMenu("File");

        // 4. Create Menu Items
        JMenuItem newItem = new JMenuItem("New");
        JMenuItem openItem = new JMenuItem("Open");
        JMenuItem saveItem = new JMenuItem("Save");
        JMenuItem exitItem = new JMenuItem("Exit");

        // 5. Add Menu Items to the Menu
        fileMenu.add(newItem);
        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.addSeparator(); // Adds a visual dividing line
        fileMenu.add(exitItem);

        // 6. Add the Menu to the Menu Bar
        menuBar.add(fileMenu);

        // 7. Set the Menu Bar to the Frame
        frame.setJMenuBar(menuBar);

        // Frame configurations
        frame.setSize(400, 300);
        frame.setLayout(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}


No comments:

Post a Comment

Wednesday, 4 March 2026

JAVA | PAPER [1]

JAVA | PAPER [1]

(1) Full form of JDK.
--> Java Development Kit.

(2) Full form of IDE.
--> Integrated Development Environment.

(3) Full form of JRE.
--> Java Resource Environment.

(4) Full form of JVM.
--> Java Virtual Machine.
(1) What is Whitespace?
--> Whitespace in Java refers to any character that represents empty space, such as spaces, tabs, and newlines. They are used to separate tokens and make code readable. The compiler ignores extra whitespace.

(2) What is Literal?
--> A Literal is a constant value appearing directly in the program without calculation. It is a fixed value assigned to a variable.
Examples: 10, 4.5, 'A', "Java", true.

(1) Write a program in Java to generate first n prime numbers.
-->
    import java.util.Scanner;
    public class PrimeNumbers {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter the value of n: ");
        int n = sc.nextInt();
        int count = 0, num = 2;

        System.out.println("The first " + n + " prime numbers are:");
        while (count < n) {
            boolean isPrime = true;
            for (int i = 2; i <= Math.sqrt(num); i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                System.out.print(num + " ");
                count++;
            }
            num++;
        }
    }
}


(2) What is Command Line Argument? Explain with example.
--> * Definition:
A Command Line Argument is the information passed to a Java program at the time of its execution via the console. These arguments are stored as strings in the 'String args[]' parameter of the main() method.

Example: If we run a program as: java MyProg Hello 123 - args[0] will store "Hello" - args[1] will store "123"

Sample Code Snippet:
    public static void main(String[] args) {
        System.out.println("First Argument: " + args[0]);
    }


(1) Write a program of Jagged Array and explain it.
--> * EXPLANATION:

- A Jagged Array is an array of arrays where each member array can have a different number of columns (length).

- Unlike a standard 2D array (matrix), it does not have a rectangular shape.

- It is also known as a "Ragged Array."

- Memory is allocated dynamically for each row separately.

    
public class JaggedArrayDemo {
    public static void main(String[] args) {
        // Declare a jagged array with 3 rows
        int[][] jagged = new int[3][];

        // Define different column sizes for each row
        jagged[0] = new int[2]; // Row 0 has 2 columns
        jagged[1] = new int[4]; // Row 1 has 4 columns
        jagged[2] = new int[3]; // Row 2 has 3 columns
        
        // Initializing and Printing
        int val = 1;
        for (int i = 0; i < jagged.length; i++) {
            for (int j = 0; j < jagged[i].length; j++) {
                jagged[i][j] = val++;
                System.out.print(jagged[i][j] + " ");
            }
            System.out.println(); // Move to next line for each row
        }
    }
}


(2) Explain the Java Loop Statement and Write a program in java that calculate sum of 1 to 10 using do while loop.
--> * EXPLANATION:

Looping statements in Java are used to execute a block of code repeatedly as long as a specified condition is true.

Types of Loops in Java:

1. for loop: Used when the number of iterations is known.

2. while loop: An entry-controlled loop; checks condition first.

3. do-while loop: An exit-controlled loop; executes the body at least once before checking the condition.

4. for-each loop: Specifically used to iterate through arrays/collections.
public class DoWhileSum {
    public static void main(String[] args) {
        int sum = 0;
        int i = 1; // Initialization

        do {
            sum += i; // Add i to sum
            i++;      // Increment
        } while (i <= 10); // Condition check at the end

        System.out.println("The sum of numbers from 1 to 10 is: " + sum);
    }
}


(1) Which keyword must be used to inherit a class?
--> extends

(2) A class member declared protected becomes a member of subclass of which type?
--> It becomes a protected member of the subclass (accessible within the subclass and the same package).

(3) The class that is being inherited or subclasses is called ________.
--> Superclass (or Base class / Parent class).

(4) Java language supports ________ type of inheritance.
--> Single, Multilevel, and Hierarchical (Multiple inheritance is supported only through interfaces, not classes).
(1) Explain any four string function in java.
-->
1. length(): Returns the number of characters in the string.
2. charAt(int index): Returns the character at the specified index.
3. toLowerCase(): Converts all characters in the string to lower case.
4. toUpperCase(): Converts all characters in the string to upper case.

(2) Why Wrapper Class is needed? Explain with Example.
--> Wrapper classes provide a way to use primitive data types (int, boolean, etc.) as objects. They are essential because Java's Collection framework (like ArrayList, Vector) only stores objects, not primitive types.

Example:
    int num = 5; // Primitive
    Integer obj = Integer.valueOf(num); // Converting into Wrapper Object (Autoboxing)


(1) Write an application that illustrates method overriding in the different packages.
-->
// File 1: Animal.java inside package 'pack1'
package pack1;
public class Animal {
    public void makeSound() {
        System.out.println("Generic Animal Sound");
    }
}

// File 2: Dog.java inside package 'pack2'
package pack2;
import pack1.Animal;

public class Dog extends Animal {
    // Overriding the method from the superclass in a different package
    @Override
    public void makeSound() {
        System.out.println("Dog Barks: Woof Woof");
    }

    public static void main(String[] args) {
        Animal myDog = new Dog();
        myDog.makeSound(); // Output: Dog Barks: Woof Woof
    }
}


(2) Explain Concept of User Defined Package in brief.
--> A package in Java is used to group related classes, interfaces, and sub-packages. A User-Defined Package is created by the programmer to logically organize their own code.

* How to create: Use the package keyword at the very top of the Java source file.
* Advantages:
  1. Prevents naming conflicts (two classes can have the same name in different packages).
  2. Provides access protection (using default and protected modifiers).
  3. Makes searching and locating classes easier.

Example: package mycompany.utilities;

(1) Write a java program to demonstrate multiple inheritances using interface.
-->
// First Interface
interface Printable {
    void print();
}

// Second Interface
interface Showable {
    void show();
}

// Class implementing both interfaces to achieve multiple inheritance
public class MultipleInheritanceDemo implements Printable, Showable {
    
    // Providing implementation for Printable
    public void print() {
        System.out.println("Hello, I am Printing.");
    }

    // Providing implementation for Showable
    public void show() {
        System.out.println("Welcome, I am Showing.");
    }

    public static void main(String[] args) {
        MultipleInheritanceDemo obj = new MultipleInheritanceDemo();
        obj.print();
        obj.show();
    }
}


(2) Write a program to calculate area of circle using Constructor.
-->
import java.util.Scanner;

public class Circle {
    double radius;
    double area;

    // Parameterized Constructor to calculate area
    public Circle(double r) {
        radius = r;
        // Area formula: π * r^2
        area = Math.PI * radius * radius; 
    }

    public void displayArea() {
        System.out.println("The area of the circle with radius " 
                           + radius + " is: " + area);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the radius of the circle: ");
        double rad = sc.nextDouble();

        // Object creation calls the constructor automatically
        Circle myCircle = new Circle(rad); 
        myCircle.displayArea();
    }
}


(1) Which of the following handles the exception when a catch is not used?
--> The Default Exception Handler (provided by the JVM).

(2) When does Exceptions in Java arises in code sequence?
--> Exceptions arise during the execution of a program (at runtime) when an abnormal event occurs that disrupts the normal flow of instructions.

(3) Which keywords is used to manually throw an exception?
--> The throw keyword.

(4) Which exceptions are thrown by the JVM?
--> Unchecked exceptions (or System exceptions) like NullPointerException, ArrayIndexOutOfBoundsException, and OutOfMemoryError are implicitly thrown by the JVM.
(1) What is Thread Life cycle? Explain it.
--> The thread lifecycle describes the various states a thread goes through from its creation to its termination.



States:
1. New: A thread is in this state when an instance of the Thread class is created but start() is not yet called.
2. Runnable: After start() is invoked, the thread is ready to run and waiting for CPU time.
3. Running: The thread scheduler allocates CPU time, and the thread's run() method executes.
4. Blocked/Waiting: The thread is temporarily inactive (e.g., waiting for I/O, a lock, or sleeping).
5. Terminated (Dead): The thread has completed execution of its run() method.

(2) What is Daemon Thread?
--> A Daemon thread in Java is a low-priority background thread that provides services to user threads.

Its life depends on the user threads; if all user threads finish their execution, the JVM automatically terminates the daemon thread, regardless of whether it has finished its task.
Example: The Garbage Collector (GC) is a daemon thread.

(1) Explain Synchronization in Thread.
--> Synchronization in Java is the capability to control the access of multiple threads to any shared resource.

In a multithreaded environment, if multiple threads try to read and write shared data at the same time, it can lead to data inconsistency (Thread Interference). By using the synchronized keyword (on methods or blocks), we ensure that only one thread can execute a particular section of code at a given time, keeping the data consistent.

(2) Explain Try ... Catch Statement with suitable example.
--> The try...catch statement is used for handling exceptions in Java.
- The try block encloses the code that might generate an exception.
- The catch block handles the exception if it is thrown, preventing the program from crashing.
public class ExceptionDemo {
    public static void main(String[] args) {
        try {
            // Code that may throw an exception
            int result = 100 / 0; 
        } catch (ArithmeticException e) {
            // Handling the exception
            System.out.println("Error: Cannot divide a number by zero.");
        }
        System.out.println("Program continues normally...");
    }
}


(1) Write a program that executes two threads. One thread will print the even numbers and the another thread will print odd numbers from 1 to 50.
-->
class EvenThread extends Thread {
    public void run() {
        for (int i = 2; i <= 50; i += 2) {
            System.out.println("Even Thread: " + i);
        }
    }
}

class OddThread extends Thread {
    public void run() {
        for (int i = 1; i <= 50; i += 2) {
            System.out.println("Odd Thread: " + i);
        }
    }
}

public class PrintNumbersDemo {
    public static void main(String[] args) {
        EvenThread t1 = new EvenThread();
        OddThread t2 = new OddThread();
        
        t1.start(); // Starts EvenThread
        t2.start(); // Starts OddThread
    }
}


(2) Write a program in Java to create, write, modify, read operations on a Text file.
-->
import java.io.*;
import java.util.Scanner;

public class FileOperations {
    public static void main(String[] args) {
        String fileName = "sample.txt";

        try {
            // 1. Create and Write to file
            FileWriter writer = new FileWriter(fileName);
            writer.write("Hello! This is the initial text.\n");
            writer.close();
            System.out.println("File created and written successfully.");

            // 2. Modify (Append) file
            // Passing 'true' to FileWriter enables append mode
            FileWriter appender = new FileWriter(fileName, true);
            appender.write("This text is appended (modified).\n");
            appender.close();
            System.out.println("File modified successfully.");

            // 3. Read from file
            File myFile = new File(fileName);
            Scanner reader = new Scanner(myFile);
            System.out.println("\n--- Reading File Contents ---");
            while (reader.hasNextLine()) {
                String data = reader.nextLine();
                System.out.println(data);
            }
            reader.close();

        } catch (IOException e) {
            System.out.println("An error occurred during file operations.");
            e.printStackTrace();
        }
    }
}


(1) Which functions is called to display the output of an applet?
--> The paint() method.

(2) Which methods can be used to output a string in an applet?
--> The drawString() method (from the Graphics class).

(3) Default layout manager for subclasses of 'Window' is
--> BorderLayout.

(4) Which is the default Layout Manager for an Applet?
--> FlowLayout.
(1) What is Graphics class?
--> The Graphics class is an abstract base class in Java AWT that provides the graphics context for drawing components. It allows an application to draw shapes (lines, rectangles, ovals), text, and images onto the screen or off-screen images. Objects of this class are typically passed as arguments to the paint() method.

(2) What is NO LAYOUT Manager?
--> "No Layout Manager" (or Absolute Positioning) means setting a container's layout manager to null using setLayout(null);. When this is done, the programmer must manually specify the exact X and Y coordinates, as well as the width and height of every component using the setBounds(x, y, width, height) method.

(1) Explain Applet Life Cycle in detail.
--> An Applet undergoes several states from its creation to its destruction. The java.applet.Applet class provides specific methods corresponding to these states.



Life Cycle Methods:
1. init(): Called exactly once to initialize the applet (similar to a constructor).
2. start(): Called after init(), and every time the applet is revisited by the user. It starts the applet's execution.
3. paint(Graphics g): Called to draw the applet's interface on the screen. It is called every time the applet needs to be redrawn.
4. stop(): Called when the user leaves the web page or minimizes the browser. It pauses the applet.
5. destroy(): Called exactly once when the browser is closed or memory needs to be reclaimed. It performs final cleanup.

(2) Explain types of Layout Manager in detail.
--> Layout Managers in Java automatically arrange components within a Container.



Common Types:
1. FlowLayout: The default for Applets and Panels. It arranges components in a line, one after another (left to right). If the line is full, it moves to the next line.
2. BorderLayout: The default for Windows and Frames. It divides the container into five regions: North, South, East, West, and Center.
3. GridLayout: Arranges components in a rectangular grid defined by a specific number of rows and columns. All components are of equal size.
4. CardLayout: Treats components as a stack of cards, where only one "card" (component) is visible at a time.
5. GridBagLayout: The most flexible and complex layout manager. It places components in a grid, but allows components to span multiple rows or columns and vary in size.

(1) Write a Java program compute factorial value using Applet.
-->
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/*
<applet code="FactorialApplet" width="300" height="200">
</applet>
*/

public class FactorialApplet extends Applet implements ActionListener {
    TextField t1;
    Button b1;
    Label l1, l2;

    public void init() {
        l1 = new Label("Enter a Number: ");
        t1 = new TextField(10);
        b1 = new Button("Calculate Factorial");
        l2 = new Label("Result will appear here.");

        add(l1);
        add(t1);
        add(b1);
        add(l2);

        b1.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == b1) {
            try {
                int num = Integer.parseInt(t1.getText());
                long fact = 1;
                for (int i = 1; i <= num; i++) {
                    fact = fact * i;
                }
                l2.setText("Factorial of " + num + " is " + fact);
            } catch (NumberFormatException ex) {
                l2.setText("Please enter a valid integer.");
            }
        }
    }
}


(2) Explain GridBagLayout with GridBagConstraints in detail.
--> GridBagLayout is the most flexible layout manager in AWT. It aligns components in a dynamic grid, but unlike GridLayout, components can vary in size and span multiple rows or columns.

To use it effectively, you must configure a GridBagConstraints object for each component to dictate how it should be placed in the grid.



Key GridBagConstraints Properties:
* gridx, gridy: Specifies the cell at the upper left of the component's display area, where (0,0) is the top-left.
* gridwidth, gridheight: Specifies the number of columns or rows the component occupies (spanning).
* fill: Determines how the component fills its display area if the area is larger than the component's requested size (e.g., HORIZONTAL, VERTICAL, BOTH, NONE).
* ipadx, ipady: Specifies internal padding (spacing added inside the component).
* insets: Specifies external padding (margins around the component).
* weightx, weighty: Used to determine how to distribute extra, empty space horizontally or vertically when the window is resized.
* anchor: Determines where to place the component within its display area when the component is smaller than its area (e.g., NORTH, CENTER, WEST).

(1) The size of a frame on the screen is measured in ______.
--> Pixels.

(2) Which methods can be used to know which key is pressed?
--> getKeyCode() and getKeyChar() methods of the KeyEvent class.

(3) Which package provides many event classes and Listener interfaces for event handling?
--> java.awt.event

(4) By which method you can set or change the text in a Label?
--> setText(String text)
(1) Difference between JFrame, JPanel.
-->
* JFrame: It is a top-level container that provides a window with a title bar, border, and close buttons. It is an independent container that cannot be added inside other containers.
* JPanel: It is a lightweight, invisible middle-tier container used to group smaller components (like buttons and text fields) together. It does not have a title bar and must be added to a top-level container (like a JFrame) to be visible.

(2) Difference between AWT and Swing Components.
-->
1. Platform Dependency: AWT components are platform-dependent (they look different on Windows, Mac, Linux). Swing components are platform-independent (look the same everywhere).
2. Weight: AWT components are Heavyweight (rely on the underlying OS). Swing components are Lightweight (written entirely in Java).
3. MVC Pattern: Swing supports the Model-View-Controller design pattern; AWT does not.
4. Naming: Swing components generally start with 'J' (e.g., JButton, JLabel), whereas AWT components do not (e.g., Button, Label).



(1) Explain Event Delegation Model in detail.
--> The Event Delegation Model is the standard mechanism in Java for handling UI events. It relies on a "source" and "listener" relationship to separate the user interface code from the logic that handles events.



Key Components:
1. Event Source: The UI component (e.g., a Button) that generates an event when the user interacts with it.
2. Event Object: An object that encapsulates the details of the event that occurred (e.g., ActionEvent).
3. Event Listener: An interface (e.g., ActionListener) containing methods that receive and process the event object.

How it works: The Source delegates the event handling to the Listener. The Listener must be registered with the Source (e.g., button.addActionListener(this)). When the event occurs, the Source invokes the appropriate method on the registered Listener, passing the Event Object.

(2) What is Adapter Classes? Explain Adapter Classes in detail.
--> An Adapter Class is an abstract class in Java that provides default, empty implementations for all methods of a corresponding Event Listener interface.

Why it is used: Many Listener interfaces (like WindowListener or MouseListener) have multiple methods. If you implement the interface directly, you are forced to override all its methods, even if you only need one (leaving the rest with empty bodies). By extending an Adapter Class (like WindowAdapter), you only need to override the specific method you care about, keeping the code clean and readable.

Example: Extending MouseAdapter allows you to only override mouseClicked() without having to write empty methods for mouseEntered(), mouseExited(), etc.

(1) Write a calculator program using Java swing.
-->
import javax.swing.*;
import java.awt.event.*;

public class SimpleCalculator implements ActionListener {
    JFrame frame;
    JTextField t1, t2, result;
    JButton bAdd, bSub;

    SimpleCalculator() {
        frame = new JFrame("Calculator");
        
        t1 = new JTextField();
        t1.setBounds(50, 50, 150, 20);
        
        t2 = new JTextField();
        t2.setBounds(50, 100, 150, 20);
        
        result = new JTextField();
        result.setBounds(50, 150, 150, 20);
        result.setEditable(false);
        
        bAdd = new JButton("+");
        bAdd.setBounds(50, 200, 50, 50);
        
        bSub = new JButton("-");
        bSub.setBounds(120, 200, 50, 50);
        
        bAdd.addActionListener(this);
        bSub.addActionListener(this);
        
        frame.add(t1); frame.add(t2); frame.add(result);
        frame.add(bAdd); frame.add(bSub);
        
        frame.setSize(300, 350);
        frame.setLayout(null);
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        String s1 = t1.getText();
        String s2 = t2.getText();
        int a = Integer.parseInt(s1);
        int b = Integer.parseInt(s2);
        int c = 0;
        
        if (e.getSource() == bAdd) {
            c = a + b;
        } else if (e.getSource() == bSub) {
            c = a - b;
        }
        result.setText(String.valueOf(c));
    }

    public static void main(String[] args) {
        new SimpleCalculator();
    }
}


(2) Write a Program to demonstrate the menu using swing.
-->
import javax.swing.*;

public class SwingMenuDemo {
    public static void main(String[] args) {
        // 1. Create the top-level container
        JFrame frame = new JFrame("Menu Demonstration");

        // 2. Create the Menu Bar
        JMenuBar menuBar = new JMenuBar();

        // 3. Create a Menu
        JMenu fileMenu = new JMenu("File");

        // 4. Create Menu Items
        JMenuItem newItem = new JMenuItem("New");
        JMenuItem openItem = new JMenuItem("Open");
        JMenuItem saveItem = new JMenuItem("Save");
        JMenuItem exitItem = new JMenuItem("Exit");

        // 5. Add Menu Items to the Menu
        fileMenu.add(newItem);
        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.addSeparator(); // Adds a visual dividing line
        fileMenu.add(exitItem);

        // 6. Add the Menu to the Menu Bar
        menuBar.add(fileMenu);

        // 7. Set the Menu Bar to the Frame
        frame.setJMenuBar(menuBar);

        // Frame configurations
        frame.setSize(400, 300);
        frame.setLayout(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}


GOHEL MANTHAN - March 04, 2026
‹
›
Home

Creating innovative solutions for a connected world.

Email On

manthangohel04@gmail.com

This website was designed , developed and maintenance by GOHEL MANTHAN © 2026