Skip to main content

Chapter 2

OOP in Java

TU BCA past exam questions

Past questions and answers

80 questions set from this chapter. Most repeated first.

  • 2019 · 5 marks

Define OOP. Explain features of Object Oriented Programming Language.

Answer

Object Oriented Programming (OOP) is a programming paradigm in which a program is organised as a collection of objects. An object combines data (attributes) and the functions that operate on it (methods), and objects communicate by passing messages. It models real-world entities and emphasises data security and reuse rather than procedures alone.

Features of an object oriented language

  1. Class and object: a class is a blueprint that defines data and methods; an object is an instance of a class.
  2. Encapsulation: wrapping data and methods in one unit (class) and restricting direct access with access modifiers, so data is protected.
  3. Abstraction: showing only essential features and hiding implementation details, using abstract classes and interfaces.
  4. Inheritance: a new class (subclass) acquires the properties and methods of an existing class (superclass), giving code reuse and a hierarchy.
  5. Polymorphism: one name having many forms, either compile-time (method overloading) or run-time (method overriding).
  6. Message passing and dynamic binding: objects interact by calling each other's methods, and the method to execute is decided at run time.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 5 marks

Explain different types of control statements used in java.

Answer

Control statements decide the order in which statements of a program are executed. Java has three groups.

1. Selection (decision-making) statements

  • if, if-else, nested if and if-else-if ladder:
if (marks >= 40) System.out.println("Pass");
else System.out.println("Fail");
  • switch selects one of many blocks depending on the value of an expression:
switch (day) {
    case 1: System.out.println("Sunday"); break;
    case 2: System.out.println("Monday"); break;
    default: System.out.println("Other");
}

2. Iteration (looping) statements

  • for loop: for (int i = 1; i <= 5; i++) System.out.println(i);
  • while loop: tests the condition before each iteration.
  • do-while loop: executes the body at least once, then tests the condition.
  • Enhanced for loop: for (int x : arr) System.out.println(x);

3. Jump statements

  • break leaves a loop or switch immediately.
  • continue skips the rest of the current iteration and goes to the next one.
  • return exits from a method, optionally with a value.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 5 marks

Define Abstract Class. Explain different types of Access controls available in java.

Answer

Abstract class

An abstract class is a class declared with the keyword abstract. It cannot be instantiated and may contain abstract methods (methods with no body) as well as normal methods, fields and constructors. A subclass must override all abstract methods or itself be declared abstract.

abstract class Shape {
    abstract double area();          // abstract method
    void show() { System.out.println("Shape"); }
}
class Circle extends Shape {
    double r = 2;
    double area() { return Math.PI * r * r; }
}

Access controls (access modifiers) in Java

ModifierSame classSame packageSubclass in other packageOther packages
privateYesNoNoNo
default (no keyword)YesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes
  • private: accessible only inside the class where it is declared.
  • default: accessible only within the same package.
  • protected: accessible within the package and in subclasses, even in other packages.
  • public: accessible from everywhere.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 5 marks

Define method overriding? Write any program to implement concept of multiple inheritance in java.

Answer

Method overriding

Method overriding is when a subclass provides its own implementation of a method that is already defined in its superclass, with the same name, parameters and return type. The method that runs is decided at run time by the type of the actual object (run-time polymorphism). The overriding method cannot have weaker access and static, final and private methods cannot be overridden.

class Animal { void sound() { System.out.println("Animal sound"); } }
class Dog extends Animal {
    @Override
    void sound() { System.out.println("Dog barks"); }
}

Multiple inheritance

Java does not allow a class to extend more than one class (to avoid ambiguity), but multiple inheritance of type is achieved using interfaces.

interface Printable {
    void print();
}
interface Showable {
    void show();
}
class Document implements Printable, Showable {
    public void print() { System.out.println("Printing document"); }
    public void show()  { System.out.println("Showing document"); }
}
public class MultipleInheritance {
    public static void main(String[] args) {
        Document d = new Document();
        d.print();
        d.show();
    }
}

Output:

Printing document
Showing document

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 5 marks

Why it is important to handle exception in java? Write a program to illustrate the use of exception handling.

Answer

Why exception handling is important

An exception is an abnormal event during execution that disrupts the normal flow of the program. Handling it is important because:

  • The program does not terminate abruptly; it can recover or end gracefully.
  • Error-handling code is separated from normal logic, making code cleaner.
  • Errors can be propagated up the call stack to a method that knows how to deal with them.
  • Resources such as files and connections can be released properly (using finally).
  • Meaningful messages can be shown to the user instead of a system crash.

Program

public class ExceptionDemo {
    public static void main(String[] args) {
        int[] a = {10, 20, 30};
        try {
            int x = 10 / 0;                       // ArithmeticException
            System.out.println(x);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero: " + e.getMessage());
        }
        try {
            System.out.println(a[5]);             // ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Invalid index: " + e.getMessage());
        } finally {
            System.out.println("Finally block always executes");
        }
        System.out.println("Program continues normally");
    }
}

Output:

Cannot divide by zero: / by zero
Invalid index: Index 5 out of bounds for length 3
Finally block always executes
Program continues normally

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 5 marks

Define the use of static keyword. Write any four String methods used in java with example.

Answer

Use of the static keyword

static makes a member belong to the class rather than to any object.

  • Static variable: a single copy shared by all objects of the class (memory is allocated once).
  • Static method: can be called with the class name without creating an object; it can access only static members directly (e.g. main, Math.sqrt).
  • Static block: runs once when the class is loaded, used to initialise static data.
  • Static nested class: a nested class that does not need an instance of the outer class.
class Counter {
    static int count = 0;
    Counter() { count++; }
    static void show() { System.out.println("Objects: " + count); }
}

Four String methods

String s = "Hello World";
System.out.println(s.length());           // 11
System.out.println(s.toUpperCase());      // HELLO WORLD
System.out.println(s.charAt(4));          // o
System.out.println(s.substring(6));       // World
  • length() returns the number of characters.
  • toUpperCase() returns the string in upper case (toLowerCase() does the opposite).
  • charAt(i) returns the character at index i.
  • substring(begin) returns the part of the string from index begin to the end.

Other useful methods are equals(), concat(), indexOf() and replace().

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 5 marks

Define super, final and this keyword in java. Explain the concept of MVC in brief.

Answer

super keyword

super refers to the immediate parent class. It is used to call the superclass constructor (super(args), which must be the first statement), to access a hidden superclass variable (super.x) and to call an overridden superclass method (super.show()).

final keyword

  • A final variable is a constant and cannot be reassigned.
  • A final method cannot be overridden.
  • A final class cannot be extended (e.g. String).

this keyword

this refers to the current object. It is used to distinguish instance variables from parameters with the same name (this.name = name), to call another constructor of the same class (this(...)), to call a current-class method and to pass the current object as an argument.

class A { int x = 10; A(int x) { this.x = x; } }
class B extends A {
    B() { super(5); }
    void show() { System.out.println(super.x); }
}

MVC (Model-View-Controller)

MVC is a design pattern that divides an application into three parts:

  • Model: holds the data and business logic (e.g. a Student class or database access); it is independent of the user interface.
  • View: the presentation layer that displays the model's data to the user (e.g. a Swing form, JSP page).
  • Controller: receives user input, updates the model and selects the view to refresh.

The user acts on the view, the controller handles the request and updates the model, and the view shows the new state. This separation makes code easier to maintain, test and reuse.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 10 marks

a) Define multithreading. Write a java program to show the inter-thread communication.
b) Define Stream. Write a program in java to copy the content from one file to another.

Answer

(a) Multithreading

Multithreading is the ability of a program to execute two or more threads (lightweight units of execution) concurrently within a single process. Threads share the same memory, so it gives better CPU utilisation and responsiveness. A thread is created by extending the Thread class or implementing Runnable.

Inter-thread communication lets threads cooperate using wait(), notify() and notifyAll() inside synchronized code. The following producer-consumer program shows it.

class Buffer {
    private int data;
    private boolean available = false;

    synchronized void put(int value) {
        while (available) {
            try { wait(); } catch (InterruptedException e) { }
        }
        data = value;
        available = true;
        System.out.println("Produced: " + value);
        notify();
    }

    synchronized int get() {
        while (!available) {
            try { wait(); } catch (InterruptedException e) { }
        }
        available = false;
        System.out.println("Consumed: " + data);
        notify();
        return data;
    }
}

class Producer extends Thread {
    Buffer b;
    Producer(Buffer b) { this.b = b; }
    public void run() { for (int i = 1; i <= 5; i++) b.put(i); }
}

class Consumer extends Thread {
    Buffer b;
    Consumer(Buffer b) { this.b = b; }
    public void run() { for (int i = 1; i <= 5; i++) b.get(); }
}

public class InterThreadDemo {
    public static void main(String[] args) {
        Buffer b = new Buffer();
        new Producer(b).start();
        new Consumer(b).start();
    }
}

The producer waits while the value has not been consumed and the consumer waits until a value is produced, so the output alternates: Produced 1, Consumed 1, Produced 2, and so on.

(b) Stream

A stream is a continuous flow of data between a program and a source or destination (file, keyboard, network). Byte streams (InputStream, OutputStream) handle binary data and character streams (Reader, Writer) handle text.

Program to copy one file to another

import java.io.*;

public class FileCopy {
    public static void main(String[] args) {
        try (FileInputStream in = new FileInputStream("source.txt");
             FileOutputStream out = new FileOutputStream("target.txt")) {
            int ch;
            while ((ch = in.read()) != -1) {
                out.write(ch);
            }
            System.out.println("File copied successfully");
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 10 marks

a) Define Collection Class. Explain different Wrapper classes and associated methods in java.
b) Define AWT. Explain different types of Layout Managers in java.

Answer

(a) Collection class

The Java Collections Framework (package java.util) provides classes and interfaces to store and manipulate groups of objects. The main interfaces are List, Set, Queue and Map; common classes are ArrayList, LinkedList, HashSet, TreeSet, HashMap and TreeMap. Methods include add(), remove(), get(), size(), contains() and clear().

ArrayList<String> list = new ArrayList<>();
list.add("Ram"); list.add("Sita");
System.out.println(list.get(0) + " " + list.size());

Wrapper classes

Wrapper classes convert primitive types into objects, which collections require.

PrimitiveWrapper
byte, short, int, longByte, Short, Integer, Long
float, doubleFloat, Double
char, booleanCharacter, Boolean

Associated methods:

  • Integer.parseInt(String) converts a string to an int; Integer.valueOf() returns an Integer object.
  • intValue(), doubleValue() convert the wrapped value to a primitive type (unboxing).
  • toString() returns the string form; compareTo() and equals() compare values.
  • Integer.MAX_VALUE and MIN_VALUE give limits; Character.isDigit(), isLetter() test characters.

Autoboxing and unboxing convert automatically between primitives and wrappers (Integer x = 5; int y = x;).

(b) AWT

The Abstract Window Toolkit (package java.awt) is Java's original platform-dependent GUI toolkit, with components such as Button, Label, TextField, Frame and Panel, which use native (heavyweight) peers.

Layout managers

A layout manager controls the size and position of components in a container.

  • FlowLayout: places components left to right in a row and wraps to the next row; the default for Panel.
  • BorderLayout: divides the container into North, South, East, West and Center; the default for Frame.
  • GridLayout: arranges components in a grid of equal-sized cells (rows by columns).
  • CardLayout: stacks components like cards so that only one is visible at a time.
  • GridBagLayout: a flexible grid where components can span several rows and columns and have different sizes.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 10 marks

a) List and explain any five swing controls with their uses.
b) Define JDBC. Write a program to display all records from a table of database.

Answer

(a) Five Swing controls

Swing (package javax.swing) provides lightweight, platform-independent GUI components.

  1. JLabel: displays a non-editable text or image, used for captions and messages.
  2. JTextField: a single-line text box for user input (getText(), setText()); JTextArea is the multi-line version.
  3. JButton: a push button that triggers an action when clicked, handled through an ActionListener.
  4. JCheckBox / JRadioButton: JCheckBox allows selecting any number of options; JRadioButton (grouped with ButtonGroup) allows selecting one option out of many.
  5. JComboBox: a drop-down list from which the user selects one item; JList shows a scrollable list of items. (JTable is used for tabular data.)

(b) JDBC

Java Database Connectivity (JDBC) is a Java API that lets Java programs connect to relational databases, execute SQL statements and process results. Its main parts are DriverManager, Connection, Statement/PreparedStatement and ResultSet. The steps are: load the driver, create a connection, create a statement, execute the query, process the ResultSet and close the connection.

Program to display all records of a table (MySQL database college, table student(id, name, address))

import java.sql.*;

public class DisplayRecords {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/college";
        try (Connection con = DriverManager.getConnection(url, "root", "password");
             Statement st = con.createStatement();
             ResultSet rs = st.executeQuery("SELECT * FROM student")) {

            while (rs.next()) {
                System.out.println(rs.getInt("id") + "  "
                        + rs.getString("name") + "  "
                        + rs.getString("address"));
            }
        } catch (SQLException e) {
            System.out.println("Database error: " + e.getMessage());
        }
    }
}

The MySQL connector JAR must be on the classpath. rs.next() moves to the next row and returns false when no rows remain.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 1 mark

Which one of the following is not a valid java bitwise operator? (a) >> (b) << (c) >>> (d) <<<

Answer

(d) <<<

Java has the shift operators << (left shift), >> (signed right shift) and >>> (unsigned right shift). There is no <<< operator because left shifting does not involve a sign bit, so a separate unsigned form is not needed.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 1 mark

Which one of the following keyword is used to declare an exception? (a) throws (b) throw (c) try (d) catch

Answer

(a) throws

The throws keyword is used in a method signature to declare the exceptions the method may pass to its caller. throw is used to actually raise an exception, while try and catch are used to handle one.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 20 marks

Which of these is an incorrect array declaration? (a) int ary[] = new int; (b) int[] ary = new int; (c) int ary = int new; (d) int ary[]; ary = new int;

Answer

(c) int ary = int new;

An array is declared as int ary[] = new int[size]; or int[] ary = new int[size];. The form int new has the keyword new in the wrong place and has no type with brackets, so it is not valid Java. The other options are valid ways of declaring and creating an array.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 1 mark

Which one of the following access specifier is appropriate for members of superclass to access only from subclass? (a) private (b) protected (c) public (d) default

Answer

(b) protected

A protected member is accessible in the class itself and in its subclasses (and also in the same package). private is not visible even to subclasses, public is visible to everyone and default is limited to the package.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 1 mark

Which one of the following is not a collection class defined in java? (a) Linked List (b) Hash Set (c) Tree Set (d) Graph Set

Answer

(d) Graph Set

LinkedList, HashSet and TreeSet are classes in the Java Collections Framework. There is no GraphSet class in java.util.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 1 mark

Which one of the following inheritance is best implemented using interface in java? (a) single inheritance (b) multi-level inheritance (c) multiple inheritance (d) hierarchical inheritance

Answer

(c) multiple inheritance

Java does not support multiple inheritance with classes because of ambiguity (the diamond problem), but a class can implement several interfaces, which gives multiple inheritance of type.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 1 mark

Which one of the following method is called only once during the run time of your applet? (a) stop() (b) paint() (c) init() (d) start()

Answer

(c) init()

init() is called only once, when the applet is first loaded, to initialise it. start() is called after init() and every time the applet becomes visible again, stop() is called when it is hidden and paint() is called whenever the display needs to be redrawn.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 1 mark

Which of these method of class String is used to compare two String objects for their equality? (a) equals() (b) Equals() (c) isEqual() (d) IsEqual()

Answer

(a) equals()

The String method equals() compares the contents of two strings for equality (case-sensitive). Java method names are case-sensitive, so Equals() does not exist, and isEqual() and IsEqual() are not String methods.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 1 mark

What is the default value of priority variable MIN_PRIORITY and MAX_PRIORITY? (a) 0 & 63 (b) 1 & 10 (c) 0 & 1 (d) 1 & 32

Answer

(b) 1 & 10

In the Thread class, MIN_PRIORITY is 1, NORM_PRIORITY is 5 (the default) and MAX_PRIORITY is 10.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2019 · 1 mark

Which one of the following is not java swing container? (a) Panel (b) Tabbed Pane (c) Scroll Pane (d) Scroll bar

Answer

(d) Scroll bar

JPanel, JTabbedPane and JScrollPane are Swing containers that can hold other components. A scroll bar (JScrollBar) is an individual control used to scroll, not a container.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 5 marks

Define OOP. Write the characteristics of OOP language.

Answer

Object Oriented Programming (OOP) is a programming approach in which a program is built from objects that combine data and the methods that operate on that data. Instead of focusing on procedures, it models real-world entities and their interactions.

Characteristics of an OOP language

  1. Objects and classes: a class is a template; an object is a real instance with state (attributes) and behaviour (methods).
  2. Encapsulation: binding data and methods together and hiding the internal details using access control, which protects data.
  3. Abstraction: exposing only the essential features and hiding the complex implementation (abstract classes, interfaces).
  4. Inheritance: a class can acquire the properties and behaviour of another class, promoting code reuse and hierarchical classification.
  5. Polymorphism: the same operation behaving differently in different situations, through method overloading (compile time) and overriding (run time).
  6. Message passing: objects communicate by invoking each other's methods.
  7. Dynamic binding: the code executed for a method call is determined at run time.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 5 marks

Explain the operators available in Java programming.

Answer

Operators are symbols that perform operations on one or more operands. Java provides the following groups.

1. Arithmetic operators: +, -, *, /, % (remainder). Example: 10 % 3 gives 1. For integers, / truncates, so 7 / 2 gives 3.

2. Relational operators: ==, !=, >, <, >=, <=. They compare two values and return a boolean.

3. Logical operators: && (AND), || (OR), ! (NOT). && and || short-circuit, so the right operand is evaluated only if needed.

4. Assignment operators: =, +=, -=, *=, /=, %=. Example: x += 5 means x = x + 5.

5. Unary operators: +, -, ++, --, !. Prefix ++a increments before use; postfix a++ increments after use.

6. Bitwise operators: &, |, ^, ~, <<, >>, >>>. They work on individual bits; for example 5 & 3 gives 1, and 5 << 1 gives 10.

7. Ternary (conditional) operator: condition ? value1 : value2.

8. instanceof operator: tests whether an object is an instance of a class, e.g. obj instanceof String.

public class OperatorDemo {
    public static void main(String[] args) {
        int a = 10, b = 3;
        System.out.println(a + b);            // 13
        System.out.println(a % b);            // 1
        System.out.println(a > b && b > 0);   // true
        a += 5;                               // 15
        int max = (a > b) ? a : b;            // 15
        System.out.println(max);
        System.out.println(a & b);            // 15 & 3 = 3
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 5 marks

Define loop. Write a java program to print first n prime numbers.

Answer

A loop is a control structure that repeatedly executes a block of statements as long as a given condition remains true. Java provides for, while and do-while loops (and the enhanced for-each loop for arrays and collections).

Program: print the first n prime numbers

import java.util.Scanner;

public class FirstNPrimes {
    static boolean isPrime(int num) {
        if (num < 2) return false;
        for (int i = 2; i * i <= num; i++) {
            if (num % i == 0) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = sc.nextInt();
        int count = 0, num = 2;
        while (count < n) {
            if (isPrime(num)) {
                System.out.print(num + " ");
                count++;
            }
            num++;
        }
    }
}

For n = 5 the output is 2 3 5 7 11. The outer while loop keeps testing consecutive numbers until n primes have been printed; the inner for loop checks divisors only up to num\sqrt{num}.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 5 marks

Differentiate between abstract class and interface with suitable example.

Answer

An abstract class is a class declared with abstract that may contain both abstract (bodyless) and concrete methods. An interface is a fully abstract contract that declares methods a class must implement.

BasisAbstract classInterface
Keywordabstract classinterface
MethodsAbstract and concrete methodsAbstract methods; default, static and private methods since Java 8/9
VariablesAny kind of variableOnly public static final constants
InheritanceExtended with extends; only one classImplemented with implements; many interfaces allowed
ConstructorCan have constructorsCannot have constructors
Access modifiersMembers can be private, protected, etc.Methods are implicitly public
Use"is-a" relation with shared codeCapability / multiple inheritance of type

Example

abstract class Shape {
    abstract double area();            // abstract method
    void show() { System.out.println("Area = " + area()); }  // concrete method
}

interface Drawable {
    void draw();
}

class Circle extends Shape implements Drawable {
    double r;
    Circle(double r) { this.r = r; }
    double area() { return Math.PI * r * r; }
    public void draw() { System.out.println("Drawing circle"); }
}

public class Test {
    public static void main(String[] args) {
        Circle c = new Circle(2);
        c.show();
        c.draw();
    }
}

Here Circle inherits the shared show() from the abstract class and promises the draw() behaviour through the interface.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 5 marks

Define access modifier. Explain access modifiers in java with example.

Answer

An access modifier is a keyword that sets the visibility (scope) of a class, variable, method or constructor, i.e. which other code can access it. It supports encapsulation.

Java has four access levels:

  1. public: accessible from everywhere, in any package.
  2. protected: accessible within the same package and in subclasses of other packages.
  3. default (no keyword): accessible only within the same package.
  4. private: accessible only within the declaring class.
ModifierSame classSame packageSubclass (other package)Other package
publicYesYesYesYes
protectedYesYesYesNo
defaultYesYesNoNo
privateYesNoNoNo

Example

package bank;

public class Account {
    private double balance;          // only inside Account
    String branch = "Kathmandu";     // default: same package
    protected int id = 101;          // package + subclasses
    public String name = "Ram";      // everywhere

    public void deposit(double amt) {   // controlled access to private data
        if (amt > 0) balance += amt;
    }
    public double getBalance() { return balance; }
}

Code outside Account cannot write acc.balance = 5000; (compile error), but can call acc.deposit(5000) and acc.getBalance().

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 5 marks

Define exception. Explain exception handling mechanism in java with example.

Answer

An exception is an abnormal event that occurs during program execution and disrupts the normal flow of instructions (for example division by zero, accessing an invalid array index, or a missing file). In Java an exception is an object of a class derived from java.lang.Throwable.

Exception handling mechanism

Java handles exceptions with five keywords:

  • try: encloses code that may throw an exception.
  • catch: handles a specific exception type thrown in the try block.
  • finally: block that always runs (cleanup), whether or not an exception occurs.
  • throw: explicitly throws an exception object.
  • throws: declares exceptions a method may pass to its caller.

When an error occurs, the JVM creates an exception object and looks for a matching catch. If one is found, control jumps to it; otherwise the exception propagates up the call stack and the program terminates with a stack trace.

Exceptions are either checked (compile-time checked, e.g. IOException) or unchecked (runtime, e.g. ArithmeticException).

Example

public class ExceptionDemo {
    static void check(int age) throws Exception {
        if (age < 18) throw new Exception("Not eligible to vote");
    }

    public static void main(String[] args) {
        try {
            int[] a = new int[3];
            int x = 10 / 0;              // ArithmeticException
            a[5] = 1;
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Bad index");
        } finally {
            System.out.println("finally always runs");
        }

        try {
            check(15);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Output: Error: / by zero, finally always runs, Not eligible to vote.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 5 marks

Write short note on (Any Two);
a) Final keyword
b) Collection class
c) JDBC

Answer

(a) Final keyword

final is a non-access modifier that restricts modification. It can be used in three places:

  • Final variable: its value can be assigned only once, so it becomes a constant. final double PI = 3.14159;
  • Final method: cannot be overridden by a subclass.
  • Final class: cannot be extended (inherited). String is a final class.
final class Base { }                 // cannot be subclassed
class A {
    final int MAX = 100;             // constant
    final void show() { }            // cannot be overridden
}
// MAX = 200;  -> compile-time error

(b) Collection class

The Java Collections Framework (package java.util) provides ready-made classes and interfaces to store and manipulate groups of objects dynamically. The root interface is Collection, with sub-interfaces List, Set and Queue; Map is separate.

  • List (ordered, allows duplicates): ArrayList, LinkedList, Vector.
  • Set (no duplicates): HashSet, LinkedHashSet, TreeSet.
  • Map (key-value pairs): HashMap, TreeMap, Hashtable.
  • The utility class Collections offers sort(), reverse(), max() and so on.
ArrayList<String> list = new ArrayList<>();
list.add("Ram");
list.add("Sita");
Collections.sort(list);
System.out.println(list);   // [Ram, Sita]

Unlike arrays, collections are resizable and offer built-in algorithms.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 10 marks

a) Write a program to create and use java package.
b) Define thread. Explain the life cycle of thread.

Answer

(a) Creating and using a Java package

A package groups related classes and interfaces. Step 1: create a class in a package (file mypack/Calculator.java).

package mypack;

public class Calculator {
    public int add(int a, int b) { return a + b; }
    public int multiply(int a, int b) { return a * b; }
}

Step 2: compile it with javac -d . Calculator.java, which creates the folder mypack containing Calculator.class.

Step 3: use it from another file with import.

import mypack.Calculator;

public class UsePackage {
    public static void main(String[] args) {
        Calculator c = new Calculator();
        System.out.println("Sum = " + c.add(5, 3));          // 8
        System.out.println("Product = " + c.multiply(5, 3)); // 15
    }
}

Compile and run with javac UsePackage.java and java UsePackage. The class and its used members must be public to be reachable from outside the package.

(b) Thread and its life cycle

A thread is a lightweight unit of execution within a process. Java supports multithreading, where several threads run concurrently and share the process's memory. Threads are created by extending Thread or implementing Runnable.

Life cycle of a thread (states in Thread.State):

  1. New: the thread object is created (new Thread()), but start() has not been called.
  2. Runnable: after start(), the thread is ready and waits for CPU time from the scheduler (it may also be running).
  3. Running: the scheduler has given it the CPU and run() executes.
  4. Blocked / Waiting / Timed Waiting: the thread is temporarily inactive. It may be waiting for a lock (blocked), for another thread via wait() or join() (waiting), or sleeping for a fixed period via sleep(ms) (timed waiting). It returns to Runnable when the condition ends.
  5. Terminated (Dead): run() has completed or the thread was stopped by an uncaught exception. It cannot be restarted.
class MyThread extends Thread {
    public void run() {
        for (int i = 1; i <= 3; i++) {
            System.out.println("Running " + i);
            try { Thread.sleep(500); } catch (InterruptedException e) { }
        }
    }
}
public class Life {
    public static void main(String[] args) {
        MyThread t = new MyThread();   // New
        t.start();                     // Runnable -> Running -> Timed waiting -> ... -> Terminated
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 10 marks

a) Write a program to sort name of any five cities in ascending order.
b) Define polymorphism. How do we achieve polymorphism in java explain with examples?

Answer

(a) Sorting five city names in ascending order

import java.util.Arrays;

public class SortCities {
    public static void main(String[] args) {
        String[] cities = {"Pokhara", "Kathmandu", "Biratnagar", "Lalitpur", "Butwal"};

        // bubble sort using compareTo
        for (int i = 0; i < cities.length - 1; i++) {
            for (int j = 0; j < cities.length - 1 - i; j++) {
                if (cities[j].compareTo(cities[j + 1]) > 0) {
                    String temp = cities[j];
                    cities[j] = cities[j + 1];
                    cities[j + 1] = temp;
                }
            }
        }
        System.out.println("Ascending order:");
        for (String c : cities) System.out.println(c);
        // Arrays.sort(cities) would give the same result
    }
}

Output: Biratnagar, Butwal, Kathmandu, Lalitpur, Pokhara.

(b) Polymorphism

Polymorphism means "many forms": the same name or interface behaves differently depending on the context. In Java it is of two kinds.

  1. Compile-time (static) polymorphism is achieved by method overloading: several methods in a class share a name but differ in the number or types of parameters. The compiler chooses the method at compile time.
class Calc {
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b; }
    int add(int a, int b, int c) { return a + b + c; }
}
  1. Run-time (dynamic) polymorphism is achieved by method overriding: a subclass redefines a method of its superclass, and a superclass reference holding a subclass object calls the subclass version at run time (dynamic method dispatch).
class Animal { void sound() { System.out.println("Animal sound"); } }
class Dog extends Animal { void sound() { System.out.println("Bark"); } }
class Cat extends Animal { void sound() { System.out.println("Meow"); } }

public class Test {
    public static void main(String[] args) {
        Animal a;
        a = new Dog(); a.sound();   // Bark
        a = new Cat(); a.sound();   // Meow
    }
}

Polymorphism is also achieved through interfaces and abstract classes. It makes code flexible and extensible.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2020 · 10 marks

a) Differentiate between java AWT and java Swing. Explain the different types of layout managers in java GUI programming.
b) Write a java GUI program to calculate square of entered number.

Answer

(a) AWT versus Swing

BasisAWTSwing
Packagejava.awtjavax.swing
ComponentsHeavyweight (use native OS peers)Lightweight (written in Java)
Look and feelDepends on the platformPluggable; same on all platforms
Component setLimitedRich (tables, trees, tabbed panes)
SpeedFaster to load, less flexibleSlightly slower but more powerful
NamingButton, LabelJButton, JLabel
MVCNot followedFollows MVC

Layout managers

A layout manager automatically arranges components inside a container. The main types are:

  1. FlowLayout: places components left to right in a row and wraps to the next row when full. It is the default for JPanel.
  2. BorderLayout: divides the container into five regions (NORTH, SOUTH, EAST, WEST, CENTER). It is the default for JFrame.
  3. GridLayout: arranges components in a grid of equal-sized cells (rows by columns).
  4. CardLayout: stacks components like cards so that only one is visible at a time.
  5. GridBagLayout: a flexible grid in which components may span several rows or columns, using constraints.
  6. BoxLayout: arranges components in a single row or column.

(b) GUI program to calculate the square of an entered number

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

public class SquareGUI extends JFrame implements ActionListener {
    JTextField input, output;
    JButton calc;

    SquareGUI() {
        setTitle("Square Calculator");
        setLayout(new FlowLayout());
        add(new JLabel("Enter number:"));
        input = new JTextField(10);
        add(input);
        calc = new JButton("Square");
        add(calc);
        add(new JLabel("Result:"));
        output = new JTextField(10);
        output.setEditable(false);
        add(output);
        calc.addActionListener(this);
        setSize(250, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        try {
            double n = Double.parseDouble(input.getText());
            output.setText(String.valueOf(n * n));
        } catch (NumberFormatException ex) {
            output.setText("Invalid input");
        }
    }

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

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

Explain features of Object oriented concept in detail.

Answer

Object-oriented programming (OOP) models software as a collection of objects that combine data and behaviour. Its main features are as follows.

1. Class and object. A class is a blueprint that defines data members and methods; an object is an instance of a class with its own state. Example: Student s = new Student();.

2. Encapsulation. Wrapping data and the methods that operate on it into a single unit (class) and hiding the data using private access with public getters and setters. It protects data from unwanted access.

3. Inheritance. A new class (subclass) acquires the properties and methods of an existing class (superclass) using extends. It gives code reuse and an "is-a" hierarchy.

class Person { String name; }
class Student extends Person { int roll; }

4. Polymorphism. One interface, many forms. Compile-time polymorphism is method overloading; run-time polymorphism is method overriding.

5. Abstraction. Showing only essential details while hiding implementation. It is achieved with abstract classes and interfaces.

6. Message passing / dynamic binding. Objects communicate by calling each other's methods; the method to run is resolved at run time for overridden methods.

Together these features give modular, reusable, maintainable and secure programs.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

What is a continue statement? Write a program in java that displays the sum of odd integers of an array.

Answer

The continue statement skips the remaining statements of the current iteration of a loop and moves control to the next iteration (the update expression in a for loop, or the condition test in while/do-while). It differs from break, which terminates the loop entirely.

Program: sum of odd integers of an array

public class OddSum {
    public static void main(String[] args) {
        int[] arr = {12, 7, 4, 9, 15, 20, 3};
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 == 0) {
                continue;          // skip even numbers
            }
            sum += arr[i];
        }
        System.out.println("Sum of odd integers = " + sum);
    }
}

The odd elements are 7, 9, 15 and 3, so 7+9+15+3=347 + 9 + 15 + 3 = 34 and the output is Sum of odd integers = 34.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

What is a parameterized constructor? Explain with an example.

Answer

A constructor is a special method with the same name as its class and no return type, which runs automatically when an object is created and initialises it. A parameterized constructor is a constructor that takes parameters, so each object can be initialised with different values at creation time.

If no constructor is written, Java supplies a default no-argument constructor; once a parameterized constructor is defined, the default one is no longer provided automatically.

Example

class Student {
    int roll;
    String name;

    Student(int roll, String name) {     // parameterized constructor
        this.roll = roll;
        this.name = name;
    }

    void display() {
        System.out.println(roll + " " + name);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student(1, "Ram");
        Student s2 = new Student(2, "Sita");
        s1.display();   // 1 Ram
        s2.display();   // 2 Sita
    }
}

Each object receives its own values through the arguments passed to new.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

Explain method overloading in java with proper example.

Answer

Method overloading means defining two or more methods in the same class with the same name but different parameter lists (different number, type or order of parameters). It is a form of compile-time (static) polymorphism: the compiler selects the method from the arguments in the call. The return type alone cannot distinguish overloaded methods.

Example

class Calculator {
    int add(int a, int b) {
        return a + b;
    }
    int add(int a, int b, int c) {      // different number of parameters
        return a + b + c;
    }
    double add(double a, double b) {    // different parameter types
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator c = new Calculator();
        System.out.println(c.add(2, 3));        // 5
        System.out.println(c.add(2, 3, 4));     // 9
        System.out.println(c.add(2.5, 3.5));    // 6.0
    }
}

Overloading improves readability, since one meaningful name serves related operations.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

What is the use of 'this' and 'super' keyword? Explain with examples.

Answer

this keyword

this is a reference to the current object. Its uses are:

  1. To distinguish instance variables from parameters with the same name.
  2. To call another constructor of the same class: this(...), which must be the first statement.
  3. To call a method of the current object, or pass the current object as an argument.
class Student {
    int roll; String name;
    Student() { this(0, "Unknown"); }            // calls another constructor
    Student(int roll, String name) {
        this.roll = roll;                        // field = parameter
        this.name = name;
    }
}

super keyword

super is a reference to the immediate parent class. Its uses are:

  1. To access a parent field hidden by a subclass field: super.x.
  2. To call an overridden parent method: super.show().
  3. To call the parent constructor: super(...), which must be the first statement.
class Person {
    String name = "Person";
    Person(String n) { System.out.println("Person constructor " + n); }
    void show() { System.out.println("Parent show"); }
}
class Employee extends Person {
    String name = "Employee";
    Employee() {
        super("Ram");                            // parent constructor
    }
    void show() {
        super.show();                            // parent method
        System.out.println(name + " / " + super.name);
    }
}

Calling new Employee().show() prints Person constructor Ram, Parent show, Employee / Person.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

Defined exception. How exceptions are handled in java? Explain with a proper example.

Answer

An exception is an abnormal event during program execution that disrupts normal flow, such as division by zero, an invalid array index or a missing file. In Java it is an object of a subclass of Throwable; Exception covers recoverable conditions and Error covers serious system problems.

How exceptions are handled

Java uses the keywords try, catch, finally, throw and throws:

  • Code that may fail is placed in a try block.
  • One or more catch blocks handle specific exception types; the first matching one runs.
  • A finally block runs always, for cleanup such as closing files.
  • throw raises an exception manually; throws declares that a method may pass an exception to its caller.

If no catch matches, the exception moves up the call stack and the program ends with a stack trace.

Example

import java.util.Scanner;

public class DivideDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        try {
            System.out.print("Enter two numbers: ");
            int a = sc.nextInt();
            int b = sc.nextInt();
            System.out.println("Result = " + (a / b));
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("Invalid input");
        } finally {
            System.out.println("Program finished");
        }
    }
}

For input 10 0 the output is Cannot divide by zero: / by zero followed by Program finished.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 5 marks

Write short note on (Any Two);
a) Interface
b) Access modifiers
c) JDBC

Answer

(a) Interface

An interface is a reference type that declares a set of abstract methods that implementing classes must define. It specifies what a class does, not how. Methods are implicitly public abstract, and fields are public static final. A class uses implements, and may implement several interfaces, which is how Java achieves multiple inheritance of type. An interface may also have default and static methods (Java 8).

interface Vehicle {
    void start();
}
class Car implements Vehicle {
    public void start() { System.out.println("Car starts"); }
}

Interfaces support abstraction, loose coupling and polymorphism.

(b) Access modifiers

Access modifiers control the visibility of classes, fields, methods and constructors.

  • public: visible everywhere.
  • protected: visible in the same package and in subclasses.
  • default (no keyword): visible only in the same package.
  • private: visible only inside the declaring class.
class Account {
    private double balance;                  // hidden
    public void deposit(double a) { balance += a; }
    public double getBalance() { return balance; }
}

They enforce encapsulation by hiding internal data and exposing only a controlled interface.

(c) JDBC

JDBC (Java Database Connectivity) is a Java API (package java.sql) used to connect to relational databases and run SQL. Main steps: load the driver, get a Connection with DriverManager.getConnection(url, user, pass), create a Statement or PreparedStatement, execute a query to get a ResultSet, process results, and close the connection.

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root", "");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM student");
while (rs.next()) System.out.println(rs.getInt(1) + " " + rs.getString(2));
con.close();

(Any two of the three are required.)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 10 marks

a) Define inheritance. Explain the use of "extends" keyword in java.
b) What is an abstract class? Explain its use with an example.

Answer

(a) Inheritance and the extends keyword

Inheritance is the OOP mechanism by which one class (the subclass or child) acquires the fields and methods of another class (the superclass or parent). It models an "is-a" relationship and provides code reuse, method overriding (run-time polymorphism) and a natural class hierarchy.

The extends keyword declares that a class inherits from another:

class Subclass extends Superclass { ... }

Points about extends:

  • A Java class can extend only one class (no multiple inheritance of classes).
  • The subclass inherits non-private members; constructors are not inherited, but super(...) calls the parent constructor.
  • The subclass may add new members and override inherited methods.
  • Interfaces use extends to extend other interfaces; a class uses implements for interfaces.
  • Types of inheritance in Java: single, multilevel and hierarchical (multiple only through interfaces).
class Person {
    String name;
    void display() { System.out.println("Name: " + name); }
}
class Student extends Person {
    int roll;
    void show() {
        display();                         // inherited method
        System.out.println("Roll: " + roll);
    }
}
public class Main {
    public static void main(String[] args) {
        Student s = new Student();
        s.name = "Ram";
        s.roll = 5;
        s.show();
    }
}

(b) Abstract class

An abstract class is declared with the keyword abstract. It cannot be instantiated and may contain abstract methods (declared without a body) and ordinary methods, fields and constructors. A subclass must implement all abstract methods or itself be declared abstract.

Use: it provides a common base with shared code and forces subclasses to supply specific behaviour, achieving abstraction.

abstract class Shape {
    String color = "Red";
    abstract double area();                    // must be implemented
    void showColor() { System.out.println("Color: " + color); }
}
class Rectangle extends Shape {
    double l, w;
    Rectangle(double l, double w) { this.l = l; this.w = w; }
    double area() { return l * w; }
}
class Circle extends Shape {
    double r;
    Circle(double r) { this.r = r; }
    double area() { return Math.PI * r * r; }
}
public class Test {
    public static void main(String[] args) {
        Shape s = new Rectangle(4, 5);
        s.showColor();
        System.out.println("Area = " + s.area());   // 20.0
        s = new Circle(1);
        System.out.println("Area = " + s.area());   // 3.14159...
    }
}

new Shape() would be a compile-time error, but the reference Shape s can hold any subclass object, giving run-time polymorphism.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 10 marks

a) List and explain any five String methods used in Java with examples.
b) Differentiate between byte stream and character stream. Write a program to copy the content of a file to another file using streams.

Answer

(a) Five String methods

A String in Java is an immutable sequence of characters. Common methods:

  1. length() returns the number of characters. "Nepal".length() gives 5.
  2. charAt(int index) returns the character at the index. "Nepal".charAt(1) gives 'e'.
  3. substring(int begin, int end) returns the part from begin up to end-1. "Kathmandu".substring(0, 4) gives "Kath".
  4. toUpperCase() / toLowerCase() change case. "java".toUpperCase() gives "JAVA".
  5. equals(String s) compares content (case-sensitive). "abc".equals("abc") gives true. (equalsIgnoreCase ignores case.)
  6. indexOf(String s) returns the first position of s, or -1. "banana".indexOf("na") gives 2.
  7. replace(old, new) replaces characters. "hello".replace('l','p') gives "heppo".
String s = "Education Nepal";
System.out.println(s.length());          // 15
System.out.println(s.charAt(0));         // E
System.out.println(s.substring(10));     // Nepal
System.out.println(s.toUpperCase());     // EDUCATION NEPAL
System.out.println(s.indexOf("Nepal"));  // 10

(b) Byte stream versus character stream

BasisByte streamCharacter stream
Unit of data8-bit bytes16-bit Unicode characters
Base classesInputStream, OutputStreamReader, Writer
ExamplesFileInputStream, FileOutputStreamFileReader, FileWriter
Best forBinary data (images, audio, video)Text data
EncodingNoneHandles character encoding

Program to copy a file using streams

import java.io.*;

public class FileCopy {
    public static void main(String[] args) {
        try (FileInputStream in = new FileInputStream("source.txt");
             FileOutputStream out = new FileOutputStream("destination.txt")) {
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            System.out.println("File copied successfully");
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

The try-with-resources statement closes both streams automatically. Using FileReader and FileWriter instead would copy the text through character streams.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2021 · 10 marks

a) Create the following GUI form in Java that checks a number entered in the text box is even or odd.
b) Differentiate AWT with swing. Explain any two layout management in Java.

Answer

(a) GUI form that checks whether a number is even or odd

The form has a label, a text field, a "Check" button and a result label.

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

public class EvenOddForm extends JFrame implements ActionListener {
    JLabel lbl, result;
    JTextField txt;
    JButton btn;

    EvenOddForm() {
        setTitle("Even or Odd");
        setLayout(new FlowLayout());
        lbl = new JLabel("Enter a number:");
        txt = new JTextField(10);
        btn = new JButton("Check");
        result = new JLabel("");
        add(lbl);
        add(txt);
        add(btn);
        add(result);
        btn.addActionListener(this);
        setSize(300, 150);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        try {
            int n = Integer.parseInt(txt.getText().trim());
            if (n % 2 == 0)
                result.setText(n + " is Even");
            else
                result.setText(n + " is Odd");
        } catch (NumberFormatException ex) {
            result.setText("Please enter a valid integer");
        }
    }

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

(b) AWT versus Swing

BasisAWTSwing
Packagejava.awtjavax.swing
ComponentsHeavyweight, depend on native OSLightweight, pure Java
Look and feelPlatform dependentPluggable, platform independent
ComponentsFewer (Button, Label)More (JButton, JTable, JTree)
ArchitectureNot MVCMVC based

Two layout managers

  1. FlowLayout places components one after another from left to right, wrapping to a new row when the row is full. Components keep their preferred size. It is the default for panels.
setLayout(new FlowLayout(FlowLayout.CENTER));
  1. BorderLayout divides the container into five regions: NORTH, SOUTH, EAST, WEST and CENTER. Each region holds one component, and CENTER takes the remaining space. It is the default for frames.
add(new JButton("Top"), BorderLayout.NORTH);
add(new JButton("Middle"), BorderLayout.CENTER);

(GridLayout, which arranges components in equal-sized rows and columns, is another common layout.)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What is jagged array? Write a java program to initialize and display jagged array element with sum of each row.

Answer

A jagged array is a two-dimensional array in which each row can have a different length. In Java a 2D array is an array of arrays, so only the number of rows is fixed first and each row is allocated separately.

int[][] a = new int[3][];   // 3 rows, columns not yet defined
a[0] = new int[2];
a[1] = new int[4];
a[2] = new int[3];

Program

public class JaggedArray {
    public static void main(String[] args) {
        int[][] jag = {
            {1, 2},
            {3, 4, 5, 6},
            {7, 8, 9}
        };

        for (int i = 0; i < jag.length; i++) {
            int sum = 0;
            for (int j = 0; j < jag[i].length; j++) {
                System.out.print(jag[i][j] + " ");
                sum += jag[i][j];
            }
            System.out.println("  -> Sum of row " + (i + 1) + " = " + sum);
        }
    }
}

Output:

1 2   -> Sum of row 1 = 3
3 4 5 6   -> Sum of row 2 = 18
7 8 9   -> Sum of row 3 = 24

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What are uses of this keyword? Write a java program to implement method overloading concept.

Answer

Uses of the this keyword

this refers to the current object. It is used to:

  1. Distinguish instance variables from local variables or parameters with the same name (this.x = x;).
  2. Invoke another constructor of the same class (this(...)), as the first statement.
  3. Invoke a method of the current object (this.show();).
  4. Pass the current object as an argument to another method or constructor.
  5. Return the current object from a method (return this;), which allows method chaining.

Program for method overloading

class Calculator {
    int a, b;

    Calculator(int a, int b) {
        this.a = a;                 // use of this
        this.b = b;
    }

    int add(int x, int y) { return x + y; }
    int add(int x, int y, int z) { return x + y + z; }
    double add(double x, double y) { return x + y; }
    int add() { return this.a + this.b; }     // uses fields via this
}

public class OverloadDemo {
    public static void main(String[] args) {
        Calculator c = new Calculator(10, 20);
        System.out.println(c.add(2, 3));         // 5
        System.out.println(c.add(2, 3, 4));      // 9
        System.out.println(c.add(1.5, 2.5));     // 4.0
        System.out.println(c.add());             // 30
    }
}

The compiler picks the version of add that matches the number and types of the arguments.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

Why inheritance is needed in java? How will you implement multiple inheritance using interface? Explain with program.

Answer

Need for inheritance

Inheritance is needed because it:

  • Promotes code reuse: common fields and methods are written once in the superclass.
  • Supports method overriding, giving run-time polymorphism.
  • Models real-world "is-a" hierarchies (Student is a Person).
  • Makes programs easier to extend and maintain, since changes in the parent propagate to children.

Multiple inheritance using interfaces

Java does not allow a class to extend more than one class, because it could cause ambiguity (the diamond problem). However, a class can implement any number of interfaces, so multiple inheritance of type is achieved through interfaces.

interface Printable {
    void print();
}
interface Showable {
    void show();
}
class Document implements Printable, Showable {
    public void print() { System.out.println("Printing document"); }
    public void show() { System.out.println("Showing document"); }
}
public class MultipleInheritance {
    public static void main(String[] args) {
        Document d = new Document();
        d.print();
        d.show();
    }
}

Document inherits the abstract behaviours of both Printable and Showable and must implement both methods. Since interfaces carry no state or implementation conflicts (a class must override a clashing default method), there is no ambiguity.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What is multithreading? Explain with program how you will create thread by implementing runnable interface and extending Thread class.

Answer

Multithreading is the ability of a program to run two or more threads concurrently, each executing a separate path of code within the same process. It makes better use of the CPU, improves responsiveness and lets tasks run in parallel (for example downloading while updating the UI). Threads share the same memory.

There are two ways to create a thread in Java.

1. Extending the Thread class: override run() and call start().

class MyThread extends Thread {
    public void run() {
        for (int i = 1; i <= 3; i++) {
            System.out.println("Thread class: " + i);
            try { Thread.sleep(300); } catch (InterruptedException e) { }
        }
    }
}

2. Implementing the Runnable interface: implement run(), wrap the object in a Thread and call start(). This is preferred because the class can still extend another class.

class MyRunnable implements Runnable {
    public void run() {
        for (int i = 1; i <= 3; i++) {
            System.out.println("Runnable: " + i);
            try { Thread.sleep(300); } catch (InterruptedException e) { }
        }
    }
}

Main program

public class ThreadDemo {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        Thread t2 = new Thread(new MyRunnable());
        t1.start();      // not run(): start() creates a new thread
        t2.start();
    }
}

Both threads run concurrently, so their output lines interleave. Calling run() directly would execute it in the main thread without creating a new one.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What are exception handling keyword in java? Write java program to illustrate the concept of NullPointerException and NumberFormatException.

Answer

Exception handling keywords

  • try: block containing code that may throw an exception.
  • catch: block that handles a particular exception thrown in try.
  • finally: block that always executes, used for cleanup.
  • throw: explicitly throws an exception object.
  • throws: declares in a method signature the exceptions it may pass to the caller.

Program

public class ExceptionDemo {
    public static void main(String[] args) {
        // NullPointerException
        try {
            String s = null;
            System.out.println(s.length());      // s is null
        } catch (NullPointerException e) {
            System.out.println("NullPointerException caught: " + e.getMessage());
        } finally {
            System.out.println("First try finished");
        }

        // NumberFormatException
        try {
            String num = "12abc";
            int n = Integer.parseInt(num);       // not a valid integer
            System.out.println(n);
        } catch (NumberFormatException e) {
            System.out.println("NumberFormatException caught: " + e.getMessage());
        } finally {
            System.out.println("Second try finished");
        }
    }
}

The first block fails because a method is called on a null reference; the second fails because the string "12abc" cannot be converted to an integer (message: For input string: "12abc"). Each exception is caught and the program continues normally.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What is serialization? Write a java program to write three student information (Roll, Name, Address, College) into file student.txt and display the student information whose address is Jhapa.

Answer

Serialization is the process of converting the state of an object into a byte stream so that it can be saved to a file, stored in a database or sent over a network. The reverse process, rebuilding the object from the stream, is deserialization. A class must implement the marker interface java.io.Serializable; fields marked transient are not serialized. ObjectOutputStream writes objects and ObjectInputStream reads them.

Program

import java.io.*;

class Student implements Serializable {
    private static final long serialVersionUID = 1L;
    int roll;
    String name, address, college;

    Student(int roll, String name, String address, String college) {
        this.roll = roll;
        this.name = name;
        this.address = address;
        this.college = college;
    }
}

public class SerializeDemo {
    public static void main(String[] args) {
        Student[] list = {
            new Student(1, "Ram", "Jhapa", "Mechi College"),
            new Student(2, "Sita", "Kathmandu", "Patan College"),
            new Student(3, "Hari", "Jhapa", "Damak College")
        };

        // write objects
        try (ObjectOutputStream out =
                 new ObjectOutputStream(new FileOutputStream("student.txt"))) {
            for (Student s : list) out.writeObject(s);
        } catch (IOException e) {
            System.out.println("Write error: " + e.getMessage());
        }

        // read objects and display those from Jhapa
        try (ObjectInputStream in =
                 new ObjectInputStream(new FileInputStream("student.txt"))) {
            for (int i = 0; i < 3; i++) {
                Student s = (Student) in.readObject();
                if (s.address.equals("Jhapa")) {
                    System.out.println(s.roll + " " + s.name + " " + s.address + " " + s.college);
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("Read error: " + e.getMessage());
        }
    }
}

Output:

1 Ram Jhapa Mechi College
3 Hari Jhapa Damak College

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 5 marks

What is Wrapper class? Explain with program, how will you use iterator and comparator in collection objects?

Answer

Wrapper class

A wrapper class wraps a primitive value inside an object. Java provides one for every primitive type: Byte, Short, Integer, Long, Float, Double, Character and Boolean. They are needed because collections such as ArrayList and HashSet store only objects, not primitives. Wrapper classes also provide utility methods such as parseInt(), valueOf(), intValue(), compare() and constants such as Integer.MAX_VALUE.

  • Boxing: primitive to object (Integer a = Integer.valueOf(10);).
  • Unboxing: object to primitive (int b = a.intValue();).
  • Since Java 5, autoboxing and auto-unboxing do this automatically.

Iterator and Comparator with collections

  • Iterator is used to traverse a collection one element at a time using hasNext(), next() and remove().
  • Comparator is an interface with compare(T a, T b). It defines a custom ordering and is passed to Collections.sort(), TreeSet or TreeMap.
import java.util.*;

public class WrapperDemo {
    public static void main(String[] args) {
        // Wrapper class: boxing and unboxing
        int p = 25;
        Integer boxed = Integer.valueOf(p);      // boxing
        int unboxed = boxed.intValue();          // unboxing
        Integer auto = p;                        // autoboxing
        int num = Integer.parseInt("100");       // String -> int
        System.out.println(boxed + " " + unboxed + " " + auto + " " + num);

        // Collection stores wrapper objects
        List<Integer> list = new ArrayList<>();
        list.add(40);
        list.add(10);
        list.add(30);
        list.add(20);

        // Iterator
        Iterator<Integer> it = list.iterator();
        while (it.hasNext()) {
            int v = it.next();
            if (v == 30) it.remove();            // safe removal
            else System.out.print(v + " ");
        }
        System.out.println();

        // Comparator: descending order
        Comparator<Integer> desc = new Comparator<Integer>() {
            public int compare(Integer a, Integer b) {
                return b.compareTo(a);
            }
        };
        Collections.sort(list, desc);
        System.out.println("Descending: " + list);
    }
}

Output:

25 25 25 100
40 10 20 
Descending: [40, 20, 10]

The iterator removes 30 safely during traversal, and the comparator sorts the remaining wrapper objects in descending order.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 10 marks

What is difference between class and interface in java? Create a java class Time with three attribute hours, minutes and seconds. Use appropriate constructors to initialize instance variable. Use methods to display time in HH:MM:SS format, add and subtract two time object. Implement the class to add, subtract and display time object.

Answer

Difference between class and interface

ClassInterface
Declared with class.Declared with interface.
Can have concrete methods, instance variables and constructors.Has abstract methods (plus default, static methods since Java 8); variables are public static final.
Can be instantiated with new.Cannot be instantiated.
A class extends only one class.A class can implement many interfaces.
Members can have any access modifier.Methods are implicitly public.
Used to define state and behaviour of objects.Used to define a contract and achieve full abstraction and multiple inheritance of type.

Time class

class Time {
    private int hours, minutes, seconds;

    Time() { this(0, 0, 0); }

    Time(int h, int m, int s) {
        long total = (long) h * 3600 + m * 60 + s;
        setFromSeconds(total);
    }

    private void setFromSeconds(long total) {
        hours = (int) (total / 3600);
        minutes = (int) ((total % 3600) / 60);
        seconds = (int) (total % 60);
    }

    int toSeconds() { return hours * 3600 + minutes * 60 + seconds; }

    Time add(Time t) {
        return new Time(0, 0, this.toSeconds() + t.toSeconds());
    }

    Time subtract(Time t) {
        int diff = this.toSeconds() - t.toSeconds();
        if (diff < 0) diff = -diff;          // absolute difference
        return new Time(0, 0, diff);
    }

    void display() {
        System.out.printf("%02d:%02d:%02d%n", hours, minutes, seconds);
    }
}

public class TimeTest {
    public static void main(String[] args) {
        Time t1 = new Time(2, 45, 50);
        Time t2 = new Time(1, 30, 40);

        System.out.print("Time 1: "); t1.display();
        System.out.print("Time 2: "); t2.display();

        System.out.print("Sum: ");        t1.add(t2).display();
        System.out.print("Difference: "); t1.subtract(t2).display();
    }
}

Output:

Time 1: 02:45:50
Time 2: 01:30:40
Sum: 04:16:30
Difference: 01:15:10

Check: 2:45:50+1:30:40=3:75:90=4:16:302{:}45{:}50 + 1{:}30{:}40 = 3{:}75{:}90 = 4{:}16{:}30, and 2:45:50−1:30:40=1:15:102{:}45{:}50 - 1{:}30{:}40 = 1{:}15{:}10.

The constructor converts everything to total seconds so that overflow of seconds and minutes is normalised automatically.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 10 marks

How AWT is differing from Swing? Write a GUI program using components to find factorial and cube of number. Use TextField for giving input and Label for output. The program should display factorial if user press mouse on result button and cube if user release mouse from result button.

Answer

AWT versus Swing

AWTSwing
Heavyweight: components use native OS peers.Lightweight: components are drawn by Java itself.
Look and feel depends on the platform.Pluggable look and feel, platform independent.
Package java.awt.Package javax.swing (built on AWT).
Fewer components (Button, Label, TextField).Richer components (JTable, JTree, JTabbedPane, etc.).
Does not follow MVC.Follows a modified MVC design.
Slower and less flexible.Faster, more flexible, supports icons and tooltips.

Program (AWT, uses MouseListener on the result button)

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

public class FactCube extends Frame implements MouseListener {
    TextField tf;
    Label result;
    Button btn;

    FactCube() {
        setLayout(new FlowLayout());
        tf = new TextField(10);
        btn = new Button("Result");
        result = new Label("                                   ");
        add(new Label("Enter number:"));
        add(tf);
        add(btn);
        add(result);

        btn.addMouseListener(this);

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) { dispose(); }
        });
        setSize(300, 150);
        setVisible(true);
    }

    public void mousePressed(MouseEvent e) {          // factorial
        try {
            int n = Integer.parseInt(tf.getText().trim());
            long f = 1;
            for (int i = 2; i <= n; i++) f *= i;
            result.setText("Factorial = " + f);
        } catch (NumberFormatException ex) {
            result.setText("Invalid input");
        }
    }

    public void mouseReleased(MouseEvent e) {         // cube
        try {
            int n = Integer.parseInt(tf.getText().trim());
            result.setText("Cube = " + (long) n * n * n);
        } catch (NumberFormatException ex) {
            result.setText("Invalid input");
        }
    }

    public void mouseClicked(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) { }
    public void mouseExited(MouseEvent e) { }

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

When the mouse button is pressed on the button, mousePressed() shows the factorial. When it is released, mouseReleased() replaces it with the cube. For input 5, pressing shows 120 and releasing shows 125.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2022 · 10 marks

What is JDBC? Write a java program to connect database Company and insert 5 employee record (EID, Ename, Salary, Department) in Employee table and display the employee record who's Department is "Sales".

Answer

JDBC

JDBC (Java Database Connectivity) is a Java API (package java.sql) that lets Java programs connect to relational databases, send SQL statements and process the results. Its main parts are DriverManager, Connection, Statement/PreparedStatement, and ResultSet. A database specific JDBC driver translates the calls into the database's protocol.

Steps: load the driver, create a connection, create a statement, execute the query, process the ResultSet, close the resources.

Program (MySQL, database Company, table Employee(EID, Ename, Salary, Department))

import java.sql.*;

public class EmployeeDemo {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/Company";
        String user = "root", pass = "";

        String sql = "INSERT INTO Employee(EID, Ename, Salary, Department) VALUES (?,?,?,?)";
        Object[][] data = {
            {1, "Ram",   45000.0, "Sales"},
            {2, "Sita",  52000.0, "HR"},
            {3, "Hari",  38000.0, "Sales"},
            {4, "Gita",  60000.0, "IT"},
            {5, "Shyam", 41000.0, "Sales"}
        };

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            try (Connection con = DriverManager.getConnection(url, user, pass)) {

                try (PreparedStatement ps = con.prepareStatement(sql)) {
                    for (Object[] r : data) {
                        ps.setInt(1, (Integer) r[0]);
                        ps.setString(2, (String) r[1]);
                        ps.setDouble(3, (Double) r[2]);
                        ps.setString(4, (String) r[3]);
                        ps.executeUpdate();
                    }
                }
                System.out.println("5 records inserted.");

                String q = "SELECT * FROM Employee WHERE Department = ?";
                try (PreparedStatement ps = con.prepareStatement(q)) {
                    ps.setString(1, "Sales");
                    try (ResultSet rs = ps.executeQuery()) {
                        System.out.println("EID\tEname\tSalary\tDepartment");
                        while (rs.next()) {
                            System.out.println(rs.getInt("EID") + "\t"
                                + rs.getString("Ename") + "\t"
                                + rs.getDouble("Salary") + "\t"
                                + rs.getString("Department"));
                        }
                    }
                }
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}

The program inserts the five rows using a PreparedStatement and then selects only the rows with Department "Sales" (Ram, Hari and Shyam). The try-with-resources blocks close the connection automatically.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What is java Buzzwords? Write a java program to find simple interest. Use command line argument to take input.

Answer

Java buzzwords

Java buzzwords are the key features that describe the language:

  • Simple: syntax is similar to C/C++ but without pointers, operator overloading and manual memory management.
  • Object-oriented: everything is organised in classes and objects; supports encapsulation, inheritance and polymorphism.
  • Platform independent / portable: source compiles to bytecode that runs on any JVM ("write once, run anywhere").
  • Robust: strong type checking, exception handling and automatic garbage collection.
  • Secure: no explicit pointers, bytecode verifier and security manager.
  • Multithreaded: built-in thread support.
  • Architecture neutral: bytecode does not depend on the hardware.
  • Interpreted and high performance: bytecode is interpreted, with JIT compilation for speed.
  • Distributed: supports networking, RMI and URLs.
  • Dynamic: classes are loaded at run time.

Simple interest using command line arguments

SI=P×T×R100SI = \frac{P \times T \times R}{100}

public class SimpleInterest {
    public static void main(String[] args) {
        if (args.length != 3) {
            System.out.println("Usage: java SimpleInterest <principal> <time> <rate>");
            return;
        }
        double p = Double.parseDouble(args[0]);
        double t = Double.parseDouble(args[1]);
        double r = Double.parseDouble(args[2]);
        double si = (p * t * r) / 100;
        System.out.println("Simple Interest = " + si);
    }
}

Running java SimpleInterest 10000 2 5 prints Simple Interest = 1000.0, since 10000×2×5100=1000\frac{10000 \times 2 \times 5}{100} = 1000.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What are uses of super keyword? Write a java program to create base class Fruit which has name, taste and size as its attributes and method called eat() which describe name and its taste. Inherit the same in two other class Apple and Orange and override the eat() method to represent each fruit taste.

Answer

Uses of the super keyword

  1. Call the parent class constructor: super(args); must be the first statement in the subclass constructor.
  2. Access a parent class member hidden by the subclass: super.variableName.
  3. Call an overridden parent method: super.methodName();.
class Fruit {
    String name, taste, size;

    Fruit(String name, String taste, String size) {
        this.name = name;
        this.taste = taste;
        this.size = size;
    }

    void eat() {
        System.out.println("This is a " + name + " and its taste is " + taste);
    }
}

class Apple extends Fruit {
    Apple() {
        super("Apple", "sweet", "medium");   // parent constructor
    }

    @Override
    void eat() {
        super.eat();                          // parent method
        System.out.println("Apple tastes sweet and crunchy.");
    }
}

class Orange extends Fruit {
    Orange() {
        super("Orange", "sour-sweet", "small");
    }

    @Override
    void eat() {
        System.out.println("Orange tastes sour-sweet and juicy.");
    }
}

public class FruitTest {
    public static void main(String[] args) {
        Fruit f1 = new Apple();
        Fruit f2 = new Orange();
        f1.eat();
        f2.eat();
    }
}

Output:

This is a Apple and its taste is sweet
Apple tastes sweet and crunchy.
Orange tastes sour-sweet and juicy.

Both subclasses override eat(), and the call through a Fruit reference runs the version of the actual object (runtime polymorphism).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What is difference between String and StringBuffer class? Write a java program to identify the input string is palindrome or not?

Answer

Difference between String and StringBuffer

StringStringBuffer
Immutable: content cannot change after creation.Mutable: content can be modified in place.
Every modification creates a new object.Modification uses the same object (append, insert, delete, reverse).
Slower for repeated modification.Faster for repeated modification.
Thread safety is not an issue (immutable).Methods are synchronized, so thread safe.
Can be created with a literal ("abc") and uses the string pool.Created only with new.
equals() compares content.equals() is not overridden (compares references).

Palindrome program

import java.util.Scanner;

public class PalindromeCheck {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String s = sc.nextLine();

        String cleaned = s.replaceAll("\\s+", "").toLowerCase();
        String rev = new StringBuffer(cleaned).reverse().toString();

        if (cleaned.equals(rev))
            System.out.println(s + " is a palindrome.");
        else
            System.out.println(s + " is not a palindrome.");
        sc.close();
    }
}

For "Madam" the cleaned string is madam, its reverse is madam, so it is a palindrome. For "hello" the reverse is olleh, so it is not.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

Why we need file handling in java? Write java program to read file into a variable and then write a variable's content into another file.

Answer

Need for file handling

Variables and objects live in RAM and are lost when the program ends. File handling lets a program:

  • store data permanently on disk and read it back later,
  • exchange data between programs and with other systems,
  • handle large data that does not fit in memory,
  • keep logs, configuration and reports.

Java provides the java.io package (File, FileReader, FileWriter, FileInputStream, FileOutputStream, BufferedReader) and java.nio.file.

Program: read a file into a variable, write it to another file

import java.io.*;

public class FileCopy {
    public static void main(String[] args) {
        StringBuilder content = new StringBuilder();

        try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                content.append(line).append(System.lineSeparator());
            }
        } catch (IOException e) {
            System.out.println("Read error: " + e.getMessage());
            return;
        }

        String data = content.toString();        // file content in a variable

        try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
            bw.write(data);
        } catch (IOException e) {
            System.out.println("Write error: " + e.getMessage());
            return;
        }
        System.out.println("File copied successfully.");
    }
}

The content of input.txt is read line by line into the variable data, and that variable is then written to output.txt. The try-with-resources statement closes both files automatically.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What is the purpose of valueof() method in Wrapper classes? Write a java program to generate random integer, double and bytes.

Answer

Purpose of valueOf() in wrapper classes

valueOf() is a static method of the wrapper classes (Integer, Double, Byte, Boolean and so on). It converts a primitive value or a String into the corresponding wrapper object, for example Integer.valueOf(5), Integer.valueOf("25"), Double.valueOf("3.14").

  • It is the standard way to box a primitive (autoboxing calls it internally).
  • It may reuse cached objects (for Integer, values from -128 to 127), saving memory, unlike new Integer(...), which is deprecated.
  • It differs from parseInt(), which returns a primitive int, whereas valueOf() returns an Integer object.

Random integer, double and bytes

import java.util.Random;

public class RandomDemo {
    public static void main(String[] args) {
        Random rand = new Random();

        int i = rand.nextInt(100);          // 0 to 99
        double d = rand.nextDouble();       // 0.0 to 1.0
        byte[] bytes = new byte[5];
        rand.nextBytes(bytes);              // fills array with random bytes

        System.out.println("Random int    : " + Integer.valueOf(i));
        System.out.println("Random double : " + Double.valueOf(d));
        System.out.print("Random bytes  : ");
        for (byte b : bytes) System.out.print(Byte.valueOf(b) + " ");
        System.out.println();
    }
}

nextInt(100) gives an integer in the range 0-99, nextDouble() gives a value in [0,1)[0, 1), and nextBytes() fills the byte array with values from -128 to 127. The values change on every run.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What is internal frames? Write a java program that display two internal frame within some parent frame.

Answer

Internal frames

An internal frame is a JInternalFrame, a lightweight window that lives inside another container, usually a JDesktopPane placed in a parent JFrame. It behaves like a normal window (it can be resized, dragged, minimised, maximised and closed) but cannot leave its parent frame. It is used to build MDI (multiple document interface) applications.

Program

import javax.swing.*;

public class InternalFrameDemo extends JFrame {
    InternalFrameDemo() {
        super("Parent Frame");
        JDesktopPane desktop = new JDesktopPane();

        JInternalFrame f1 = new JInternalFrame("Internal Frame 1", true, true, true, true);
        f1.add(new JLabel("This is the first internal frame"));
        f1.setBounds(20, 20, 250, 150);
        f1.setVisible(true);

        JInternalFrame f2 = new JInternalFrame("Internal Frame 2", true, true, true, true);
        f2.add(new JLabel("This is the second internal frame"));
        f2.setBounds(150, 100, 250, 150);
        f2.setVisible(true);

        desktop.add(f1);
        desktop.add(f2);
        add(desktop);

        setSize(500, 350);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(InternalFrameDemo::new);
    }
}

The four boolean arguments make each internal frame resizable, closable, maximizable and iconifiable. Both frames are added to the JDesktopPane, which is added to the parent JFrame.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 5 marks

What is JDBC? Write java program to connect database College and display all student information (Roll, Name, Address and Program) from Student table.

Answer

JDBC

JDBC (Java Database Connectivity) is the Java API in package java.sql for connecting to relational databases, executing SQL and processing results. A database specific driver is used through DriverManager, giving a Connection; a Statement runs the query and a ResultSet holds the rows returned.

Program (MySQL, database College, table Student(Roll, Name, Address, Program))

import java.sql.*;

public class StudentDisplay {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/College";
        String user = "root", pass = "";

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            try (Connection con = DriverManager.getConnection(url, user, pass);
                 Statement st = con.createStatement();
                 ResultSet rs = st.executeQuery("SELECT Roll, Name, Address, Program FROM Student")) {

                System.out.println("Roll\tName\tAddress\tProgram");
                while (rs.next()) {
                    System.out.println(rs.getInt("Roll") + "\t"
                        + rs.getString("Name") + "\t"
                        + rs.getString("Address") + "\t"
                        + rs.getString("Program"));
                }
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}

The loop while (rs.next()) moves through each row of the result set and prints its four columns. Resources are closed automatically by try-with-resources.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 10 marks

What is Constructor overloading? Write a class Distance containing private variable feet of type int and inches of type int, suitable constructors and three methods addDistance, subtractDistance and displayDistance for adding, subtracting and displaying objects. Write a separate class MyDistance containing main method to create, add, subtract and display distance objects.

Answer

Constructor overloading

Constructor overloading means defining more than one constructor in the same class with different parameter lists (number, type or order of parameters). The compiler selects the constructor that matches the arguments given to new. It allows objects to be initialised in different ways, for example new Distance(), new Distance(5) and new Distance(5, 8).

Distance class

class Distance {
    private int feet;
    private int inches;

    Distance() {                 // default
        feet = 0;
        inches = 0;
    }

    Distance(int feet, int inches) {   // parameterised
        this.feet = feet;
        this.inches = inches;
        normalize();
    }

    Distance(int feet) {         // overloaded
        this(feet, 0);
    }

    private void normalize() {
        int total = feet * 12 + inches;
        feet = total / 12;
        inches = total % 12;
    }

    Distance addDistance(Distance d) {
        int total = (feet + d.feet) * 12 + inches + d.inches;
        return new Distance(0, total);
    }

    Distance subtractDistance(Distance d) {
        int total = (feet * 12 + inches) - (d.feet * 12 + d.inches);
        if (total < 0) total = -total;
        return new Distance(0, total);
    }

    void displayDistance() {
        System.out.println(feet + " feet " + inches + " inches");
    }
}

public class MyDistance {
    public static void main(String[] args) {
        Distance d1 = new Distance(5, 8);
        Distance d2 = new Distance(3, 7);

        System.out.print("Distance 1: "); d1.displayDistance();
        System.out.print("Distance 2: "); d2.displayDistance();

        System.out.print("Sum: ");        d1.addDistance(d2).displayDistance();
        System.out.print("Difference: "); d1.subtractDistance(d2).displayDistance();
    }
}

Output:

Distance 1: 5 feet 8 inches
Distance 2: 3 feet 7 inches
Sum: 9 feet 3 inches
Difference: 2 feet 1 inches

Check: 5′8′′+3′7′′=8′15′′=9′3′′5'8'' + 3'7'' = 8'15'' = 9'3'', and 68−43=2568 - 43 = 25 inches =2′1′′= 2'1''.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 10 marks

a) What is difference between checked and unchecked exception? Write a java program that will read college name from keyboard and display it on screen. The program should throw an exception when length of college name is more than 50. b) What are methods used for inter-thread communication? Write a java program to create two threads so that one thread prints even number and other thread prints odd number between 100 and 200.

Answer

(a) Checked and unchecked exceptions

Checked exceptionUnchecked exception
Subclass of Exception but not of RuntimeException.Subclass of RuntimeException (or Error).
Checked by the compiler at compile time.Not checked at compile time; occurs at run time.
Must be caught or declared with throws.Handling is optional.
Caused by external conditions.Usually caused by programming errors.
Examples: IOException, SQLException, ClassNotFoundException.Examples: NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException.

College name program with a custom exception

import java.util.Scanner;

class CollegeNameException extends Exception {
    CollegeNameException(String msg) { super(msg); }
}

public class CollegeName {
    static void check(String name) throws CollegeNameException {
        if (name.length() > 50)
            throw new CollegeNameException("College name is longer than 50 characters");
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter college name: ");
        String name = sc.nextLine();
        try {
            check(name);
            System.out.println("College name: " + name);
        } catch (CollegeNameException e) {
            System.out.println("Exception: " + e.getMessage());
        }
        sc.close();
    }
}

(b) Inter-thread communication

Threads communicate with the methods of class Object, which must be called inside a synchronized block or method:

  • wait(): makes the current thread release the lock and wait until notified.
  • notify(): wakes one thread waiting on the object.
  • notifyAll(): wakes all threads waiting on the object.

Program: one thread prints even and the other odd numbers between 100 and 200

The two threads alternate using wait() and notify().

class Printer {
    private boolean evenTurn = true;

    synchronized void printEven(int n) throws InterruptedException {
        while (!evenTurn) wait();
        System.out.println("Even Thread: " + n);
        evenTurn = false;
        notify();
    }

    synchronized void printOdd(int n) throws InterruptedException {
        while (evenTurn) wait();
        System.out.println("Odd Thread : " + n);
        evenTurn = true;
        notify();
    }
}

public class EvenOdd {
    public static void main(String[] args) {
        Printer p = new Printer();

        Thread even = new Thread(() -> {
            try {
                for (int i = 100; i <= 200; i += 2) p.printEven(i);
            } catch (InterruptedException e) { }
        });

        Thread odd = new Thread(() -> {
            try {
                for (int i = 101; i <= 199; i += 2) p.printOdd(i);
            } catch (InterruptedException e) { }
        });

        even.start();
        odd.start();
    }
}

The even thread prints 100, 102, ..., 200 (51 numbers) and the odd thread prints 101, ..., 199 (50 numbers). Because the even thread prints first and last, the output alternates 100, 101, 102, ..., 199, 200 and both threads finish without blocking.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2023 · 10 marks

What is MVC design pattern? Write a GUI program using swing components to calculate sum and difference of two numbers. Use two text fields for input and pre-built dialog box for output. Your program should display sum if Add button and difference if subtract button is clicked.

Answer

MVC design pattern

Model-View-Controller separates an application into three parts:

  • Model: holds the data and business logic (for example the numbers and the add/subtract calculation).
  • View: the user interface that displays the data (text fields, buttons, dialogs).
  • Controller: receives user input from the view (events), updates the model and refreshes the view.

This separation makes code easier to maintain, test and reuse. Swing components follow a variant of MVC, with the model and the view/controller combined in a UI delegate.

Program

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

public class SumDiff extends JFrame implements ActionListener {
    JTextField t1, t2;
    JButton add, sub;

    SumDiff() {
        setTitle("Sum and Difference");
        setLayout(new FlowLayout());

        t1 = new JTextField(8);
        t2 = new JTextField(8);
        add = new JButton("Add");
        sub = new JButton("Subtract");

        add(new JLabel("First number:"));
        add(t1);
        add(new JLabel("Second number:"));
        add(t2);
        add(add);
        add(sub);

        add.addActionListener(this);
        sub.addActionListener(this);

        setSize(300, 180);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        try {
            double a = Double.parseDouble(t1.getText().trim());
            double b = Double.parseDouble(t2.getText().trim());
            if (e.getSource() == add)
                JOptionPane.showMessageDialog(this, "Sum = " + (a + b));
            else
                JOptionPane.showMessageDialog(this, "Difference = " + (a - b));
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Please enter valid numbers",
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(SumDiff::new);
    }
}

Here the text fields and buttons are the view, the actionPerformed() method acts as the controller, and the numbers with the arithmetic form the model. The output is shown with the pre-built JOptionPane.showMessageDialog(). For inputs 8 and 3, Add shows 11.0 and Subtract shows 5.0.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

What is constructor? Explain the role of constructor in Java class by considering a suitable example and also list the type of constructor.

Answer

Constructor

A constructor is a special method of a class that is called automatically when an object is created with new. It has the same name as the class and no return type. Its role is to initialise the instance variables of the new object so that the object starts in a valid state. If no constructor is written, the compiler supplies a default no-argument constructor.

Types of constructor

  1. Default (no-argument) constructor: takes no parameters; either supplied by the compiler or written by the programmer.
  2. Parameterised constructor: takes arguments to initialise fields with given values.
  3. Copy constructor: takes an object of the same class and copies its values (written by the programmer; Java has no built-in one).

Constructors can be overloaded, and this(...) can call another constructor of the same class.

Example

class Student {
    String name;
    int roll;

    Student() {                          // default
        name = "Unknown";
        roll = 0;
    }

    Student(String name, int roll) {     // parameterised
        this.name = name;
        this.roll = roll;
    }

    Student(Student s) {                 // copy
        this.name = s.name;
        this.roll = s.roll;
    }

    void show() { System.out.println(roll + " " + name); }

    public static void main(String[] args) {
        Student s1 = new Student();
        Student s2 = new Student("Ram", 5);
        Student s3 = new Student(s2);
        s1.show();   // 0 Unknown
        s2.show();   // 5 Ram
        s3.show();   // 5 Ram
    }
}

Each new call runs the constructor whose parameter list matches the arguments, initialising the object.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

Define inheritance. Explain types of inheritance with suitable example.

Answer

Inheritance

Inheritance is the OOP mechanism by which a new class (subclass or child) acquires the fields and methods of an existing class (superclass or parent), using the extends keyword. It promotes code reuse, method overriding and runtime polymorphism, and models an "is-a" relationship.

Types of inheritance

  1. Single: one subclass extends one superclass.
  2. Multilevel: a chain; C extends B, which extends A.
  3. Hierarchical: several subclasses extend the same superclass.
  4. Multiple: one class inherits from more than one class. Java does not support this with classes (to avoid the diamond problem) but achieves it with interfaces.
  5. Hybrid: a combination of the above; in Java possible only through interfaces.
class Animal {                       // superclass
    void eat() { System.out.println("Eating..."); }
}

class Dog extends Animal {           // single inheritance
    void bark() { System.out.println("Barking..."); }
}

class Puppy extends Dog {            // multilevel: Animal -> Dog -> Puppy
    void weep() { System.out.println("Weeping..."); }
}

class Cat extends Animal {           // hierarchical: Dog and Cat both extend Animal
    void meow() { System.out.println("Meowing..."); }
}

interface Printable { void print(); }
interface Showable  { void show(); }

class Demo implements Printable, Showable {   // multiple (through interfaces)
    public void print() { System.out.println("Print"); }
    public void show()  { System.out.println("Show"); }
}

public class InheritanceTest {
    public static void main(String[] args) {
        Puppy p = new Puppy();
        p.eat(); p.bark(); p.weep();     // inherits from Animal and Dog
        new Cat().eat();
        Demo d = new Demo();
        d.print(); d.show();
    }
}

Puppy can use eat() from Animal, bark() from Dog and its own weep(), showing multilevel reuse.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

Define Package. Explain steps in creation and implementation of package with example.

Answer

Package

A package is a named group of related classes, interfaces and sub-packages. It organises code, avoids name conflicts, gives access protection (package-private and protected members) and makes classes easy to locate and reuse. Java has built-in packages (java.lang, java.util, java.io) and user-defined packages.

Steps to create and use a package

  1. Declare the package as the first statement of the source file with package packageName;.
  2. Write the class (make the class and methods public so other packages can use them).
  3. Compile with the -d option so the directory structure is created: javac -d . Calculator.java. This produces mypack/Calculator.class.
  4. In another program, import the package with import mypack.Calculator; (or import mypack.*;).
  5. Compile and run the program with the package on the class path: javac TestPack.java, java TestPack.

Example

File mypack/Calculator.java:

package mypack;

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
    public int multiply(int a, int b) {
        return a * b;
    }
}

File TestPack.java:

import mypack.Calculator;

public class TestPack {
    public static void main(String[] args) {
        Calculator c = new Calculator();
        System.out.println("Sum = " + c.add(10, 20));
        System.out.println("Product = " + c.multiply(10, 20));
    }
}

Output:

Sum = 30
Product = 200

The import statement makes the public class of package mypack available to TestPack.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

What is multithreading? How does Java support inter-thread communication? Explain with example.

Answer

Multithreading

Multithreading is the ability of a program to run two or more threads (independent paths of execution) concurrently within one process. Threads share the same memory but have their own stack and program counter. It improves CPU utilisation and responsiveness. In Java a thread is created by extending Thread or implementing Runnable.

Inter-thread communication

Java supports communication between threads through three methods of the Object class, which must be called from a synchronized block or method:

  • wait(): the thread releases the object's lock and waits until another thread notifies it.
  • notify(): wakes up one thread waiting on that object.
  • notifyAll(): wakes up all waiting threads.

This is used in the producer-consumer problem, where the producer must wait when the buffer is full and the consumer must wait when it is empty.

Example

class Buffer {
    private int value;
    private boolean available = false;

    synchronized void produce(int v) throws InterruptedException {
        while (available) wait();            // wait until consumed
        value = v;
        System.out.println("Produced: " + v);
        available = true;
        notify();                            // wake consumer
    }

    synchronized void consume() throws InterruptedException {
        while (!available) wait();           // wait until produced
        System.out.println("Consumed: " + value);
        available = false;
        notify();                            // wake producer
    }
}

public class ProducerConsumer {
    public static void main(String[] args) {
        Buffer b = new Buffer();

        Thread producer = new Thread(() -> {
            try { for (int i = 1; i <= 3; i++) b.produce(i); }
            catch (InterruptedException e) { }
        });
        Thread consumer = new Thread(() -> {
            try { for (int i = 1; i <= 3; i++) b.consume(); }
            catch (InterruptedException e) { }
        });

        producer.start();
        consumer.start();
    }
}

Output:

Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3

The two threads take turns because each waits until the other has notified it.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

How to handle multiple catch blocks for a nested try block? Explain with an example.

Answer

Nested try blocks with multiple catch blocks

A try block can be placed inside another try block. Each try block can have its own one or more catch blocks (and an optional finally). When an exception occurs:

  1. The JVM looks for a matching catch block of the innermost try block, checking them from top to bottom.
  2. If none matches, the exception propagates to the catch blocks of the enclosing (outer) try block.
  3. If no block matches anywhere, the program terminates with the default handler.

Rules for multiple catch blocks: the first matching block executes and the others are skipped; a subclass exception must be caught before its superclass (for example ArithmeticException before Exception), otherwise there is a compile-time error.

Example

public class NestedTry {
    public static void main(String[] args) {
        try {                                           // outer try
            int[] a = new int[3];
            try {                                       // inner try
                int x = 10 / 0;                         // ArithmeticException
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("Inner: array index problem");
            } catch (NullPointerException e) {
                System.out.println("Inner: null problem");
            }
            // not reached: the exception was not handled by the inner catch blocks
            a[5] = 1;
        } catch (ArithmeticException e) {
            System.out.println("Outer: arithmetic exception - " + e.getMessage());
        } catch (Exception e) {
            System.out.println("Outer: general exception");
        } finally {
            System.out.println("Finally block executed");
        }
    }
}

Output:

Outer: arithmetic exception - / by zero
Finally block executed

The inner catch blocks do not match ArithmeticException, so it passes to the outer try, where the first catch block handles it. The statement a[5] = 1 is skipped, and finally always runs.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

What is difference between String and String buffer and explain 3 methods of String and String Buffer class with example.

Answer

Difference between String and StringBuffer

StringStringBuffer
Immutable: value cannot be changed.Mutable: value can be changed.
Each change creates a new object.Changes are made in the same object.
Slower for repeated modification.Faster for repeated modification.
Uses the string constant pool for literals.Stored on the heap; created with new.
equals() and hashCode() are overridden.They are not overridden.
Not synchronized (not needed, immutable).Synchronized, thread safe.

Three methods of String

String s = "Hello World";
System.out.println(s.length());            // 11
System.out.println(s.substring(6));        // World
System.out.println(s.toUpperCase());       // HELLO WORLD
  • length() returns the number of characters.
  • substring(int begin) returns the part of the string from the index given.
  • toUpperCase() returns a new string in upper case (the original is unchanged).

Other useful methods: charAt(), indexOf(), equals(), concat(), replace().

Three methods of StringBuffer

StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");                       // Hello World
sb.insert(5, ",");                         // Hello, World
sb.reverse();                              // dlroW ,olleH
System.out.println(sb);
  • append(x) adds x at the end of the same object.
  • insert(int index, x) inserts x at the given position.
  • reverse() reverses the characters in place.

Other methods: delete(), replace(), capacity(), setCharAt().

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 5 marks

Write short notes on: (any two)
i. JDBC Driver
ii. Access Modifiers
iii. JDK, JRE and JVM

Answer

i. JDBC Driver

A JDBC driver is a software component that lets a Java application communicate with a particular database. It implements the JDBC interfaces (Connection, Statement, ResultSet) and translates JDBC calls into the database's own protocol. There are four types:

  1. Type 1: JDBC-ODBC bridge driver: converts JDBC calls into ODBC calls; needs an ODBC driver on the client; slow and removed from modern Java.
  2. Type 2: Native-API driver: converts JDBC calls into the database's native client library calls; needs native code installed on the client.
  3. Type 3: Network protocol driver: sends calls to a middleware server, which talks to the database; no client installation, flexible but needs an extra server.
  4. Type 4: Thin driver (pure Java): converts JDBC calls directly into the database protocol; fastest, portable and most widely used (for example MySQL Connector/J, com.mysql.cj.jdbc.Driver).

The driver is loaded with Class.forName("...") (automatic in recent JDBC versions) and used through DriverManager.getConnection(url, user, password).

ii. Access Modifiers

Access modifiers control the visibility of classes, fields, methods and constructors.

ModifierSame classSame packageSubclass in another packageAnywhere
privateYesNoNoNo
default (no keyword)YesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes

They support encapsulation: data is usually kept private and exposed through public getters and setters. A top-level class can only be public or default.

iii. JDK, JRE and JVM

  • JVM (Java Virtual Machine): the abstract machine that loads, verifies and executes bytecode (.class files), including the JIT compiler and garbage collector. It makes Java platform independent; it is platform specific itself.
  • JRE (Java Runtime Environment): JVM plus the standard class libraries and supporting files needed to run Java programs. It cannot compile programs.
  • JDK (Java Development Kit): JRE plus development tools such as the compiler javac, java, jar, javadoc and the debugger. It is needed to develop Java programs.

Relationship: JDK contains JRE, and JRE contains JVM.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 10 marks

Define array and multi dimensional array. Write a program to read two m x n matrices, perform multiplication operation and store result in third matrix.

Answer

Array

An array is a fixed-size collection of elements of the same data type stored in contiguous memory and accessed by an index starting at 0. In Java arrays are objects: int[] a = new int[5];.

Multi-dimensional array

An array whose elements are themselves arrays. The most common is the two-dimensional array (a table of rows and columns), declared as int[][] m = new int[3][4]; and accessed as m[i][j]. Java implements it as an array of arrays, so rows may even have different lengths.

Matrix multiplication program

For an m×nm \times n matrix AA and an n×pn \times p matrix BB, the product C=ABC = AB is an m×pm \times p matrix with

Cij=∑k=1nAikBkjC_{ij} = \sum_{k=1}^{n} A_{ik} B_{kj}

Multiplication is possible only when the number of columns of AA equals the number of rows of BB. For two m×nm \times n matrices this means m=nm = n (square matrices); the program reads both orders so that it also works for any compatible pair and reports otherwise.

import java.util.Scanner;

public class MatrixMultiply {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter rows and columns of first matrix: ");
        int m = sc.nextInt(), n = sc.nextInt();
        System.out.print("Enter rows and columns of second matrix: ");
        int r2 = sc.nextInt(), p = sc.nextInt();

        if (n != r2) {
            System.out.println("Multiplication not possible: columns of A must equal rows of B.");
            return;
        }

        int[][] a = new int[m][n];
        int[][] b = new int[r2][p];
        int[][] c = new int[m][p];

        System.out.println("Enter elements of first matrix:");
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                a[i][j] = sc.nextInt();

        System.out.println("Enter elements of second matrix:");
        for (int i = 0; i < r2; i++)
            for (int j = 0; j < p; j++)
                b[i][j] = sc.nextInt();

        for (int i = 0; i < m; i++)
            for (int j = 0; j < p; j++) {
                c[i][j] = 0;
                for (int k = 0; k < n; k++)
                    c[i][j] += a[i][k] * b[k][j];
            }

        System.out.println("Product matrix:");
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < p; j++)
                System.out.print(c[i][j] + "\t");
            System.out.println();
        }
        sc.close();
    }
}

Sample run with A=(1234)A = \begin{pmatrix}1&2\\3&4\end{pmatrix} and B=(5678)B = \begin{pmatrix}5&6\\7&8\end{pmatrix}:

C=(1⋅5+2⋅71⋅6+2⋅83⋅5+4⋅73⋅6+4⋅8)=(19224350)C = \begin{pmatrix}1\cdot5+2\cdot7 & 1\cdot6+2\cdot8\\ 3\cdot5+4\cdot7 & 3\cdot6+4\cdot8\end{pmatrix} = \begin{pmatrix}19&22\\43&50\end{pmatrix}

The program prints the rows 19 22 and 43 50.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 10 marks

Write a program to create the following simple GUI based application. If user press the Submit button, your program should store the information in a file named "exam.txt" only when he accepts the terms and condition otherwise it should display a message "please accept the terms and condition first".

Answer

The figure is not reproduced here, so the usual exam form is assumed: a name field, a roll number field, a program choice, a checkbox "I accept the terms and conditions" and a Submit button.

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

public class ExamForm extends JFrame implements ActionListener {
    JTextField nameField, rollField;
    JComboBox<String> program;
    JCheckBox terms;
    JButton submit;

    ExamForm() {
        setTitle("Exam Form");
        setLayout(new GridLayout(5, 2, 5, 5));

        nameField = new JTextField();
        rollField = new JTextField();
        program = new JComboBox<>(new String[]{"BCA", "BIT", "BBA"});
        terms = new JCheckBox("I accept the terms and conditions");
        submit = new JButton("Submit");

        add(new JLabel("Name:"));    add(nameField);
        add(new JLabel("Roll No:")); add(rollField);
        add(new JLabel("Program:")); add(program);
        add(terms);                  add(new JLabel(""));
        add(submit);

        submit.addActionListener(this);

        setSize(350, 220);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (!terms.isSelected()) {
            JOptionPane.showMessageDialog(this, "please accept the terms and condition first");
            return;
        }
        try (FileWriter fw = new FileWriter("exam.txt", true);
             BufferedWriter bw = new BufferedWriter(fw)) {
            bw.write("Name: " + nameField.getText()
                   + ", Roll: " + rollField.getText()
                   + ", Program: " + program.getSelectedItem());
            bw.newLine();
            JOptionPane.showMessageDialog(this, "Information saved to exam.txt");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(ExamForm::new);
    }
}

When Submit is pressed, the program checks terms.isSelected(). If the box is not ticked it shows the message "please accept the terms and condition first" and writes nothing. Otherwise it appends the entered information to exam.txt.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2024 · 10 marks

Differentiate between overloading and overriding with suitable example WAP to Create a Set with following values: {"London", "NewYork", "SanFrancisco", "Beijing", "NewYork"} Perform operations on above Set:
Add new element
Get Set size
Remove element
Contains element?
addAll
removeAll
retainAll

Answer

Overloading versus overriding

Method overloadingMethod overriding
Same method name, different parameter list, in the same class.Same name and same parameters in a subclass as in its superclass.
Compile-time (static) polymorphism.Run-time (dynamic) polymorphism.
Return type may differ (but cannot alone distinguish).Return type must be same or covariant.
Needs no inheritance.Needs inheritance.
Access modifier may be anything.Cannot reduce the visibility.
static and private methods can be overloaded.static, private and final methods cannot be overridden.
class Calc {
    int add(int a, int b)        { return a + b; }       // overloading
    double add(double a, double b) { return a + b; }
    int add(int a, int b, int c) { return a + b + c; }
}

class Shape {
    void draw() { System.out.println("Drawing shape"); }
}
class Circle extends Shape {
    @Override
    void draw() { System.out.println("Drawing circle"); }   // overriding
}

new Calc().add(2, 3) selects the int version at compile time, while Shape s = new Circle(); s.draw(); prints "Drawing circle" because the method is chosen at run time.

Set operations program

import java.util.*;

public class SetOperations {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>(Arrays.asList(
            "London", "NewYork", "SanFrancisco", "Beijing", "NewYork"));
        // the duplicate "NewYork" is ignored by the Set
        System.out.println("Initial set: " + set);

        set.add("Paris");
        System.out.println("After adding Paris: " + set);

        System.out.println("Size: " + set.size());

        set.remove("Beijing");
        System.out.println("After removing Beijing: " + set);

        System.out.println("Contains London? " + set.contains("London"));

        Set<String> other = new HashSet<>(Arrays.asList("Tokyo", "London", "Delhi"));
        set.addAll(other);
        System.out.println("After addAll: " + set);

        set.removeAll(Arrays.asList("Tokyo", "Delhi"));
        System.out.println("After removeAll [Tokyo, Delhi]: " + set);

        Set<String> keep = new HashSet<>(Arrays.asList("London", "Paris", "Oslo"));
        set.retainAll(keep);
        System.out.println("After retainAll [London, Paris, Oslo]: " + set);
    }
}

Trace: the initial set has 4 distinct elements (London, NewYork, SanFrancisco, Beijing), so after adding Paris the size is 5. After removing Beijing it has 4. addAll adds Tokyo and Delhi (London already exists), giving 6 elements. removeAll removes Tokyo and Delhi, leaving London, NewYork, SanFrancisco, Paris. retainAll keeps only elements also in keep, so the final set is {London, Paris}. The print order of a HashSet is not guaranteed.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 5 marks

What is command-line arguments? Write a program to accept two numbers and display their sum using command-line arguments.

Answer

Command-line arguments

Command-line arguments are values supplied to a program on the command line after the class name when it is run, for example java Sum 10 20. They are received as strings in the String[] args parameter of main(): args[0] is the first argument and args.length gives how many were supplied. Since they are String, numeric values must be converted, for example with Integer.parseInt().

Program

public class Sum {
    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("Usage: java Sum <number1> <number2>");
            return;
        }
        try {
            int a = Integer.parseInt(args[0]);
            int b = Integer.parseInt(args[1]);
            System.out.println("Sum = " + (a + b));
        } catch (NumberFormatException e) {
            System.out.println("Please enter valid integers.");
        }
    }
}

Compile with javac Sum.java and run with java Sum 10 20. The output is Sum = 30.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 5 marks

Write a program to demonstrate exception handling of ArrayIndexOutOfBoundsException.

Answer

ArrayIndexOutOfBoundsException is an unchecked exception thrown when an array is accessed with an index that is negative or greater than or equal to its length. It is handled with a try-catch block.

public class ArrayExceptionDemo {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};

        try {
            System.out.println("Accessing valid index 2: " + numbers[2]);
            // Invalid index: valid indices are 0 to 4
            System.out.println("Accessing index 7: " + numbers[7]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Exception caught: " + e.getMessage());
        } finally {
            System.out.println("finally block always executes.");
        }

        System.out.println("Program continues normally after handling.");
    }
}

Output

Accessing valid index 2: 30
Exception caught: Index 7 out of bounds for length 5
finally block always executes.
Program continues normally after handling.

The statement numbers[7] throws the exception. Control jumps to the matching catch block, which prints the message, so the program does not terminate abnormally. The finally block runs whether or not an exception occurred.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 5 marks

What is string immutability? Explain with an example.

Answer

String immutability means that once a String object is created, its contents cannot be changed. Any operation that appears to modify a string (such as concat, replace, toUpperCase or +) does not change the original object; it creates and returns a new String object.

Example

public class ImmutableDemo {
    public static void main(String[] args) {
        String s1 = "Hello";
        s1.concat(" World");          // result is discarded
        System.out.println(s1);       // Hello

        String s2 = s1.concat(" World");
        System.out.println(s2);       // Hello World
        System.out.println(s1);       // Hello (unchanged)

        s1 = s1 + "!";                // s1 now refers to a NEW object
        System.out.println(s1);       // Hello!
    }
}

The call s1.concat(" World") leaves s1 as "Hello". Only the reference changes when we assign the new result; the old object "Hello" is untouched (and later garbage collected if unreferenced).

Why strings are immutable

  • String pool: literals with the same value share one object in the pool, which saves memory. This is safe only if the object cannot change.
  • Security: strings are used for file names, URLs, passwords and class names; immutability prevents them being altered after validation.
  • Thread safety: immutable objects can be shared between threads without synchronization.
  • Hashcode caching: the hash code is computed once, which makes strings efficient as HashMap keys.

For frequent modification, StringBuilder or StringBuffer (mutable) should be used.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 5 marks

Write a program to create multiple threads and execute them concurrently.

Answer

In Java, multiple threads can be created by extending the Thread class or implementing the Runnable interface. Calling start() makes each thread run concurrently, with the JVM scheduler interleaving their execution.

class MyThread extends Thread {
    private String name;

    MyThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(name + " : count " + i);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                System.out.println(name + " interrupted");
            }
        }
        System.out.println(name + " finished");
    }
}

public class MultiThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        MyThread t1 = new MyThread("Thread-A");
        MyThread t2 = new MyThread("Thread-B");
        Thread t3 = new Thread(() -> {                 // Runnable via lambda
            for (int i = 1; i <= 5; i++) {
                System.out.println("Thread-C : count " + i);
                try { Thread.sleep(500); } catch (InterruptedException e) { }
            }
        });

        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();
        System.out.println("All threads completed.");
    }
}

The output lines of Thread-A, Thread-B and Thread-C are interleaved, and the order may differ between runs because scheduling is decided by the JVM and operating system. start() creates a new call stack and invokes run(); calling run() directly would execute it in the main thread without concurrency. join() makes the main thread wait until the others finish.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 5 marks

Explain the Serializable interface in java with an example.

Answer

java.io.Serializable is a marker interface (it has no methods) in the java.io package. A class that implements it can have its objects converted to a byte stream (serialization) so they can be saved to a file, sent over a network or stored in a database, and later rebuilt (deserialization) into an object.

Key points

  • Serialization uses ObjectOutputStream.writeObject(), deserialization uses ObjectInputStream.readObject().
  • If a class does not implement Serializable, NotSerializableException is thrown.
  • Fields declared transient (and static fields) are not serialized; on deserialization they get default values.
  • serialVersionUID is a version number used to verify that the sender and receiver classes are compatible.
  • All fields of a serializable object must themselves be serializable (or transient).

Example

import java.io.*;

class Student implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;
    int roll;
    transient String password;   // not saved

    Student(String name, int roll, String password) {
        this.name = name;
        this.roll = roll;
        this.password = password;
    }
}

public class SerializeDemo {
    public static void main(String[] args) throws Exception {
        Student s = new Student("Ram", 101, "secret");

        try (ObjectOutputStream out =
                 new ObjectOutputStream(new FileOutputStream("student.ser"))) {
            out.writeObject(s);
        }

        try (ObjectInputStream in =
                 new ObjectInputStream(new FileInputStream("student.ser"))) {
            Student r = (Student) in.readObject();
            System.out.println(r.name + " " + r.roll + " " + r.password);
        }
    }
}

Output: Ram 101 null (the transient field password was not stored).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 5 marks

What is multiple inheritance? Explain how multiple inheritance is implemented in Java?

Answer

Multiple inheritance is a feature in which a class inherits properties and behaviour from more than one parent class.

Java does not support multiple inheritance through classes. If class C extended both A and B and both defined the same method, the compiler could not decide which version to inherit (the diamond problem). To avoid this ambiguity and complexity, a Java class may extend only one class.

Implementation using interfaces

Java achieves multiple inheritance of type and behaviour through interfaces, because a class can implement any number of interfaces, and interfaces contain no instance state.

interface Printable {
    void print();
}

interface Showable {
    void show();
}

class Document implements Printable, Showable {
    public void print() {
        System.out.println("Printing document");
    }
    public void show() {
        System.out.println("Showing document");
    }
}

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

Default method conflicts: if two interfaces provide the same default method, the implementing class must override it and may choose one with InterfaceName.super.method().

interface A { default void hello() { System.out.println("A"); } }
interface B { default void hello() { System.out.println("B"); } }

class C implements A, B {
    public void hello() {
        A.super.hello();   // resolves the conflict explicitly
    }
}

A class can also combine both forms: class D extends Base implements I1, I2.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 5 marks

What is JDBC? Explain its architecture.

Answer

JDBC (Java Database Connectivity) is a Java API (package java.sql) that allows Java programs to connect to relational databases, execute SQL statements and process the results in a database-independent way. Vendors supply JDBC drivers, so the same application code works with MySQL, Oracle, PostgreSQL and others.

JDBC architecture

The architecture has two layers: the JDBC API and the JDBC Driver API.

Java Application
      |
   JDBC API  (Connection, Statement, ResultSet ...)
      |
 JDBC DriverManager
      |
 JDBC Driver (vendor specific)
      |
   Database
  1. Java application: issues SQL requests using the JDBC API.
  2. JDBC API: provides the interfaces and classes: DriverManager, Connection, Statement, PreparedStatement, CallableStatement, ResultSet, SQLException.
  3. DriverManager: manages the list of registered drivers and selects the proper driver for a given connection URL.
  4. JDBC driver: translates JDBC calls into the database's native protocol. Driver types are: Type 1 (JDBC-ODBC bridge), Type 2 (native API), Type 3 (network protocol) and Type 4 (pure Java thin driver, most widely used).
  5. Database: executes the query and returns results.

Basic steps

Connection con = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/college", "root", "password");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM student");
while (rs.next()) {
    System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
con.close();

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 10 marks

Explain nested and inner classes in java with examples. Discuss the scenarios where inner classes are useful.

Answer

A nested class is a class defined inside another class. Nested classes are of two kinds: static nested classes and inner (non-static) classes. Inner classes are further divided into member inner classes, local inner classes and anonymous inner classes.

1. Static nested class

Declared with static; it does not need an outer instance and can access only static members of the outer class.

class Outer {
    static int x = 10;
    static class Nested {
        void show() { System.out.println("x = " + x); }
    }
}
// Outer.Nested n = new Outer.Nested(); n.show();

2. Member inner class

A non-static class defined at member level. It needs an outer object and can access all members of the outer class, including private ones.

class Outer {
    private int data = 50;
    class Inner {
        void display() { System.out.println("data = " + data); }
    }
}
// Outer o = new Outer();
// Outer.Inner i = o.new Inner();
// i.display();

3. Local inner class

Defined inside a method or block; visible only there, and it can use final or effectively final local variables.

class Outer {
    void method() {
        int n = 5;
        class Local {
            void print() { System.out.println("n = " + n); }
        }
        new Local().print();
    }
}

4. Anonymous inner class

A class without a name, declared and instantiated in a single expression, usually to implement an interface or override a method.

Runnable r = new Runnable() {
    public void run() { System.out.println("Running"); }
};
new Thread(r).start();

Scenarios where inner classes are useful

  • Logical grouping: a class used only by one other class can be placed inside it, keeping the code together (e.g. Node inside LinkedList).
  • Encapsulation: the inner class can access private members of the outer class while remaining hidden from the outside world.
  • Event handling: anonymous inner classes are widely used for listeners in AWT/Swing, such as ActionListener, and for callbacks.
  • Iterators: a collection class can provide an inner class implementing Iterator that directly accesses the collection's private data.
  • Readable and maintainable code: fewer top-level classes and closer placement of related code.
  • Multiple inheritance of implementation: an outer class can have several inner classes each extending a different class.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 10 marks

Create a class Person (with attributes name and age, and a method display()). Derive a class Employee from Person with additional attributes employeeId and salary. Use constructors and override the display() method to include all details.

Answer

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    void display() {
        System.out.println("Name : " + name);
        System.out.println("Age  : " + age);
    }
}

class Employee extends Person {
    int employeeId;
    double salary;

    Employee(String name, int age, int employeeId, double salary) {
        super(name, age);               // call Person constructor
        this.employeeId = employeeId;
        this.salary = salary;
    }

    @Override
    void display() {
        super.display();                // display name and age
        System.out.println("Employee ID : " + employeeId);
        System.out.println("Salary      : Rs " + salary);
    }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Person("Sita", 30);
        System.out.println("--- Person ---");
        p.display();

        Employee e = new Employee("Ram", 28, 101, 45000.0);
        System.out.println("--- Employee ---");
        e.display();

        Person ref = new Employee("Hari", 35, 102, 60000.0);
        System.out.println("--- Employee via Person reference ---");
        ref.display();                  // runtime polymorphism
    }
}

Output

--- Person ---
Name : Sita
Age  : 30
--- Employee ---
Name : Ram
Age  : 28
Employee ID : 101
Salary      : Rs 45000.0
--- Employee via Person reference ---
Name : Hari
Age  : 35
Employee ID : 102
Salary      : Rs 60000.0

Explanation

  • Employee inherits name, age and display() from Person using extends.
  • The Employee constructor calls super(name, age) to initialise the inherited part, then sets its own attributes.
  • display() is overridden in Employee; it calls super.display() to reuse the parent output and adds the extra details.
  • With a Person reference holding an Employee object, the overridden version is selected at run time (dynamic method dispatch).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2025 · 10 marks

Build a form with Passenger Name, Flight Number, Seat Preference (Window, Aisle, Middle), and a checkbox for "I agree to baggage rules." Clicking Confirm Booking should save data to "flight.txt" if rules are accepted otherwise display "Accept baggage rules first."

Answer

The form is built with Swing. On clicking Confirm Booking, if the checkbox is selected the data is appended to flight.txt; otherwise the message "Accept baggage rules first." is shown.

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

public class FlightBookingForm extends JFrame implements ActionListener {
    JTextField nameField, flightField;
    JRadioButton window, aisle, middle;
    JCheckBox agree;
    JButton confirm;

    FlightBookingForm() {
        setTitle("Flight Booking");
        setSize(380, 300);
        setLayout(new GridLayout(6, 2, 5, 5));
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        nameField = new JTextField();
        flightField = new JTextField();

        window = new JRadioButton("Window", true);
        aisle = new JRadioButton("Aisle");
        middle = new JRadioButton("Middle");
        ButtonGroup group = new ButtonGroup();
        group.add(window);
        group.add(aisle);
        group.add(middle);

        JPanel seatPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        seatPanel.add(window);
        seatPanel.add(aisle);
        seatPanel.add(middle);

        agree = new JCheckBox("I agree to baggage rules.");
        confirm = new JButton("Confirm Booking");
        confirm.addActionListener(this);

        add(new JLabel("Passenger Name:"));
        add(nameField);
        add(new JLabel("Flight Number:"));
        add(flightField);
        add(new JLabel("Seat Preference:"));
        add(seatPanel);
        add(new JLabel(""));
        add(agree);
        add(new JLabel(""));
        add(confirm);

        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (!agree.isSelected()) {
            JOptionPane.showMessageDialog(this, "Accept baggage rules first.");
            return;
        }

        String seat = window.isSelected() ? "Window"
                    : aisle.isSelected() ? "Aisle" : "Middle";

        try (FileWriter fw = new FileWriter("flight.txt", true);
             BufferedWriter bw = new BufferedWriter(fw)) {
            bw.write("Passenger: " + nameField.getText()
                   + ", Flight: " + flightField.getText()
                   + ", Seat: " + seat);
            bw.newLine();
            JOptionPane.showMessageDialog(this, "Booking confirmed and saved.");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Error saving data: " + ex.getMessage());
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(FlightBookingForm::new);
    }
}

Explanation

  • Radio buttons in a ButtonGroup ensure only one seat preference is chosen.
  • agree.isSelected() checks the checkbox; if false, the warning is displayed and nothing is written.
  • FileWriter("flight.txt", true) opens the file in append mode, so earlier bookings are kept; try-with-resources closes the file automatically.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

Questions from TU BCA 2019 Third Semester Data Structures and Algorithms (TU board exam, 2019), TU BCA 2019 Third Semester Data Structures and Algorithms (TU board exam, 2019 Group A objective questions (scanned paper compiled by Aadim College)), TU BCA 2020 Third Semester Data Structures and Algorithms (TU board exam, 2020), TU BCA 2021 Third Semester Data Structures and Algorithms (TU board exam, 2021), TU BCA 2022 Third Semester Data Structures and Algorithms (TU board exam, 2022), TU BCA 2023 Third Semester Data Structures and Algorithms (TU board exam, 2023), TU BCA 2024 Third Semester Data Structures and Algorithms (TU board exam, 2024), TU BCA 2025 Third Semester Data Structures and Algorithms (TU board exam, 2025), TU BCA 2019 Third Semester OOP in Java (TU board exam, 2019), TU BCA 2019 Third Semester OOP in Java (TU board exam, 2019 Group A objective questions (scanned paper compiled by Aadim College)), TU BCA 2020 Third Semester OOP in Java (TU board exam, 2020), TU BCA 2021 Third Semester OOP in Java (TU board exam, 2021), TU BCA 2022 Third Semester OOP in Java (TU board exam, 2022), TU BCA 2023 Third Semester OOP in Java (TU board exam, 2023), TU BCA 2024 Third Semester OOP in Java (TU board exam, 2024), TU BCA 2025 Third Semester OOP in Java (TU board exam, 2025), TU BCA 2019 Third Semester Probability and Statistics (TU board exam, 2019), TU BCA 2019 Third Semester Probability and Statistics (TU board exam, 2019 Group A objective questions (scanned paper compiled by Aadim College)), TU BCA 2020 Third Semester Probability and Statistics (TU board exam, 2020), TU BCA 2021 Third Semester Probability and Statistics (TU board exam, 2021), TU BCA 2022 Third Semester Probability and Statistics (TU board exam, 2022), TU BCA 2023 Third Semester Probability and Statistics (TU board exam, 2023), TU BCA 2024 Third Semester Probability and Statistics (TU board exam, 2024), TU BCA 2025 Third Semester Probability and Statistics (TU board exam, 2025), TU BCA 2019 Third Semester System Analysis and Design (TU board exam, 2019), TU BCA 2019 Third Semester System Analysis and Design (TU board exam, listed as 2019 (a second 2019 set in the compilation)), TU BCA 2019 Third Semester System Analysis and Design (TU board exam, 2019 Group A objective questions (scanned paper compiled by Aadim College)), TU BCA 2020 Third Semester System Analysis and Design (TU board exam, 2020), TU BCA 2021 Third Semester System Analysis and Design (TU board exam, 2021), TU BCA 2022 Third Semester System Analysis and Design (TU board exam, 2022), TU BCA 2023 Third Semester System Analysis and Design (TU board exam, 2023), TU BCA 2024 Third Semester System Analysis and Design (TU board exam, 2024), TU BCA 2025 Third Semester System Analysis and Design (TU board exam, 2025), TU BCA 2019 Third Semester Web Technology (TU board exam, 2019), TU BCA 2019 Third Semester Web Technology (TU board exam, 2019 Group A objective questions (scanned paper compiled by Aadim College)), TU BCA 2020 Third Semester Web Technology (TU board exam, 2020), TU BCA 2021 Third Semester Web Technology (TU board exam, 2021), TU BCA 2022 Third Semester Web Technology (TU board exam, 2022), TU BCA 2023 Third Semester Web Technology (TU board exam, 2023), TU BCA 2024 Third Semester Web Technology (TU board exam, 2024) and TU BCA 2025 Third Semester Web Technology (TU board exam, 2025). Answers are written for this site; check them against your class notes.