Chapter 5
Java Programming
PU BCA past exam questions
Past questions and answers
77 questions set from this chapter, 2 of them more than once. Most repeated first.
- Asked 2 times
- 2023 Spring · 8 marks
- 2022 Fall · 8 marks
What is a Layout Manager? Explain GridBagLayout manager with examples.
Answer
Layout manager
A layout manager is an object that controls the size and position of components inside a container (Frame, Panel, JFrame). It lets the interface adjust to different screen sizes and platforms. It is set with setLayout(). Common ones are FlowLayout, BorderLayout, GridLayout, CardLayout, BoxLayout and GridBagLayout.
GridBagLayout
GridBagLayout is the most flexible layout manager. It places components in a grid of rows and columns, but a component may span several rows or columns, and rows and columns can have different sizes. Each component is controlled by a GridBagConstraints object with these main fields:
gridx,gridy: the cell (column, row).gridwidth,gridheight: the number of columns or rows spanned.weightx,weighty: how extra space is shared.fill: how the component grows (NONE,HORIZONTAL,VERTICAL,BOTH).anchor: where the component sits inside its cell.insets: the external padding.ipadx,ipady: the internal padding.
Example
import javax.swing.*;
import java.awt.*;
public class GridBagDemo {
public static void main(String[] args) {
JFrame f = new JFrame("GridBagLayout");
f.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0; c.gridy = 0;
f.add(new JLabel("Name:"), c);
c.gridx = 1; c.gridy = 0; c.weightx = 1.0;
f.add(new JTextField(15), c);
c.gridx = 0; c.gridy = 1; c.gridwidth = 2; // spans two columns
f.add(new JButton("Submit"), c);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
The label and text field are in row 0, and the button sits in row 1 across both columns.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- Asked 2 times
- 2023 Spring · 5 marks
- 2022 Fall · 5 marks
Write short notes on: Can we achieve polymorphism in Java Generics?
Answer
Yes. Polymorphism can be achieved in Java generics in these ways.
- Parametric polymorphism: one generic class or method works for many types, for example
Box<T>or<T> void show(T x). - Bounded type parameters:
<T extends Shape>acceptsShapeand its subclasses, and calls overridden methods polymorphically. - Wildcards:
List<? extends Shape>acceptsList<Circle>orList<Square>, andList<? super Circle>accepts lists ofCircleand its parents. - Subtype objects inside a generic type:
List<Shape>can holdCircleandSquareobjects, anddraw()is chosen at run time.
Important limit: generics are invariant. List<Circle> is not a List<Shape>, even though Circle is a Shape. Wildcards are used to overcome this.
static void drawAll(List<? extends Shape> list) {
for (Shape s : list) s.draw(); // runtime polymorphism
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 7 marks
Write a program in Java to create a file named sample.txt, write "Java Programming is Fun!!" to the file, and then read the content from sample.txt. Use appropriate file reading and writing classes.
Similar questions: File write and read: Hello World (2024 Fall)
Answer
FileWriter writes characters to a file and FileReader (wrapped in BufferedReader) reads them back. Both can throw IOException, so they are used with try-with-resources, which closes the files automatically.
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
// create sample.txt and write to it
try (FileWriter fw = new FileWriter("sample.txt")) {
fw.write("Java Programming is Fun!!");
System.out.println("Data written to sample.txt");
} catch (IOException e) {
System.out.println("Write error: " + e.getMessage());
}
// read the content back
try (BufferedReader br = new BufferedReader(new FileReader("sample.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Read error: " + e.getMessage());
}
}
}
Output:
Data written to sample.txt
Java Programming is Fun!!
new FileWriter("sample.txt") creates the file if it does not exist (and overwrites it if it does). readLine() returns null at the end of the file, which ends the loop.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 7 marks
Write a program in Java to create a file named sample.txt, write "Hello World" to the file, and then read the content from sample.txt. Use appropriate file reading and writing classes.
Similar questions: File write and read: Java Programming is Fun!! (2025 Spring)
Answer
FileWriter writes characters to a file and FileReader reads characters from it. Both throw the checked IOException, so the code is placed in try-catch; try-with-resources closes the streams automatically.
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
// Create sample.txt and write "Hello World"
try (FileWriter fw = new FileWriter("sample.txt")) {
fw.write("Hello World");
System.out.println("Data written to sample.txt");
} catch (IOException e) {
System.out.println("Write error: " + e.getMessage());
}
// Read the content back
try (FileReader fr = new FileReader("sample.txt")) {
int ch;
System.out.print("File content: ");
while ((ch = fr.read()) != -1) {
System.out.print((char) ch);
}
System.out.println();
} catch (IOException e) {
System.out.println("Read error: " + e.getMessage());
}
}
}
Explanation.
new FileWriter("sample.txt")creates the file if it does not exist (and overwrites it if it does).write()stores the string; closing the writer flushes the data to disk.FileReader.read()returns one character as anint, or-1at end of file, so the loop prints characters until-1.
Output:
Data written to sample.txt
File content: Hello World
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 8 marks
What is the importance of generic methods over non-generic method? Explain with example.
Similar questions: Generics, importance of generic methods (2022 Fall)
Answer
A generic method declares its own type parameter before the return type, so it can work with many data types while the compiler still checks the types.
Importance over non-generic methods
- One method for all types: a non-generic version needs one overloaded method per type, or an
Objectparameter. - Type safety: with
Object, wrong types are found only at run time (ClassCastException). A generic method is checked at compile time. - No casting: the result already has the right type.
- Reusability and maintenance: one method is easier to maintain than many copies.
- Type inference: the compiler infers
Tfrom the arguments, so the call looks simple.
Example
Non-generic code needs separate methods:
static void print(Integer[] a) { for (Integer x : a) System.out.print(x + " "); }
static void print(String[] a) { for (String x : a) System.out.print(x + " "); }
Generic version:
public class GenericMethodDemo {
static <T> void print(T[] arr) {
for (T x : arr) System.out.print(x + " ");
System.out.println();
}
static <T extends Comparable<T>> T max(T a, T b) {
return a.compareTo(b) > 0 ? a : b;
}
public static void main(String[] args) {
print(new Integer[]{1, 2, 3});
print(new String[]{"Ram", "Sita"});
print(new Double[]{1.5, 2.5});
System.out.println(max(10, 20)); // 20
System.out.println(max("apple", "mango")); // mango
}
}
The single print and max methods work for Integer, String and Double.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 7 marks
Define Generics in Java. What is the importance of generic methods over non-generic method? Explain with example.
Similar questions: Generic methods importance (2023 Spring)
Answer
Generics in Java
Generics allow classes, interfaces and methods to take types as parameters (<T>). They provide compile-time type checking, remove the need for casting, and make code reusable. Collections such as ArrayList<String> use generics.
Importance of generic methods over non-generic methods
- One generic method handles all types, while non-generic code needs a separate overloaded method for each type.
- It is type safe, since mistakes are found at compile time. A non-generic method taking
Objectcan fail at run time withClassCastException. - No casting is needed on the result.
- It reduces duplicate code and is easier to maintain.
- Bounds (
<T extends Comparable<T>>) allow operations that need certain capabilities.
Example
public class GenericDemo {
static <T> void display(T[] arr) {
for (T e : arr) System.out.print(e + " ");
System.out.println();
}
static <T extends Comparable<T>> T largest(T[] arr) {
T max = arr[0];
for (T e : arr) if (e.compareTo(max) > 0) max = e;
return max;
}
public static void main(String[] args) {
Integer[] a = {3, 9, 5};
String[] s = {"ball", "zebra", "cat"};
display(a);
display(s);
System.out.println(largest(a)); // 9
System.out.println(largest(s)); // zebra
}
}
Two methods serve both Integer and String arrays; without generics, four methods would be needed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 8 marks
What do you mean by platform independence? Write down the steps to compile and execute java program with necessary diagram.
Answer
Platform independence
Platform independence means a program written once can run unchanged on any operating system and hardware (Windows, Linux, macOS) without recompiling. Java achieves this ("Write Once, Run Anywhere") because the compiler does not produce machine code for a specific CPU. It produces bytecode (a .class file), an intermediate, platform-neutral instruction set. Each platform has its own Java Virtual Machine (JVM) that interprets or JIT-compiles the bytecode into native instructions. Only the JVM is platform dependent; the bytecode is not.
Steps to compile and execute a Java program
Step 1: Write the source code in a text editor or IDE and save it with the .java extension. The file name must match the public class name.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, Nepal!");
}
}
Step 2: Compile with the Java compiler: javac Hello.java. The compiler checks syntax and types and generates Hello.class containing bytecode. Errors are reported here and no class file is produced.
Step 3: Load and verify. When you run java Hello, the JVM's class loader loads Hello.class, and the bytecode verifier checks that the code is valid and safe.
Step 4: Execute. The interpreter and JIT compiler convert bytecode into native machine code for the host system and run it. Output: Hello, Nepal!
Diagram
Hello.java --javac--> Hello.class (bytecode)
|
+---------------------+---------------------+
| | |
JVM for Windows JVM for Linux JVM for macOS
| | |
Windows machine code Linux machine code macOS machine code
The same .class file runs on every JVM, which is what makes Java platform independent.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 7 marks
Explain 1D and 2D array with the help of example explaining accessing and displaying the elements on an array.
Answer
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.
One-dimensional (1D) array
A 1D array is a single row of elements.
Declaration and creation: int[] marks = new int[5]; or with initial values int[] marks = {70, 85, 60, 90, 75};
Accessing: marks[0] is 70 and marks[4] is 75. The length is marks.length.
public class OneD {
public static void main(String[] args) {
int[] marks = {70, 85, 60, 90, 75};
marks[2] = 65; // modify an element
for (int i = 0; i < marks.length; i++) {
System.out.println("marks[" + i + "] = " + marks[i]);
}
for (int m : marks) { // enhanced for loop
System.out.print(m + " ");
}
}
}
Two-dimensional (2D) array
A 2D array is an array of arrays, organised as rows and columns (a matrix). An element is accessed with two indices: a[row][col].
Declaration: int[][] a = new int[2][3]; or int[][] a = {{1, 2, 3}, {4, 5, 6}};
public class TwoD {
public static void main(String[] args) {
int[][] a = {{1, 2, 3}, {4, 5, 6}};
System.out.println("a[1][2] = " + a[1][2]); // 6
for (int i = 0; i < a.length; i++) { // rows
for (int j = 0; j < a[i].length; j++) { // columns
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
Output:
a[1][2] = 6
1 2 3
4 5 6
Accessing and displaying a 1D array needs one loop, while a 2D array needs nested loops (outer for rows, inner for columns). Accessing an index outside the range throws ArrayIndexOutOfBoundsException.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 7 marks
Define method overriding. Explain predefined, user defined and static methods used in Java class.
Answer
Method overriding
Method overriding is defining a method in a subclass that has the same name, parameter list and compatible return type as a method in its superclass, so the subclass supplies its own implementation. It achieves runtime polymorphism: the method called is decided by the actual object type at run time. The overriding method cannot have weaker access, and static, final and private methods cannot be overridden. @Override is used to make the compiler check it.
class Animal { void sound() { System.out.println("Animal sound"); } }
class Dog extends Animal {
@Override
void sound() { System.out.println("Dog barks"); }
}
// Animal a = new Dog(); a.sound(); // prints "Dog barks"
Types of methods in a Java class
(a) Predefined (built-in) methods are already written in Java class libraries and are used directly by importing the class. Examples: Math.sqrt(16), String.length(), System.out.println().
double r = Math.sqrt(25); // 5.0
int n = "Pokhara".length(); // 7
(b) User-defined methods are written by the programmer to perform a specific task. They have a return type, name, parameters and body, and can be called many times (code reuse).
class Calc {
int add(int a, int b) { return a + b; }
}
// new Calc().add(3, 4) returns 7
(c) Static methods belong to the class rather than to any object. They are declared with static and called using the class name, with no object needed. They can access only static members directly. main is a static method.
class Util {
static int square(int x) { return x * x; }
}
// Util.square(5) returns 25
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 8 marks
Explain Java Strings and StringBuffer with examples. How does StringBuffer differ from String?
Answer
Java String
String is a class representing a sequence of characters. Strings are immutable: once created, the content cannot be changed; every modification creates a new object. String literals are kept in the String constant pool.
String s1 = "Hello"; // literal, in pool
String s2 = new String("Hello"); // new object in heap
String s3 = s1.concat(" World"); // new String; s1 unchanged
System.out.println(s3.length()); // 11
System.out.println(s3.toUpperCase()); // HELLO WORLD
System.out.println(s3.substring(0, 5)); // Hello
System.out.println(s1.equals(s2)); // true (same content)
System.out.println(s1 == s2); // false (different objects)
Common methods: length(), charAt(), substring(), indexOf(), equals(), compareTo(), replace(), trim().
StringBuffer
StringBuffer is a mutable sequence of characters. Its content can be modified in place without creating new objects. It is thread-safe because its methods are synchronized.
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // Hello World
sb.insert(5, ","); // Hello, World
sb.replace(0, 5, "Hi"); // Hi, World
sb.reverse(); // dlroW ,iH
sb.delete(0, 2); // oW ,iH
System.out.println(sb);
Other methods: capacity(), length(), deleteCharAt(), setCharAt(). The default capacity is 16 and it grows automatically.
Difference between String and StringBuffer
| String | StringBuffer |
|---|---|
| Immutable | Mutable |
| Every change creates a new object | Changes made in the same object |
| Slower for repeated modification | Faster for repeated modification |
| Uses String pool | Stored in heap only |
equals() compares content | equals() is not overridden (compares reference) |
Uses + operator for concatenation | Uses append() |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 7 marks
Define class. Create a class Employee having two constructor to set default and parameterized value to name designation and salary instance variable, and displayInfo() method. Also write main method inside same class and create two object for both constructor, finally call displayInfo() methtod to show result.
Answer
A class is a blueprint or template that defines the data (instance variables) and behaviour (methods) common to a group of objects. An object is an instance of a class.
public class Employee {
String name;
String designation;
double salary;
// default constructor
Employee() {
name = "Unknown";
designation = "Not Assigned";
salary = 0.0;
}
// parameterized constructor
Employee(String name, String designation, double salary) {
this.name = name;
this.designation = designation;
this.salary = salary;
}
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Designation: " + designation);
System.out.println("Salary: Rs " + salary);
}
public static void main(String[] args) {
Employee e1 = new Employee(); // default
Employee e2 = new Employee("Ram Sharma", "Manager", 55000.0); // parameterized
e1.displayInfo();
System.out.println();
e2.displayInfo();
}
}
Output:
Name: Unknown
Designation: Not Assigned
Salary: Rs 0.0
Name: Ram Sharma
Designation: Manager
Salary: Rs 55000.0
new Employee() calls the default constructor and new Employee("Ram Sharma", ...) calls the parameterized one, chosen by matching the arguments (constructor overloading).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 7 marks
Write a java program to create an interface Shape with a method calculateArea(). Implement this interface in two classes: Circle and Rectangle. Display the area of each shape.
Answer
An interface declares methods that implementing classes must define. Here Shape declares calculateArea(), and Circle and Rectangle implement it.
interface Shape {
double calculateArea();
}
class Circle implements Shape {
double radius;
Circle(double radius) { this.radius = radius; }
public double calculateArea() {
return Math.PI * radius * radius;
}
}
class Rectangle implements Shape {
double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double calculateArea() {
return length * width;
}
}
public class ShapeDemo {
public static void main(String[] args) {
Shape c = new Circle(7);
Shape r = new Rectangle(5, 4);
System.out.println("Area of Circle = " + c.calculateArea());
System.out.println("Area of Rectangle = " + r.calculateArea());
}
}
Output:
Area of Circle = 153.93804002589985
Area of Rectangle = 20.0
Check: circle area ; rectangle area . Interface methods are implicitly public, so the implementations must be declared public. Using the Shape reference to call each object's method is an example of polymorphism.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 7 marks
Write a java program with an abstract class Motor. Inherits this class from two other classes Car and Bus using the methods start_engine(), stop_engine() and display_engine() in both the classes.
Answer
An abstract class cannot be instantiated and may contain abstract methods (no body) that subclasses must implement.
abstract class Motor {
abstract void start_engine();
abstract void stop_engine();
abstract void display_engine();
}
class Car extends Motor {
void start_engine() { System.out.println("Car engine started."); }
void stop_engine() { System.out.println("Car engine stopped."); }
void display_engine() { System.out.println("Car has a 1500 cc petrol engine."); }
}
class Bus extends Motor {
void start_engine() { System.out.println("Bus engine started."); }
void stop_engine() { System.out.println("Bus engine stopped."); }
void display_engine() { System.out.println("Bus has a 6000 cc diesel engine."); }
}
public class MotorDemo {
public static void main(String[] args) {
Motor m1 = new Car();
Motor m2 = new Bus();
m1.start_engine();
m1.display_engine();
m1.stop_engine();
m2.start_engine();
m2.display_engine();
m2.stop_engine();
}
}
Output:
Car engine started.
Car has a 1500 cc petrol engine.
Car engine stopped.
Bus engine started.
Bus has a 6000 cc diesel engine.
Bus engine stopped.
Car and Bus inherit Motor using extends and give their own implementation of all three abstract methods. Writing new Motor() would be a compile-time error.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 8 marks
Define Inheritance. Does java support multiple inheritance? If yes justify with code example.
Answer
Inheritance
Inheritance is the OOP mechanism by which a class (subclass or child) acquires the fields and methods of another class (superclass or parent), using the extends keyword. It promotes code reuse, method overriding and an "is-a" relationship.
class Person { String name = "Sita"; void eat() { System.out.println("eating"); } }
class Student extends Person { void study() { System.out.println("studying"); } }
Does Java support multiple inheritance?
Java does not support multiple inheritance through classes: a class can extend only one class. This avoids the diamond problem, where two parents have the same method and the compiler cannot decide which to inherit. However, Java does support multiple inheritance of type through interfaces: a class can implement any number of interfaces, and an interface can extend several interfaces. So the answer is yes, via interfaces.
Code example
interface Printable {
void print();
}
interface Showable {
void show();
}
class Document implements Printable, Showable { // multiple inheritance
public void print() { System.out.println("Printing document"); }
public void show() { System.out.println("Showing document"); }
}
public class MultipleDemo {
public static void main(String[] args) {
Document d = new Document();
d.print();
d.show();
}
}
Output:
Printing document
Showing document
Document inherits the abstract methods of both Printable and Showable. If two interfaces declare the same method, the class provides one implementation, so there is no ambiguity. With default methods of the same name, the class must override and may call Printable.super.method() to choose one.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 8 marks
Why do we need multithreading programming? Explain with code example one thread by extending Thread class and another by implementing Runnable interface.
Answer
Need for multithreading
A thread is a lightweight unit of execution within a process. Multithreading runs several threads concurrently in one program. It is needed because it:
- makes better use of the CPU, since one thread can run while another waits for I/O, so idle time is reduced;
- keeps applications responsive (the GUI stays active while a download or calculation runs in the background);
- allows tasks to run in parallel on multi-core processors, improving performance;
- shares memory within a process, so threads are cheaper to create and switch than processes;
- suits servers that handle many clients simultaneously.
Thread by extending the Thread class
Extend Thread, override run(), create the object and call start().
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println("MyThread: " + i);
try { Thread.sleep(200); } catch (InterruptedException e) { }
}
}
}
Thread by implementing Runnable
Implement Runnable, define run(), pass the object to a Thread constructor and call start(). This is preferred because the class can still extend another class.
class MyTask implements Runnable {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println("MyTask: " + i);
try { Thread.sleep(200); } catch (InterruptedException e) { }
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread();
Thread t2 = new Thread(new MyTask());
t1.start();
t2.start();
}
}
Both threads run concurrently, so the output lines interleave (for example MyThread: 1, MyTask: 1, MyThread: 2, MyTask: 2, ...); the exact order may vary. Calling run() directly instead of start() would not create a new thread.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 7 marks
Define exception. Explain about creating your own exception clauses.
Answer
Exception
An exception is an abnormal event or runtime error that disrupts the normal flow of a program's instructions, such as dividing by zero, accessing an invalid array index or opening a missing file. Java handles exceptions with try, catch, finally, throw and throws. All exceptions are subclasses of Throwable; checked exceptions derive from Exception and unchecked ones from RuntimeException.
Creating your own exception (user-defined exception)
When the built-in exceptions do not describe an application-specific error, we create our own class by extending Exception (checked) or RuntimeException (unchecked). Steps:
- Create a class that extends
Exception. - Provide a constructor that passes a message to
super(message). - Use
throw new MyException("...")where the error condition occurs. - Declare it with
throwsin the method signature if it is checked, and handle it withtry-catch.
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}
public class VoteDemo {
static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age " + age + " is not eligible to vote");
}
System.out.println("Eligible to vote");
}
public static void main(String[] args) {
try {
checkAge(20);
checkAge(15);
} catch (InvalidAgeException e) {
System.out.println("Caught: " + e.getMessage());
} finally {
System.out.println("Finished");
}
}
}
Output:
Eligible to vote
Caught: Age 15 is not eligible to vote
Finished
The finally block always executes, whether or not an exception occurs.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 8 marks
What are Wrapper class Explain Auto boxing and unboxing with an example.
Answer
Wrapper classes
Wrapper classes are classes in java.lang that wrap a primitive value in an object. Every primitive type has one:
| Primitive | Wrapper |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
They are needed because collections such as ArrayList store only objects, and they provide useful methods like Integer.parseInt("25"), Integer.MAX_VALUE and Double.valueOf().
Autoboxing and unboxing
Autoboxing is the automatic conversion of a primitive into its wrapper object by the compiler. Unboxing is the automatic conversion of a wrapper object back into its primitive. Both were introduced in Java 5.
import java.util.ArrayList;
public class BoxDemo {
public static void main(String[] args) {
int a = 10;
Integer obj = a; // autoboxing: int -> Integer
int b = obj; // unboxing: Integer -> int
System.out.println(obj + " " + b);
ArrayList<Integer> list = new ArrayList<>();
list.add(5); // autoboxing 5 to Integer
int x = list.get(0); // unboxing to int
System.out.println(x + obj); // 15
}
}
Output:
10 10
15
Before Java 5 this had to be done manually: Integer obj = Integer.valueOf(a); and int b = obj.intValue();. Unboxing a null wrapper throws NullPointerException.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 8 marks
What is JDBC Driver? Write steps to connect database from java application.
Answer
JDBC driver
JDBC (Java Database Connectivity) is a Java API (java.sql package) for connecting to relational databases and executing SQL. A JDBC driver is the software component that implements the JDBC interfaces for a specific database and translates Java calls into the database's own protocol. There are four types: Type 1 (JDBC-ODBC bridge), Type 2 (native API), Type 3 (network protocol) and Type 4 (thin, pure Java driver, the most widely used, e.g. MySQL Connector/J).
Steps to connect to a database
- Import the packages:
import java.sql.*; - Load and register the driver:
Class.forName("com.mysql.cj.jdbc.Driver");(optional in JDBC 4 and later, because the driver on the classpath registers itself). - Establish the connection using
DriverManager.getConnection(url, user, password). - Create a Statement (
StatementorPreparedStatement) from the connection. - Execute the SQL query:
executeQuery()for SELECT orexecuteUpdate()for INSERT, UPDATE, DELETE. - Process the ResultSet by looping with
rs.next(). - Close the connection (and statement and result set) to release resources.
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/college";
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // step 2
Connection con = DriverManager.getConnection(url, "root", "pass"); // step 3
Statement st = con.createStatement(); // step 4
ResultSet rs = st.executeQuery("SELECT id, name FROM student"); // step 5
while (rs.next()) { // step 6
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
con.close(); // step 7
} catch (Exception e) {
System.out.println(e);
}
}
}
The MySQL connector JAR must be on the classpath, and the database college with table student must exist.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 7 marks
Write down the use of JavaFX with architecture diagram. Write down the code to display a greeting message in your first JavaFX Application.
Answer
Use of JavaFX
JavaFX is a Java library for building rich desktop and cross-platform graphical user interface (GUI) applications. It replaces Swing/AWT and is used for:
- creating windows, forms, buttons, tables, charts and menus;
- styling with CSS and designing layouts with FXML;
- 2D/3D graphics, animation, audio and video;
- event-driven applications that run on Windows, Linux and macOS.
Architecture
+--------------------------------------------------+
| JavaFX Public APIs / Scene Graph |
| (Application, Stage, Scene, Nodes, Layouts) |
+--------------------------------------------------+
| Glass Windowing Toolkit | Quantum Toolkit |
| Prism (rendering) | Media | Web engines |
+--------------------------------------------------+
| Java Virtual Machine (JVM) |
+--------------------------------------------------+
| Operating System / Graphics hardware |
+--------------------------------------------------+
- Scene graph: a tree of nodes (controls, shapes, layouts) displayed in a scene.
- Stage: the top-level window; Scene: the container of the scene graph content.
- Prism: graphics rendering engine (hardware or software accelerated).
- Glass Windowing Toolkit: connects JavaFX to the native OS for windows and events.
- Quantum Toolkit: ties Prism and Glass together.
- Media and WebView engines: audio/video playback and embedded web content.
First JavaFX application: greeting message
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class GreetingApp extends Application {
@Override
public void start(Stage stage) {
Label greeting = new Label("Hello! Welcome to JavaFX.");
StackPane root = new StackPane(greeting);
Scene scene = new Scene(root, 350, 150);
stage.setTitle("My First JavaFX App");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
launch() starts the JavaFX runtime, which calls start(Stage). The label is placed in a layout pane, the pane in a scene, and the scene on the stage window.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 5 marks
Write short notes on: Abstraction and Polymorphism
Answer
Abstraction is the OOP concept of hiding implementation details and showing only the essential features to the user. In Java it is achieved with abstract classes and interfaces. For example, a driver uses the brake pedal without knowing the braking mechanism.
abstract class Vehicle { abstract void run(); }
class Bike extends Vehicle { void run() { System.out.println("Bike runs"); } }
It reduces complexity, increases security and lets implementation change without affecting users.
Polymorphism means "many forms": one name or interface behaving differently in different situations. Java has two kinds:
- Compile-time (static) polymorphism through method overloading: same method name, different parameters, resolved by the compiler. For example
add(int, int)andadd(double, double). - Runtime (dynamic) polymorphism through method overriding: a superclass reference calls the subclass's version, resolved at run time.
class Shape { void draw() { System.out.println("Shape"); } }
class Circle extends Shape { void draw() { System.out.println("Circle"); } }
// Shape s = new Circle(); s.draw(); // prints Circle
A real-world example is a person who is a teacher at college, a customer in a shop and a son at home: one person, different behaviour in each role.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 5 marks
Write short notes on: Package
Answer
A package is a namespace that groups related classes, interfaces and sub-packages together, like a folder in a file system. It is declared at the top of a source file with the package keyword.
package mycollege.util;
public class Helper {
public static void greet() { System.out.println("Hello from package"); }
}
It is used from another file with import mycollege.util.Helper; (or mycollege.util.*).
Types:
- Built-in packages:
java.lang(imported automatically),java.util,java.io,java.sql,java.awt. - User-defined packages: created by the programmer.
Advantages:
- avoids name conflicts, since classes in different packages can share a name;
- organises large programs and makes classes easy to find;
- provides access protection (package-private members);
- promotes reusability.
Compile with javac -d . Helper.java, which creates the matching directory structure mycollege/util/Helper.class.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 Spring · 5 marks
Write short notes on: Collection Frameworks
Answer
The Java Collections Framework (in java.util) is a unified architecture of interfaces, implementation classes and algorithms for storing and manipulating groups of objects. It replaces fixed-size arrays with dynamically growing data structures.
Core interfaces:
Collectionis the root interface. Its main sub-interfaces areList,SetandQueue.Mapstores key-value pairs and is separate fromCollection.
Main implementations:
| Interface | Classes | Features |
|---|---|---|
| List | ArrayList, LinkedList, Vector | ordered, allows duplicates, index access |
| Set | HashSet, LinkedHashSet, TreeSet | no duplicates; TreeSet keeps sorted order |
| Queue | PriorityQueue, ArrayDeque | FIFO or priority ordering |
| Map | HashMap, LinkedHashMap, TreeMap | unique keys mapped to values |
import java.util.*;
public class CollDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Ram"); list.add("Sita"); list.add("Ram");
Set<String> set = new HashSet<>(list); // duplicates removed
Map<Integer, String> map = new HashMap<>();
map.put(1, "Hari");
System.out.println(list + " " + set.size() + " " + map);
}
}
The Collections utility class provides algorithms such as sort(), reverse() and max(). Advantages are reduced programming effort, reusable tested code, dynamic size and better performance.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 8 marks
Describe the Structure of Java Programming and concepts of OOP with real world examples.
Answer
Structure of a Java program
A Java program is organised in these sections, in order:
- Documentation section: optional comments (
//,/* */,/** */). - Package statement: optional,
package mypack; - Import statements: bring in other classes, e.g.
import java.util.Scanner; - Class definition: one or more classes, with variables and methods.
- Main method:
public static void main(String[] args), the entry point.
// Documentation: simple greeting program
package demo; // package statement
import java.util.Scanner; // import statement
public class Greeting { // class definition
String msg = "Hello, "; // variable
void show(String name) { // method
System.out.println(msg + name);
}
public static void main(String[] args) { // main method
Scanner sc = new Scanner(System.in);
String n = sc.nextLine();
new Greeting().show(n);
}
}
Concepts of OOP with real-world examples
Class and object: a class is a blueprint and an object is an instance. Car is a class; my red Toyota is an object.
Encapsulation: wrapping data and methods in one unit and hiding data with private plus getters/setters. A bank account hides its balance and lets you change it only via deposit and withdraw.
Inheritance: a class acquires properties of another. Dog and Cat inherit from Animal, as a child inherits traits from parents.
Polymorphism: one interface, many forms. The same "play" button plays music, video or a game depending on the app.
Abstraction: showing essential features and hiding details. An ATM lets you withdraw cash without showing the internal banking process.
Together these make programs modular, reusable, secure and easy to maintain.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 7 marks
Define Array. Create a class SortAge and two methods ascending(int[] arr) and descending(int[] arr) to sort and display an array in ascending and descending order. Create another class AgeInput with main method and take an age of 10 person from keyboard and call necessary methods.
Answer
Array
An array is a fixed-size, ordered collection of elements of the same data type, stored in contiguous memory locations and accessed using a zero-based index, e.g. int[] age = new int[10];.
Program
import java.util.Scanner;
class SortAge {
void ascending(int[] arr) {
int[] a = arr.clone();
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
}
}
System.out.print("Ascending : ");
for (int x : a) System.out.print(x + " ");
System.out.println();
}
void descending(int[] arr) {
int[] a = arr.clone();
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] < a[j + 1]) {
int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
}
}
System.out.print("Descending: ");
for (int x : a) System.out.print(x + " ");
System.out.println();
}
}
public class AgeInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] ages = new int[10];
for (int i = 0; i < 10; i++) {
System.out.print("Enter age of person " + (i + 1) + ": ");
ages[i] = sc.nextInt();
}
SortAge s = new SortAge();
s.ascending(ages);
s.descending(ages);
}
}
For the input 25 18 40 33 21 60 12 45 30 28 the output is:
Ascending : 12 18 21 25 28 30 33 40 45 60
Descending: 60 45 40 33 30 28 25 21 18 12
Both methods use bubble sort on a copy, so the original array is not disturbed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 7 marks
What are the different types of methods in Java? Explain each type with the help of examples.
Answer
A method is a named block of code that performs a task and can be reused. Syntax: returnType name(parameters) { body }. Methods in Java are classified as follows.
(a) Predefined (library) methods are supplied by the Java API and called directly.
double r = Math.pow(2, 3); // 8.0
String s = "java".toUpperCase(); // JAVA
(b) User-defined methods are written by the programmer. They may or may not take parameters and may or may not return a value, giving four forms:
class Demo {
void hello() { System.out.println("Hello"); } // no param, no return
void greet(String n) { System.out.println("Hi " + n); } // param, no return
int five() { return 5; } // no param, returns
int add(int a, int b) { return a + b; } // param, returns
}
(c) Static methods belong to the class and are called as ClassName.method() without creating an object.
class MathUtil { static int square(int x) { return x * x; } }
// MathUtil.square(4) returns 16
(d) Instance methods are non-static and need an object: new Demo().add(2, 3) returns 5.
(e) Abstract methods have no body and are declared with abstract in an abstract class or interface; subclasses must implement them.
abstract class Shape { abstract double area(); }
(f) Final methods cannot be overridden by subclasses: final void show() { }.
(g) Overloaded and overridden methods: overloaded methods share a name but differ in parameters (same class); overridden methods redefine a superclass method in a subclass.
(h) Constructors are special methods with the class name and no return type, used to initialise objects.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 8 marks
What is a Constructor? Write a java program to find the Area of Circle using Constructor.
Answer
Constructor
A constructor is a special member method that has the same name as its class and no return type. It is invoked automatically when an object is created with new, and is used to initialise the object's instance variables. If none is written, the compiler supplies a default no-argument constructor. Types: default (no-argument), parameterized, and copy constructor. Constructors can be overloaded.
Program: area of a circle using a constructor
Area of a circle is .
public class Circle {
double radius;
double area;
Circle(double r) { // parameterized constructor
radius = r;
area = Math.PI * radius * radius;
}
void display() {
System.out.println("Radius = " + radius);
System.out.println("Area = " + area);
}
public static void main(String[] args) {
Circle c = new Circle(5);
c.display();
}
}
Output (for , ):
Radius = 5.0
Area = 78.53981633974483
The constructor receives the radius when new Circle(5) executes, and computes the area at the time of object creation.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 7 marks
What are visibility modes in Java? How different modes work in class member?
Answer
Visibility modes (access modifiers) control which classes can access a class, method or variable. Java has four levels.
| Modifier | Same class | Same package | Subclass in other package | Other packages |
|---|---|---|---|---|
private | Yes | No | No | No |
| default (no keyword) | Yes | Yes | No | No |
protected | Yes | Yes | Yes (through inheritance) | No |
public | Yes | Yes | Yes | Yes |
private: accessible only inside the declaring class. Used to hide data (encapsulation).
default (package-private): used when no modifier is written; accessible within the same package only.
protected: accessible within the package and in subclasses even if they are in different packages.
public: accessible from anywhere.
package pack1;
public class A {
private int a = 1;
int b = 2; // default
protected int c = 3;
public int d = 4;
public int getA() { return a; } // access private via a public method
}
package pack2;
import pack1.A;
public class B extends A {
void test() {
// System.out.println(a); // error: private
// System.out.println(b); // error: default, different package
System.out.println(c); // OK: protected via inheritance
System.out.println(d); // OK: public
}
}
Top-level classes can be only public or default; private and protected apply to members (and nested classes).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 8 marks
Define Inheritance with its types. How do you create multiple inheritance in java? Explain with code example.
Answer
Inheritance
Inheritance is the mechanism by which a subclass acquires the fields and methods of a superclass using extends. It provides code reuse and supports overriding and polymorphism.
Types of inheritance
- Single: one subclass extends one superclass.
B extends A. - Multilevel: a chain of inheritance.
C extends B,B extends A. - Hierarchical: several subclasses extend one superclass.
B extends A,C extends A. - Multiple: a class inherits from more than one parent. Not supported with classes in Java; achieved through interfaces.
- Hybrid: a combination of the above; in Java possible only using interfaces.
Single: A -> B Multilevel: A -> B -> C
Hierarchical: A -> B, A -> C
Multiple: A, B -> C (via interfaces)
Multiple inheritance in Java
Java does not allow a class to extend two classes, to avoid the diamond problem (ambiguity when both parents define the same method). We create it using interfaces: a class implements multiple interfaces, using implements.
interface Father {
void skills();
}
interface Mother {
void talents();
}
class Child implements Father, Mother {
public void skills() { System.out.println("Child has father's skills"); }
public void talents() { System.out.println("Child has mother's talents"); }
}
public class Main {
public static void main(String[] args) {
Child c = new Child();
c.skills();
c.talents();
}
}
Output:
Child has father's skills
Child has mother's talents
Child inherits from both Father and Mother, which is multiple inheritance of type, and since interface methods have no implementation there is no ambiguity.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 7 marks
Compare Method Overriding and Method Overloading with an example program.
Answer
| Method Overloading | Method Overriding |
|---|---|
| Same method name, different parameter list (number, type or order) in the same class | Same name, same parameters and compatible return type in subclass and superclass |
| Compile-time (static) polymorphism | Runtime (dynamic) polymorphism |
| No inheritance needed | Inheritance is required |
| Return type alone cannot differentiate | Return type must be same or covariant |
| Access modifier may be anything | Access cannot be more restrictive |
Can be static or final | static, final and private methods cannot be overridden |
| Improves readability | Gives a specific implementation of an inherited method |
Example program
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; } // overloading
int add(int a, int b, int c) { return a + b + c; } // overloading
}
class Animal {
void sound() { System.out.println("Animal makes a sound"); }
}
class Dog extends Animal {
@Override
void sound() { System.out.println("Dog barks"); } // overriding
}
public class Demo {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(2, 3)); // 5
System.out.println(c.add(2.5, 3.5)); // 6.0
System.out.println(c.add(1, 2, 3)); // 6
Animal a = new Dog();
a.sound(); // Dog barks
}
}
Output:
5
6.0
6
Dog barks
The three add calls are resolved at compile time from their arguments (overloading), whereas a.sound() is resolved at run time from the actual object Dog (overriding).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 8 marks
Define the uses of package and interface. Write down the steps to create a package with code example.
Answer
Uses of a package
- Groups related classes and interfaces, so large projects are well organised.
- Avoids naming conflicts, because the same class name can exist in different packages.
- Gives access control through package-private and protected members.
- Makes code reusable and easy to locate and maintain.
Uses of an interface
- Defines a contract of methods that implementing classes must provide, giving 100% abstraction.
- Enables multiple inheritance in Java, since a class can implement many interfaces.
- Achieves loose coupling and runtime polymorphism (code depends on the interface, not the implementation).
- Gives a common type to unrelated classes, e.g.
Comparable,Runnable.
Steps to create a package
- Choose a package name (lowercase, e.g.
college.math). - Declare it as the first statement of every source file:
package college.math; - Write the public classes inside that file.
- Compile with
-dso the directory structure is created:javac -d . Calculator.javaproducescollege/math/Calculator.class. - Import and use the package in another program, then compile and run it.
// File: Calculator.java
package college.math;
public class Calculator {
public int add(int a, int b) { return a + b; }
public int multiply(int a, int b) { return a * b; }
}
// File: Main.java
import college.math.Calculator;
public class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println("Sum = " + c.add(4, 6));
System.out.println("Product = " + c.multiply(4, 6));
}
}
Compile and run: javac -d . Calculator.java, then javac Main.java, then java Main.
Output:
Sum = 10
Product = 24
Classes and methods used from another package must be public; the package folder must be on the classpath.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 7 marks
Define collection framework. Explain with code example how you create a dynamic list and a unique list.
Answer
The Collections Framework is a unified architecture in the java.util package for storing, retrieving and manipulating groups of objects. It provides:
- Interfaces:
Collection,List,Set,Queue,DequeandMap(Map is part of the framework but does not extendCollection). - Implementations:
ArrayList,LinkedList,Vector,HashSet,LinkedHashSet,TreeSet,PriorityQueue,HashMap,TreeMap, etc. - Algorithms: static methods in
Collectionssuch assort(),reverse(),shuffle(),binarySearch(),max().
Its advantages are reduced programming effort, reusable ready-made data structures, good performance, and a common API so that implementations can be swapped easily.
Dynamic list. ArrayList is a resizable array. It grows automatically when elements are added, keeps insertion order and allows duplicates.
Unique list. HashSet (or LinkedHashSet to keep insertion order, TreeSet for sorted order) stores only distinct elements; adding a duplicate is ignored.
import java.util.*;
public class CollectionDemo {
public static void main(String[] args) {
// Dynamic list: size grows as needed, duplicates allowed
List<String> list = new ArrayList<>();
list.add("Ram");
list.add("Sita");
list.add("Ram"); // duplicate is kept
list.remove("Sita");
System.out.println("List: " + list); // [Ram, Ram]
System.out.println("Size: " + list.size()); // 2
// Unique list: duplicates are rejected
Set<String> set = new LinkedHashSet<>();
set.add("Ram");
set.add("Sita");
boolean added = set.add("Ram"); // false, already present
System.out.println("Set: " + set); // [Ram, Sita]
System.out.println("Duplicate added? " + added);
}
}
Output:
List: [Ram, Ram]
Size: 2
Set: [Ram, Sita]
Duplicate added? false
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 7 marks
Write a java program to create two threads and execute simultaneously.
Answer
In Java a thread can be created by extending Thread or by implementing Runnable. When start() is called on two thread objects, the JVM schedules both, so their run() methods execute concurrently and their output is interleaved.
class FirstThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("First thread: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
class SecondThread implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Second thread: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class TwoThreads {
public static void main(String[] args) {
Thread t1 = new FirstThread();
Thread t2 = new Thread(new SecondThread());
t1.start(); // both threads now run simultaneously
t2.start();
}
}
Explanation. start() (not run()) creates a new call stack for each thread. Thread.sleep(500) pauses the current thread for 500 ms, giving the other thread the CPU, so the output alternates, for example:
First thread: 1
Second thread: 1
Second thread: 2
First thread: 2
...
The exact order may differ between runs because thread scheduling is controlled by the operating system and the JVM.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 8 marks
Write a java program to create user Define exception to throw Negative Value Exception if the user enters negative value.
Answer
A user-defined (custom) exception is created by extending Exception (checked) or RuntimeException (unchecked). It is raised with throw and handled with try-catch.
import java.util.Scanner;
class NegativeValueException extends Exception {
NegativeValueException(String message) {
super(message);
}
}
public class NegativeTest {
static void check(int value) throws NegativeValueException {
if (value < 0) {
throw new NegativeValueException("Negative value entered: " + value);
}
System.out.println("You entered a valid value: " + value);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
try {
check(n);
} catch (NegativeValueException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
sc.close();
}
}
}
Working.
NegativeValueExceptionextendsExceptionand passes its message to the superclass constructor.check()declaresthrows NegativeValueExceptionand usesthrow new ...when the value is below zero.maincatches the exception and prints the message.
Sample runs:
Enter a number: 25
You entered a valid value: 25
Enter a number: -7
Exception caught: Negative value entered: -7
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 8 marks
What is a Java Exception? Explain its Types.
Answer
An exception is an abnormal event or runtime problem that disrupts the normal flow of a program's instructions (for example dividing by zero or opening a missing file). In Java an exception is an object of a class derived from java.lang.Throwable; when it occurs, the JVM creates the object and throws it. If it is not handled, the program terminates. Java handles exceptions with try, catch, finally, throw and throws.
Hierarchy. Object -> Throwable -> (Error, Exception); Exception -> (RuntimeException and other checked exceptions).
Types of exceptions
(a) Checked exceptions. Checked by the compiler at compile time. The programmer must either handle them with try-catch or declare them with throws; otherwise the code does not compile. They are subclasses of Exception other than RuntimeException. Examples: IOException, FileNotFoundException, SQLException, ClassNotFoundException, InterruptedException.
(b) Unchecked exceptions. Subclasses of RuntimeException. They occur at run time and the compiler does not force handling. They normally indicate programming mistakes. Examples: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException, ClassCastException.
(c) Errors. Subclasses of Error; they represent serious problems of the JVM or environment that an application should not try to catch, such as OutOfMemoryError, StackOverflowError, VirtualMachineError.
Built-in vs user-defined. Exceptions supplied by Java are built-in; programmers may also write their own by extending Exception or RuntimeException.
public class ExceptionTypes {
public static void main(String[] args) {
try {
int a = 10 / 0; // unchecked
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
}
try {
new java.io.FileReader("missing.txt"); // checked
} catch (java.io.FileNotFoundException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 8 marks
What is JDBC? How can we connect Java application to any database?
Answer
JDBC (Java Database Connectivity) is a Java API in the packages java.sql and javax.sql that lets Java programs connect to relational databases, send SQL statements and process the results. It gives one common interface; a vendor-specific driver (for example MySQL Connector/J, Oracle's ojdbc, PostgreSQL driver) translates calls into the database's own protocol. Thus the same code works with different databases by changing only the driver and URL.
Steps to connect a Java application to a database
- Import packages:
java.sql.*. - Load/register the driver:
Class.forName("com.mysql.cj.jdbc.Driver");(optional in JDBC 4+ if the driver jar is on the classpath, but it must be added to the classpath). - Establish the connection:
DriverManager.getConnection(url, user, password)where the URL has the formjdbc:<subprotocol>://host:port/database. - Create a statement:
Statement,PreparedStatementorCallableStatement. - Execute the query:
executeQuery()for SELECT (returnsResultSet),executeUpdate()for INSERT/UPDATE/DELETE. - Process the result: loop over
ResultSetwithnext()andgetXxx(). - Close the resources:
ResultSet,Statement,Connection.
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/college";
String user = "root";
String pass = "secret";
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 id, name FROM student")) {
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
To connect to another database, only the driver class, driver jar and URL change, for example jdbc:oracle:thin:@localhost:1521:xe for Oracle or jdbc:postgresql://localhost:5432/college for PostgreSQL.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 5 marks
Write short notes on: JavaFX architecture
Answer
JavaFX is the Java framework for building rich desktop and media-rich client applications. Its architecture is layered:
- Scene graph: the application UI is a tree of nodes (controls, layouts, shapes, images, media). Each node has a parent except the root; this is the public API through which the developer works.
- Stage and Scene:
Stageis the top-level window (the primary stage is passed tostart()); aSceneholds the scene graph and is set on a stage.Applicationis the base class; its lifecycle methods areinit(),start(Stage)andstop(). - Java public APIs:
javafx.scene,javafx.stage,javafx.scene.control,javafx.scene.layout, animation, CSS styling, FXML, properties and bindings, and event handling. - Quantum Toolkit: connects Prism and Glass Windowing Toolkit and manages rendering threads.
- Prism: the graphics rendering engine, using hardware acceleration (Direct3D, OpenGL) with software fallback.
- Glass Windowing Toolkit: platform-dependent layer that provides windows, timers and event queue by talking to the operating system.
- Media Engine (audio and video) and Web Engine (embedded HTML through
WebView, based on WebKit). - JVM at the bottom, on which everything runs. UI changes occur on the JavaFX Application Thread.
public class Hello extends javafx.application.Application {
public void start(javafx.stage.Stage stage) {
stage.setScene(new javafx.scene.Scene(new javafx.scene.control.Label("Hello"), 200, 100));
stage.show();
}
public static void main(String[] a) { launch(a); }
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 5 marks
Write short notes on: Thread priority
Answer
Thread priority is an integer from 1 to 10 that tells the thread scheduler how important a thread is. A higher-priority thread is given preference for CPU time, but this is only a hint: actual scheduling depends on the operating system and JVM, so priority never guarantees execution order.
The Thread class defines three constants:
| Constant | Value |
|---|---|
Thread.MIN_PRIORITY | 1 |
Thread.NORM_PRIORITY | 5 (default) |
Thread.MAX_PRIORITY | 10 |
A new thread inherits the priority of the thread that creates it. Methods: setPriority(int) (throws IllegalArgumentException outside 1 to 10) and getPriority().
class P extends Thread {
public void run() {
System.out.println(getName() + " priority = " + getPriority());
}
public static void main(String[] args) {
P t1 = new P();
P t2 = new P();
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}
Here t1 runs with priority 1 and t2 with priority 10, so t2 is likely, but not certain, to get CPU time first.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Fall · 5 marks
Write short notes on: Use of finalize
Answer
finalize() is a method of the Object class, declared as protected void finalize() throws Throwable. The garbage collector calls it on an object just before reclaiming its memory, so it can be overridden to release resources (open files, network or database connections) or to do clean-up.
class Demo {
protected void finalize() {
System.out.println("Object is being garbage collected");
}
public static void main(String[] args) {
Demo d = new Demo();
d = null; // object becomes unreachable
System.gc(); // requests garbage collection
}
}
Points to note
- It is called at most once per object, by the garbage collector, not by the programmer.
- There is no guarantee of when (or whether) it will run, and
System.gc()is only a request. - Exceptions thrown inside it are ignored.
- It is not like a C++ destructor. Since Java 9 it is deprecated (and deprecated for removal in later versions); preferred alternatives are
try-with-resourceswithAutoCloseable, orjava.lang.ref.Cleaner. - It is different from
final(a modifier) andfinally(a block that always runs after try-catch).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 8 marks
Define inheritance and interface. Write down the code to create multiple inheritance in java.
Answer
Inheritance is the mechanism by which a class (subclass/child) acquires the fields and methods of another class (superclass/parent) using the extends keyword. It supports code reuse and run-time polymorphism and models an "is-a" relationship.
Interface is a reference type that contains abstract method declarations (plus constants, default, static and private methods since Java 8/9). It defines a contract that a class fulfils with implements. A class may implement any number of interfaces, and an interface may extend several interfaces.
Multiple inheritance. Java does not allow a class to extend more than one class (to avoid ambiguity such as the diamond problem), but multiple inheritance of type is achieved through interfaces.
interface Printable {
void print();
}
interface Showable {
void show();
}
class Document implements Printable, Showable { // multiple inheritance
public void print() {
System.out.println("Printing the document");
}
public void show() {
System.out.println("Showing the document");
}
}
// An interface can also extend several interfaces
interface Both extends Printable, Showable { }
public class MultipleInheritance {
public static void main(String[] args) {
Document d = new Document();
d.print();
d.show();
Printable p = d; // polymorphic reference
p.print();
}
}
Output:
Printing the document
Showing the document
Printing the document
If two interfaces declare the same method, the class provides a single implementation, so no ambiguity arises. If they have the same default method, the class must override it.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 7 marks
Differentiate error and exceptions. How can exceptions be handled in java? Explain with suitable example.
Answer
Difference between error and exception
| Error | Exception |
|---|---|
Subclass of java.lang.Error | Subclass of java.lang.Exception |
| Serious problem in the JVM or system resources | Condition arising from the program or its input |
| Normally cannot be recovered; should not be caught | Can be caught and handled |
| Always unchecked | Checked or unchecked |
| Occurs at run time only | Checked ones are detected at compile time |
Examples: OutOfMemoryError, StackOverflowError | Examples: IOException, ArithmeticException |
Handling exceptions in Java. Java uses five keywords:
try: block containing code that may throw an exception.catch: block that handles a particular exception type; several catch blocks (or multi-catchA | B) may follow a try.finally: block that always runs (for clean-up), whether or not an exception occurs.throw: explicitly throws an exception object.throws: declares in a method signature the checked exceptions it may pass to its caller.
public class HandleDemo {
static int divide(int a, int b) throws ArithmeticException {
if (b == 0) throw new ArithmeticException("Divisor is zero");
return a / b;
}
public static void main(String[] args) {
try {
int[] arr = new int[3];
System.out.println(divide(10, 2)); // 5
System.out.println(divide(10, 0)); // throws
arr[5] = 1; // never reached
} catch (ArithmeticException e) {
System.out.println("Arithmetic problem: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Bad index: " + e.getMessage());
} finally {
System.out.println("finally block executed");
}
}
}
Output:
5
Arithmetic problem: Divisor is zero
finally block executed
When the exception occurs, control leaves the try block at once, the matching catch block runs, then finally runs and execution continues normally.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 8 marks
Differences between java applet and java application program. Write the steps to execute the applet.
Answer
Differences between Java applet and Java application
| Java applet | Java application |
|---|---|
Embedded in a web page and run by a browser or appletviewer | Standalone program run by the java command |
Extends java.applet.Applet (or JApplet) | Ordinary class, no required superclass |
No main() method; life-cycle methods init(), start(), stop(), destroy(), paint() are used | Execution starts at public static void main(String[] args) |
| Runs under a restricted security sandbox (no local file access, no connections other than to its origin server) | Has full access to the system's files and network |
Needs an HTML file with the <applet> tag | Needs no HTML file |
Output is graphical, via paint(Graphics) | Output is usually console or GUI |
| Loaded over network; depends on browser support | Runs locally on installed JVM |
(Applets are deprecated since Java 9 and removed in later versions, but remain in the syllabus.)
Steps to execute an applet
- Write the source code, e.g.
HelloApplet.java:
import java.applet.Applet;
import java.awt.Graphics;
public class HelloApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello Applet", 50, 50);
}
}
- Compile it:
javac HelloApplet.java, which producesHelloApplet.class. - Create an HTML file
hello.htmlthat refers to the class:
<html>
<body>
<applet code="HelloApplet.class" width="300" height="200"></applet>
</body>
</html>
- Run it with the applet viewer:
appletviewer hello.html(or open the page in an applet-enabled browser).
Alternatively, put the <applet> tag in a comment at the top of the Java file, /* <applet code="HelloApplet" width=300 height=200></applet> */, and run appletviewer HelloApplet.java.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 7 marks
Why multi-threading is important in java programming? Create two classes the first by extending Thread class which will print 10 even numbers and second by implementing Runnable interface which will print 20 odd numbers in every 100ms. Create third class to call them and display result in the console.
Answer
Importance of multithreading
- Several tasks run concurrently within one program, so the application stays responsive (for example a GUI keeps responding while a file downloads).
- It uses the CPU better: while one thread waits for I/O, others run, and multi-core processors are exploited.
- Threads share the same memory, so they are lightweight and cheaper to create and switch than processes.
- It simplifies modelling of independent activities such as servers handling many clients, animation and background jobs.
Program
class EvenThread extends Thread {
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Even: " + (2 * i));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
class OddRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 20; i++) {
System.out.println("Odd: " + (2 * i - 1));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class EvenOddMain {
public static void main(String[] args) {
Thread even = new EvenThread();
Thread odd = new Thread(new OddRunnable());
even.start();
odd.start();
}
}
Explanation. EvenThread extends Thread and prints the first 10 even numbers (2 to 20). OddRunnable implements Runnable and prints the first 20 odd numbers (1 to 39). Each sleeps 100 ms after every number. Since both threads run together, their lines are interleaved, for example:
Even: 2
Odd: 1
Odd: 3
Even: 4
...
After 10 numbers the even thread finishes and the odd thread continues until 39.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 7 marks
What is Byte/Character Stream? Write a program to read and write in a file Pokhara.txt with sentence "I study BCA"
Answer
A stream is a sequence of data flowing between a program and a source or destination (file, keyboard, network).
Byte streams handle data as 8-bit bytes. Their base classes are InputStream and OutputStream, with subclasses such as FileInputStream, FileOutputStream, BufferedInputStream and DataInputStream. They are suitable for binary data such as images, audio and executables.
Character streams handle 16-bit Unicode characters. Their base classes are Reader and Writer, with subclasses FileReader, FileWriter, BufferedReader, BufferedWriter and InputStreamReader. They are suitable for text and perform character-encoding conversion automatically.
Program: write and read Pokhara.txt
import java.io.*;
public class PokharaFile {
public static void main(String[] args) {
// Write
try (FileWriter fw = new FileWriter("Pokhara.txt")) {
fw.write("I study BCA");
} catch (IOException e) {
System.out.println("Write error: " + e.getMessage());
}
// Read
try (BufferedReader br = new BufferedReader(new FileReader("Pokhara.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Read error: " + e.getMessage());
}
}
}
Output:
I study BCA
The same task with byte streams would use FileOutputStream.write("I study BCA".getBytes()) and FileInputStream.read() to obtain each byte.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 8 marks
Differentiate between AWT and Swing. Briefly explain Event Delegation Model.
Answer
Difference between AWT and Swing
| AWT | Swing |
|---|---|
Package java.awt | Package javax.swing |
| Heavyweight components: each uses a native peer of the operating system | Lightweight components: drawn entirely by Java |
| Look and feel depends on the platform | Pluggable look and feel (Metal, Nimbus, Windows) |
| Fewer components | Richer set: JTable, JTree, JTabbedPane, JList, etc. |
| Not MVC based | Follows a modified MVC architecture |
| Less portable in appearance, faster on simple UIs | Platform-independent, slightly slower |
Class names like Button, Frame | Names prefixed with J: JButton, JFrame |
Event Delegation Model. Events are handled by delegating the processing from the source of the event to separate listener objects. It has three parts:
- Event source: the component that generates the event (button, text field, window).
- Event object: an object of a class derived from
java.util.EventObject, such asActionEvent,MouseEvent,KeyEvent, carrying information about the event. - Event listener: an object implementing a listener interface (
ActionListener,MouseListener,KeyListener) that contains the handler method.
The listener must be registered with the source, e.g. button.addActionListener(this). When the user acts, the source creates an event object and passes it to the registered listener's method (actionPerformed(ActionEvent e)). Only registered listeners are notified, so unrelated events cost nothing, and the GUI code is separated from the event-handling logic.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
});
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 8 marks
Write a java program to create a GUI (using Swing) for new student registration that reads student name, address, gender, city, phone and email. Use the Listbox for city and radio button for gender.
Answer
The form uses JTextField for name, address, phone and email, JRadioButton (grouped in a ButtonGroup) for gender, and a JList (list box) for city.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class StudentRegistration extends JFrame implements ActionListener {
JTextField txtName = new JTextField(20);
JTextField txtAddress = new JTextField(20);
JTextField txtPhone = new JTextField(20);
JTextField txtEmail = new JTextField(20);
JRadioButton rbMale = new JRadioButton("Male", true);
JRadioButton rbFemale = new JRadioButton("Female");
JList<String> lstCity = new JList<>(new String[]{"Kathmandu", "Pokhara", "Lalitpur", "Butwal"});
JButton btnSubmit = new JButton("Register");
StudentRegistration() {
super("Student Registration");
setLayout(new GridLayout(7, 2, 5, 5));
ButtonGroup bg = new ButtonGroup();
bg.add(rbMale);
bg.add(rbFemale);
JPanel genderPanel = new JPanel();
genderPanel.add(rbMale);
genderPanel.add(rbFemale);
lstCity.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lstCity.setSelectedIndex(0);
add(new JLabel("Name:")); add(txtName);
add(new JLabel("Address:")); add(txtAddress);
add(new JLabel("Gender:")); add(genderPanel);
add(new JLabel("City:")); add(new JScrollPane(lstCity));
add(new JLabel("Phone:")); add(txtPhone);
add(new JLabel("Email:")); add(txtEmail);
add(new JLabel("")); add(btnSubmit);
btnSubmit.addActionListener(this);
setSize(400, 350);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String gender = rbMale.isSelected() ? "Male" : "Female";
String msg = "Name: " + txtName.getText()
+ "\nAddress: " + txtAddress.getText()
+ "\nGender: " + gender
+ "\nCity: " + lstCity.getSelectedValue()
+ "\nPhone: " + txtPhone.getText()
+ "\nEmail: " + txtEmail.getText();
JOptionPane.showMessageDialog(this, msg, "Registered", JOptionPane.INFORMATION_MESSAGE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(StudentRegistration::new);
}
}
Explanation. A GridLayout of 7 rows by 2 columns places each label beside its field. The ButtonGroup ensures only one gender can be selected. The JList in single-selection mode acts as the city list box. On clicking Register, actionPerformed collects the values and displays them in a dialog.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 7 marks
What are the different types of layouts in java? Explain the GridBagLayout manager with an example.
Answer
A layout manager decides the size and position of components in a container. Main layouts in Java:
- FlowLayout: places components left to right, wrapping to the next row; default for
JPanel. - BorderLayout: five regions (North, South, East, West, Center); default for
JFrame. - GridLayout: equal-sized cells in rows and columns.
- CardLayout: stacks components like cards, showing one at a time.
- BoxLayout: arranges components in a single row or column.
- GridBagLayout: flexible grid whose rows and columns may have different sizes and components may span several cells.
- GroupLayout / SpringLayout: used mostly by GUI builders.
GridBagLayout. Components are placed in a grid of cells, but unlike GridLayout a component may span multiple rows or columns and the rows and columns need not be the same size. Each component is controlled by a GridBagConstraints object with fields:
gridx,gridy: cell position.gridwidth,gridheight: number of cells spanned.weightx,weighty: how extra space is distributed.fill: how the component fills its cell (NONE,HORIZONTAL,VERTICAL,BOTH).anchor: where it sits in the cell;insets: external padding;ipadx,ipady: internal padding.
import javax.swing.*;
import java.awt.*;
public class GridBagDemo {
public static void main(String[] args) {
JFrame f = new JFrame("GridBagLayout");
f.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0; c.gridy = 0;
f.add(new JLabel("Name:"), c);
c.gridx = 1; c.gridy = 0; c.weightx = 1.0;
f.add(new JTextField(15), c);
c.gridx = 0; c.gridy = 1; c.gridwidth = 2; // spans two columns
f.add(new JButton("Submit"), c);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
The label and text field share the first row; the button sits on the second row and spans both columns.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 8 marks
What is Proxy server? Write a simple java socket programming in which client sends a text and server receives and print it.
Answer
A proxy server is an intermediary server that sits between clients and other servers. A client sends its request to the proxy, which forwards it to the destination server and returns the response. Uses:
- Caching: stores frequently requested pages to save bandwidth and speed up access.
- Filtering and access control: blocks unwanted sites and enforces policies.
- Anonymity and security: hides the client's IP address and can inspect traffic.
- Load balancing (reverse proxy) and logging of traffic.
Socket program. The server uses ServerSocket to wait on a port; the client uses Socket to connect. Streams over the socket carry the data.
Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
try (ServerSocket ss = new ServerSocket(5000)) {
System.out.println("Server waiting for client...");
try (Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()))) {
String text = in.readLine();
System.out.println("Received from client: " + text);
}
}
}
}
Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
try (Socket s = new Socket("localhost", 5000);
PrintWriter out = new PrintWriter(s.getOutputStream(), true)) {
out.println("Hello Server, I study BCA");
}
}
}
Run. Start Server first, then Client. The server prints:
Server waiting for client...
Received from client: Hello Server, I study BCA
accept() blocks until a client connects; readLine() reads the text sent by println().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 7 marks
Write down the steps to connect to a database. Also write down a method signature to authenticate a user from database where username and password are supplied by the user as a method argument. (Note: Server: 192.168.10.121, username=pouexam, password=P0kHarA)
Answer
Steps to connect to a database (JDBC)
- Import
java.sql.*. - Load the driver, e.g.
Class.forName("com.mysql.cj.jdbc.Driver"), with the driver jar on the classpath. - Create the connection with
DriverManager.getConnection(url, user, password). - Create a
StatementorPreparedStatement. - Execute the SQL (
executeQuery/executeUpdate). - Process the
ResultSet. - Close the
ResultSet, statement and connection.
Method to authenticate a user. The server is 192.168.10.121, user pouexam, password P0kHarA. A table users(username, password) in a database (here called exam) is assumed. A PreparedStatement is used so that the supplied values cannot cause SQL injection.
import java.sql.*;
public class Auth {
public static boolean authenticate(String username, String password) {
String url = "jdbc:mysql://192.168.10.121:3306/exam";
String dbUser = "pouexam";
String dbPass = "P0kHarA";
String sql = "SELECT 1 FROM users WHERE username = ? AND password = ?";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection con = DriverManager.getConnection(url, dbUser, dbPass);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, username);
ps.setString(2, password);
try (ResultSet rs = ps.executeQuery()) {
return rs.next(); // true if a matching row exists
}
}
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Database error: " + e.getMessage());
return false;
}
}
public static void main(String[] args) {
System.out.println(authenticate("ram", "ram123") ? "Login success" : "Login failed");
}
}
The method signature is public static boolean authenticate(String username, String password). It returns true when the query finds a row with the given username and password, otherwise false. (In real systems passwords should be stored hashed and compared as hashes.)
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 7 marks
Explain URL class. Write a program to find and display the protocol, host, port, and filename of the given URL.
Answer
The java.net.URL class represents a Uniform Resource Locator, the address of a resource on the Internet. A URL has the form
protocol://host:port/path/filename?query#ref
for example https://www.example.com:8080/docs/index.html. The class lets a program parse a URL and read the resource (openStream(), openConnection()). Constructor: URL(String spec), which throws MalformedURLException for an invalid URL. Important methods:
getProtocol(): scheme such as http or https.getHost(): host name.getPort(): port number, or-1if none is given in the URL.getDefaultPort(): default port of the protocol (80 for http, 443 for https).getFile()/getPath(): file part (with / without query).getQuery(),getRef(),openStream().
import java.net.*;
public class URLDemo {
public static void main(String[] args) {
try {
URL url = new URL("http://www.example.com:8080/docs/index.html?id=5");
System.out.println("Protocol : " + url.getProtocol());
System.out.println("Host : " + url.getHost());
System.out.println("Port : " + url.getPort());
System.out.println("Filename : " + url.getFile());
} catch (MalformedURLException e) {
System.out.println("Invalid URL: " + e.getMessage());
}
}
}
Output:
Protocol : http
Host : www.example.com
Port : 8080
Filename : /docs/index.html?id=5
getPath() would return only /docs/index.html.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 8 marks
What are the advantages of generics over non-generics. How do you achieve polymorphism in generics? Explain with code example.
Answer
Generics let classes, interfaces and methods operate on types specified as parameters (e.g. List<String>), giving compile-time type safety.
Advantages of generics over non-generics
- Type safety: errors are detected at compile time instead of causing
ClassCastExceptionat run time. A rawArrayListaccepts any object, so a wrong type is found only when it is used. - No explicit casting: elements are retrieved with their correct type.
- Code reuse: one class or method works for many types (
Box<Integer>,Box<String>). - Generic algorithms: sorting, searching and similar logic can be written once for all types.
- Cleaner, self-documenting code.
// Non-generic
List raw = new ArrayList();
raw.add("Ram");
raw.add(10);
String s = (String) raw.get(1); // compiles, fails at run time: ClassCastException
// Generic
List<String> names = new ArrayList<>();
names.add("Ram");
// names.add(10); // compile-time error
String n = names.get(0); // no cast needed
Polymorphism in generics. It is achieved in three ways:
- Parametric polymorphism: one generic class or method works with many types.
- Bounded type parameters (
<T extends Number>) restrict the type and allow calling methods of the bound. - Wildcards (
? extends,? super) allow methods to accept related generic types, becauseList<Integer>is not a subtype ofList<Number>.
import java.util.*;
class Pair<T extends Comparable<T>> {
private T a, b;
Pair(T a, T b) { this.a = a; this.b = b; }
T max() { return a.compareTo(b) >= 0 ? a : b; }
}
public class GenericPoly {
// Generic method
static <E> void show(E[] arr) {
for (E e : arr) System.out.print(e + " ");
System.out.println();
}
// Wildcard: accepts List of Integer, Double, etc.
static double sum(List<? extends Number> list) {
double total = 0;
for (Number n : list) total += n.doubleValue();
return total;
}
public static void main(String[] args) {
System.out.println(new Pair<>(3, 8).max()); // 8
System.out.println(new Pair<>("apple", "bat").max()); // bat
show(new Integer[]{1, 2, 3});
show(new String[]{"A", "B"});
System.out.println(sum(Arrays.asList(1, 2, 3))); // 6.0
System.out.println(sum(Arrays.asList(1.5, 2.5))); // 4.0
}
}
The same Pair, show and sum code works for different types, demonstrating polymorphism through generics.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 5 marks
Write short notes on: Thread lifecycle
Answer
A thread passes through several states between creation and termination, described by Thread.State.
- New: the thread object has been created (
new Thread(...)) butstart()has not been called. - Runnable: after
start(), the thread is ready and waiting for the CPU, or running. (Ready and running are both reported as RUNNABLE.) - Running: the scheduler has given it the CPU and
run()executes. - Blocked: waiting to acquire a monitor lock held by another thread (for example entering a
synchronizedblock). - Waiting: waiting indefinitely for another thread, after
wait(),join()orpark(); resumes onnotify()/notifyAll()or when the joined thread ends. - Timed waiting: waiting for a specified time, after
sleep(ms),wait(ms)orjoin(ms). - Terminated (Dead):
run()has completed normally or ended due to an uncaught exception. A dead thread cannot be restarted.
New --start()--> Runnable <--> Running --run() ends--> Terminated
^ |
| sleep / wait / join / lock
+-- Blocked / Waiting / Timed waiting
getState() returns the current state, and isAlive() is true between start and termination.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 5 marks
Write short notes on: Generic class with parameters
Answer
A generic class is declared with one or more type parameters in angle brackets after the class name. The parameters act as placeholders replaced by actual types when an object is created. Conventional names: T (type), E (element), K (key), V (value), N (number).
class Pair<K, V> {
private K key;
private V value;
Pair(K key, V value) {
this.key = key;
this.value = value;
}
K getKey() { return key; }
V getValue() { return value; }
}
public class Test {
public static void main(String[] args) {
Pair<String, Integer> p = new Pair<>("Roll", 25);
String k = p.getKey(); // no cast needed
int v = p.getValue();
System.out.println(k + " = " + v); // Roll = 25
}
}
Key points
- Several parameters can be used (
Pair<K, V>). - Type arguments must be reference types:
Pair<String, Integer>, notint; primitives are autoboxed. - A parameter can be bounded:
class Box<T extends Number>. - The diamond
<>lets the compiler infer the type arguments. - Type information is erased at run time (type erasure), and
new T()is not allowed. - Benefits: type safety, no casts, reusable code.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 Spring · 5 marks
Write short notes on: JDBC drivers
Answer
A JDBC driver is a software component that lets a Java application communicate with a particular database. It implements the JDBC interfaces and translates JDBC calls into the database's protocol. There are four types:
Type 1: JDBC-ODBC bridge driver. Converts JDBC calls into ODBC calls, which the ODBC driver passes to the database. Needs the ODBC driver installed on the client. Slow and platform-dependent; removed in Java 8.
Type 2: Native-API driver (partly Java). Converts JDBC calls into the database vendor's native client library calls (e.g. Oracle OCI). Faster than Type 1, but needs native libraries on each client and is not fully portable.
Type 3: Network protocol driver (middleware). Sends JDBC calls over the network to a middleware server in a database-independent protocol; the server converts them for the database. Pure Java client, no client-side installation, suits the internet, but needs a middleware server.
Type 4: Thin driver (pure Java). Converts JDBC calls directly into the database's own network protocol. Platform-independent, fastest and most widely used; examples are MySQL Connector/J, the Oracle thin driver and the PostgreSQL driver.
Type 4 is generally preferred, with Type 3 where one driver must serve many databases.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 8 marks
Define Platform Independence? How Java support multiple-inheritance? Explain with real world example.
Answer
Platform independence. A language or program is platform independent if it can run on any operating system and hardware without modification. Java achieves this with "Write Once, Run Anywhere": the Java compiler (javac) converts source code into bytecode (.class), not into machine code. Bytecode is executed by the Java Virtual Machine (JVM), which exists for each platform (Windows, Linux, macOS) and converts bytecode to native instructions. Hence the same .class file runs on any system that has a JVM. Further reasons: fixed sizes of primitive types (an int is always 32 bits), and a standard library behaving the same everywhere.
Source (.java) --javac--> Bytecode (.class) --JVM(Windows/Linux/Mac)--> Machine code
Multiple inheritance in Java. Java does not allow a class to extend more than one class because it creates ambiguity (the diamond problem: if two parents define the same method, which one does the child inherit?). Java supports multiple inheritance through interfaces: a class can implement any number of interfaces, because interfaces carry no state and the class supplies a single implementation.
Real-world example. A smartphone is both a camera and a phone (and a music player). Camera and Phone are separate capabilities, and a smartphone class inherits from both.
interface Camera {
void takePhoto();
}
interface Phone {
void call(String number);
}
class SmartPhone implements Camera, Phone {
public void takePhoto() {
System.out.println("Photo taken");
}
public void call(String number) {
System.out.println("Calling " + number);
}
}
public class Demo {
public static void main(String[] args) {
SmartPhone s = new SmartPhone();
s.takePhoto();
s.call("9800000000");
Camera c = s; // can be used as either type
Phone p = s;
}
}
Output:
Photo taken
Calling 9800000000
Thus the smartphone gets the behaviour of both parents without ambiguity. If two interfaces have the same default method, the class must override it, resolving any conflict explicitly.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 7 marks
When to use exception handling? Write down the code to handle Insufficient Fund Exception when recharge balance is less than 10 rupees on calling to the user using user-defined exception.
Answer
When to use exception handling
Exception handling is used when a program may meet abnormal run-time conditions that it can report or recover from, so it does not crash. Examples are invalid input, division by zero, a missing file, a network failure, or a business-rule violation (such as insufficient balance). It separates error-handling code from normal logic, lets errors propagate to a suitable handler, and allows resources to be released in finally.
Program: user-defined exception for recharge balance below Rs 10
A call needs at least Rs 10 balance. If the balance is less, an InsufficientFundException is thrown, and the user must recharge.
class InsufficientFundException extends Exception {
InsufficientFundException(String msg) { super(msg); }
}
class Mobile {
private double balance;
Mobile(double balance) { this.balance = balance; }
void call(String number) throws InsufficientFundException {
if (balance < 10)
throw new InsufficientFundException(
"Insufficient fund: balance Rs " + balance + " is less than Rs 10. Please recharge.");
System.out.println("Calling " + number + " ...");
}
void recharge(double amount) {
balance += amount;
System.out.println("Recharged Rs " + amount + ", balance = Rs " + balance);
}
}
public class RechargeTest {
public static void main(String[] args) {
Mobile m = new Mobile(5);
try {
m.call("9841000000");
} catch (InsufficientFundException e) {
System.out.println(e.getMessage());
m.recharge(50);
}
}
}
Output:
Insufficient fund: balance Rs 5.0 is less than Rs 10. Please recharge.
Recharged Rs 50.0, balance = Rs 55.0
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 8 marks
Define Applet. Explain life cycle of applets with example
Answer
Applet
An applet is a small Java program that is embedded in a web page and runs inside a browser or the appletviewer, using the JVM. It extends java.applet.Applet (or javax.swing.JApplet) and has no main() method. (Applets are deprecated in recent Java versions, but they are still part of the syllabus.)
Life cycle of an applet
The browser calls these methods automatically:
init(): called once when the applet is first loaded. It initialises variables, loads images and builds the interface.start(): called afterinit()and every time the page is revisited. It starts the applet's work (for example, threads or animation).paint(Graphics g): called whenever the output must be drawn or redrawn.stop(): called when the user leaves the page or the applet is minimised. It suspends activity.destroy(): called once when the applet is removed from memory. It releases resources.
Order: init() -> start() -> paint() -> stop() -> (start() again if revisited) -> destroy().
Example
import java.applet.Applet;
import java.awt.Graphics;
public class LifeApplet extends Applet {
String msg = "";
public void init() { msg += " init"; }
public void start() { msg += " start"; }
public void paint(Graphics g) { g.drawString(msg, 20, 30); }
public void stop() { System.out.println("stop"); }
public void destroy() { System.out.println("destroy"); }
}
HTML to run it:
<applet code="LifeApplet.class" width="300" height="100"></applet>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 7 marks
Define thread and its importance. Explain Runnable interface with an example.
Answer
Thread
A thread is a lightweight unit of execution inside a process. All threads of a process share its memory, but each has its own stack and program counter. Multithreading lets a program do several tasks at once.
Importance
- Better CPU utilisation, because one thread runs while another waits for I/O.
- Responsive applications (the GUI stays active while a background task runs).
- Cheaper than processes, since creating and switching threads costs less and they share data easily.
- Suits server programs that handle many clients at once, and parallel computation.
Runnable interface
java.lang.Runnable has one method, void run(). A class implements Runnable and puts the task in run(). A Thread object is then created with the Runnable and started with start(). This is preferred over extending Thread because the class can still extend another class.
class Task implements Runnable {
private String name;
Task(String name) { this.name = name; }
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(name + " : " + i);
try { Thread.sleep(500); } catch (InterruptedException e) { }
}
}
}
public class RunnableDemo {
public static void main(String[] args) {
Thread t1 = new Thread(new Task("Thread-A"));
Thread t2 = new Thread(new Task("Thread-B"));
t1.start();
t2.start();
}
}
Both threads run concurrently, so their outputs interleave. Calling run() directly would not create a new thread, so start() must be used.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 7 marks
Define Print writer. Write a java program using file sequential.
Answer
PrintWriter
java.io.PrintWriter is a character-output class that prints formatted text to a stream or file. It has the methods print(), println() and printf(), can wrap a File, FileWriter or OutputStream, and does not throw IOException from its print methods (use checkError()). It is often wrapped over BufferedWriter for efficiency.
Sequential file program
In a sequential file, data is written and read in order from the start. The program below writes records and then reads them back sequentially.
import java.io.*;
import java.util.Scanner;
public class SequentialFile {
public static void main(String[] args) throws IOException {
// write sequentially
try (PrintWriter pw = new PrintWriter(new FileWriter("data.txt"))) {
pw.println("1 Ram 80");
pw.println("2 Sita 90");
pw.printf("%d %s %d%n", 3, "Hari", 75);
}
// read sequentially
try (Scanner sc = new Scanner(new File("data.txt"))) {
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
}
}
}
Output:
1 Ram 80
2 Sita 90
3 Hari 75
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 7 marks
Write a program to display a registration screen with full name, username, password and register button using swing components.
Answer
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RegistrationScreen extends JFrame implements ActionListener {
JTextField txtName, txtUser;
JPasswordField txtPass;
JButton btnRegister;
public RegistrationScreen() {
setTitle("Registration");
setLayout(new GridLayout(4, 2, 5, 5));
add(new JLabel("Full Name:"));
txtName = new JTextField();
add(txtName);
add(new JLabel("Username:"));
txtUser = new JTextField();
add(txtUser);
add(new JLabel("Password:"));
txtPass = new JPasswordField();
add(txtPass);
btnRegister = new JButton("Register");
btnRegister.addActionListener(this);
add(new JLabel()); // empty cell
add(btnRegister);
setSize(350, 180);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String name = txtName.getText();
String user = txtUser.getText();
String pass = new String(txtPass.getPassword());
if (name.isEmpty() || user.isEmpty() || pass.isEmpty()) {
JOptionPane.showMessageDialog(this, "Please fill all fields");
} else {
JOptionPane.showMessageDialog(this, "Registered: " + name + " (" + user + ")");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(RegistrationScreen::new);
}
}
The program uses JLabel, JTextField, JPasswordField and JButton in a 4x2 GridLayout. The button's ActionListener reads the fields and shows a confirmation message.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 8 marks
Define socket in Java? Write a simple Java Socket program to send a text to the server.
Answer
Socket
A socket is one endpoint of a two-way communication link between two programs on a network. It is identified by an IP address and a port number. Java provides java.net.Socket for the client and java.net.ServerSocket for the server, and TCP sockets give reliable, connection-oriented communication.
Server (receives text)
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5000);
System.out.println("Waiting for client...");
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String text = in.readLine();
System.out.println("Received: " + text);
in.close(); s.close(); ss.close();
}
}
Client (sends text)
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 5000);
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
out.println("Hello Server");
out.close(); s.close();
}
}
Run the server first, then the client. The server prints Received: Hello Server.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 7 marks
What is Proxy Server? Write the steps for implementing the TCP/IP based Client/Server applications.
Answer
Proxy server
A proxy server is an intermediate server between clients and other servers (usually the Internet). The client sends its request to the proxy, which forwards it to the destination, receives the reply and returns it to the client. Uses include caching (faster repeat access), filtering or blocking sites, hiding the client's IP address (anonymity), logging, and security control.
Steps to implement a TCP/IP client/server application
Server side
- Create a
ServerSocketon a port:ServerSocket ss = new ServerSocket(port); - Wait for a client:
Socket s = ss.accept();(this blocks until a client connects). - Get the input and output streams:
s.getInputStream()ands.getOutputStream(), and wrap them in readers and writers. - Read the request and send the response.
- Close the streams and sockets.
Client side
- Create a
Socketwith the server's host and port:Socket s = new Socket(host, port); - Get the input and output streams of the socket.
- Send the request and read the response.
- Close the streams and the socket.
For many clients, the server runs a loop that calls accept() and gives each connection to a new thread.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 7 marks
Write a program to save student information sid, name, semester, and program to a table called tbl_students and read back to the console.
Answer
import java.sql.*;
public class StudentJDBC {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/college";
String user = "root", pass = "password";
try (Connection con = DriverManager.getConnection(url, user, pass)) {
Class.forName("com.mysql.cj.jdbc.Driver");
Statement st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS tbl_students ("
+ "sid INT PRIMARY KEY, name VARCHAR(50), "
+ "semester INT, program VARCHAR(30))");
// save
String sql = "INSERT INTO tbl_students VALUES (?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 101);
ps.setString(2, "Ram Sharma");
ps.setInt(3, 3);
ps.setString(4, "BCA");
ps.executeUpdate();
// read back
ResultSet rs = st.executeQuery("SELECT * FROM tbl_students");
System.out.println("SID\tName\tSemester\tProgram");
while (rs.next()) {
System.out.println(rs.getInt("sid") + "\t" + rs.getString("name")
+ "\t" + rs.getInt("semester") + "\t" + rs.getString("program"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Steps: load the driver, open a Connection, create the table, insert the student with a PreparedStatement, run SELECT to get a ResultSet, and loop with rs.next() to print rows. Running the insert twice with the same sid would violate the primary key.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 8 marks
Define JDBC drivers. Explain different types of drivers
Answer
JDBC driver
A JDBC driver is a set of classes that implements the JDBC interfaces (Driver, Connection, Statement, ResultSet) for a specific database. It translates Java JDBC calls into the protocol that the database understands, and DriverManager uses it to create connections.
Types of JDBC drivers
| Type | Name | Working | Advantages | Disadvantages |
|---|---|---|---|---|
| 1 | JDBC-ODBC bridge | JDBC calls are converted to ODBC calls, then to the database | Easy; any ODBC database | Slow; needs ODBC on client; platform dependent; removed in Java 8 |
| 2 | Native-API (partly Java) | JDBC calls are converted to the database's native C/C++ library calls | Faster than Type 1 | Native library needed on client; not portable |
| 3 | Network-protocol (middleware) | JDBC calls go to a middleware server, which converts them to the database protocol | No client-side library; flexible; good for the Internet | Extra server needed; more maintenance |
| 4 | Thin (pure Java) | JDBC calls are converted directly to the database's network protocol | Fastest; platform independent; no extra software | Driver is specific to one database |
Type 4 is most widely used today (for example com.mysql.cj.jdbc.Driver, oracle.jdbc.OracleDriver).
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/db", "user", "pw");
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 5 marks
Write short notes on: Explain event delegation model with suitable example.
Answer
In the event delegation model, the handling of an event is delegated to a separate listener object. It has three parts.
- Event source: the component that generates the event (button, text field, window).
- Event object: describes the event (
ActionEvent,MouseEvent,KeyEvent). - Event listener: an object that implements a listener interface (
ActionListener,MouseListener) and is registered with the source usingaddXxxListener().
Steps: create the component, implement the listener interface, register the listener with the source, and write the code in the handler method. Only registered listeners are notified, so this is more efficient than the old model, where every event was passed through the component hierarchy. It also separates the interface logic from the application logic.
import java.awt.*;
import java.awt.event.*;
public class DelegationDemo extends Frame implements ActionListener {
Button b = new Button("Click");
Label l = new Label("Not clicked ");
DelegationDemo() {
setLayout(new FlowLayout());
add(b); add(l);
b.addActionListener(this); // register listener with source
setSize(250, 100); setVisible(true);
}
public void actionPerformed(ActionEvent e) { // event handler
l.setText("Button clicked");
}
public static void main(String[] a) { new DelegationDemo(); }
}
Here the button is the source, ActionEvent is the event, and the frame is the listener.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 Spring · 5 marks
Write short notes on: Sequential vs random access file in Java IO
Answer
| Basis | Sequential access file | Random access file |
|---|---|---|
| Access | Data is read or written in order from the beginning | Any position can be reached directly |
| Classes | FileInputStream, FileOutputStream, FileReader, FileWriter, PrintWriter, Scanner | RandomAccessFile |
| Pointer movement | Moves only forward | Moves anywhere using seek(pos) |
| Speed for a record in the middle | Slow, since all earlier data must be read | Fast, since it jumps directly to the record |
| Read and write | Usually either one at a time | Both in one file (modes "r", "rw") |
| Best for | Text files, logs, streaming | Databases, records of fixed size |
Example of random access:
RandomAccessFile raf = new RandomAccessFile("data.dat", "rw");
raf.writeInt(10);
raf.writeInt(20);
raf.writeInt(30);
raf.seek(4); // skip first int (4 bytes)
System.out.println(raf.readInt()); // 20
raf.close();
Other useful methods are getFilePointer() and length().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 8 marks
What is the "Write Once Run Anywhere" feature of Java? Explain with JVM architecture.
Answer
Write Once, Run Anywhere (WORA)
A Java program is written and compiled once. The compiler (javac) converts the source file into platform-neutral bytecode (.class), and this bytecode can run unchanged on any machine that has a JVM, whether Windows, Linux or macOS. The JVM turns the bytecode into the machine instructions of its own platform. So the program does not need to be rewritten or recompiled for each platform.
Source (.java) --javac--> Bytecode (.class) --> JVM on Windows / Linux / macOS
JVM architecture
- Class Loader subsystem: loads, links and initialises classes (Bootstrap, Extension/Platform and Application class loaders). Linking has verification, preparation and resolution.
- Runtime data areas (memory)
- Method area: class metadata, static variables, constant pool, method code.
- Heap: all objects and arrays, shared by all threads and managed by the garbage collector.
- Stack: one per thread, holding frames with local variables and partial results of method calls.
- PC register: one per thread, holding the address of the current instruction.
- Native method stack: for native (non-Java) methods.
- Execution engine
- Interpreter: executes bytecode line by line.
- JIT compiler: compiles frequently used bytecode to native code for speed.
- Garbage collector: frees objects that are no longer used.
- Native method interface (JNI) and native libraries: connect the JVM to code written in C/C++.
Because each platform has its own JVM that follows the same specification, the same bytecode behaves the same everywhere, and this gives WORA.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 7 marks
Why exception handling in Java is important? Write down the code to handle user-defined exception for InsufficientFundException when balance is less than 100 on your account.
Answer
Importance of exception handling
- It prevents abnormal termination, because errors are caught and the program continues or ends cleanly.
- It separates normal logic from error-handling code (
try/catch), so the code is cleaner. - Errors can be passed up the call stack to a method that knows how to handle them (
throws). - It gives meaningful messages to users and supports resource clean-up with
finally. - Business rules can be enforced with user-defined exceptions.
Program
class InsufficientFundException extends Exception {
InsufficientFundException(String message) { super(message); }
}
class Account {
private double balance;
Account(double balance) { this.balance = balance; }
void withdraw(double amount) throws InsufficientFundException {
if (balance < 100)
throw new InsufficientFundException(
"Insufficient fund: balance Rs " + balance + " is less than Rs 100");
if (amount > balance)
throw new InsufficientFundException("Withdrawal exceeds balance");
balance -= amount;
System.out.println("Withdrawn Rs " + amount + ", balance Rs " + balance);
}
}
public class BankTest {
public static void main(String[] args) {
Account acc = new Account(80);
try {
acc.withdraw(20);
} catch (InsufficientFundException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Transaction finished");
}
}
}
Output:
Error: Insufficient fund: balance Rs 80.0 is less than Rs 100
Transaction finished
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 8 marks
Define applet. Write down the code to display simple Hello Pokhara University. Also write down HTML code to display that applet program to webpage.
Answer
Applet
An applet is a small Java program that is embedded in an HTML page and runs inside a browser or appletviewer. It extends java.applet.Applet, has no main() method, and its life cycle methods (init, start, paint, stop, destroy) are called by the browser.
Applet code (HelloPU.java)
import java.applet.Applet;
import java.awt.Graphics;
public class HelloPU extends Applet {
public void paint(Graphics g) {
g.drawString("Hello Pokhara University", 50, 50);
}
}
Compile it with javac HelloPU.java.
HTML code (index.html)
<html>
<head><title>Hello Applet</title></head>
<body>
<applet code="HelloPU.class" width="300" height="150">
</applet>
</body>
</html>
Open the page in an applet-enabled environment, or run appletviewer index.html. The window displays "Hello Pokhara University". The .class file must be in the same folder as the HTML file, unless codebase is given.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 7 marks
Why thread synchronization is required? Explain with suitable programming example.
Answer
Why synchronization is required
When several threads use the same shared resource (a variable, a file, an account) at the same time, their operations can interleave and produce wrong or inconsistent results. This is called a race condition. For example, two threads doing count++ can both read the same old value and each write back the same new value, so one update is lost. Synchronization allows only one thread at a time into the critical section, using the object's monitor lock. It ensures data consistency and thread safety.
Ways to do it: a synchronized method, a synchronized block, or Lock objects.
Example
class Counter {
private int count = 0;
synchronized void increment() { count++; } // only one thread at a time
int get() { return count; }
}
class Worker extends Thread {
Counter c;
Worker(Counter c) { this.c = c; }
public void run() {
for (int i = 0; i < 1000; i++) c.increment();
}
}
public class SyncDemo {
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
Worker t1 = new Worker(c), t2 = new Worker(c);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println("Count = " + c.get()); // always 2000
}
}
Without synchronized, the result may be less than 2000. With it, the result is always 2000.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 8 marks
What is Java Stream? Write a Java program to write Student info (stdName, stdAge, stdId) into a file called Student.txt.
Answer
Java Stream
A stream is a sequence of data flowing from a source to a destination. Java I/O uses streams in the package java.io.
- Input stream: reads data into a program (
InputStream,Reader). - Output stream: writes data from a program (
OutputStream,Writer). - Byte streams (
FileInputStream,FileOutputStream) handle binary data in 8-bit bytes. - Character streams (
FileReader,FileWriter) handle text in 16-bit Unicode.
Program to write student info into Student.txt
import java.io.*;
import java.util.Scanner;
public class WriteStudent {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
String stdName = sc.nextLine();
System.out.print("Enter age: ");
int stdAge = sc.nextInt();
System.out.print("Enter id: ");
int stdId = sc.nextInt();
try (FileWriter fw = new FileWriter("Student.txt");
BufferedWriter bw = new BufferedWriter(fw)) {
bw.write("Name: " + stdName);
bw.newLine();
bw.write("Age: " + stdAge);
bw.newLine();
bw.write("Id: " + stdId);
bw.newLine();
System.out.println("Data written to Student.txt");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
The try-with-resources statement closes the file automatically.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 7 marks
Write a GUI program to input username and password. If the user input is "Ram" and "IIIIIII" for username and password field display the message "welcome" otherwise display message "invalid login".
Answer
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginForm extends JFrame implements ActionListener {
JTextField txtUser = new JTextField(15);
JPasswordField txtPass = new JPasswordField(15);
JButton btnLogin = new JButton("Login");
JLabel lblMsg = new JLabel(" ");
public LoginForm() {
setTitle("Login");
setLayout(new FlowLayout());
add(new JLabel("Username:"));
add(txtUser);
add(new JLabel("Password:"));
add(txtPass);
add(btnLogin);
add(lblMsg);
btnLogin.addActionListener(this);
setSize(260, 190);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String user = txtUser.getText();
String pass = new String(txtPass.getPassword());
if (user.equals("Ram") && pass.equals("IIIIIII"))
lblMsg.setText("welcome");
else
lblMsg.setText("invalid login");
}
public static void main(String[] args) {
new LoginForm();
}
}
The equals() method compares the strings exactly. When the button is clicked, the program shows "welcome" for username Ram with password IIIIIII, and "invalid login" otherwise.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 7 marks
What is a listener in Java? Explain methods of MouseListener and KeyListener.
Answer
Listener
A listener is an object that waits for and handles events from a GUI component. It is an instance of a class that implements a listener interface from java.awt.event (for example ActionListener, MouseListener, KeyListener). It is registered with a component using addXxxListener(), and when the event occurs, the matching method is called automatically.
MouseListener methods (event type MouseEvent)
| Method | Called when |
|---|---|
mouseClicked(MouseEvent e) | the mouse is pressed and released on a component |
mousePressed(MouseEvent e) | a mouse button is pressed |
mouseReleased(MouseEvent e) | a mouse button is released |
mouseEntered(MouseEvent e) | the pointer enters the component |
mouseExited(MouseEvent e) | the pointer leaves the component |
KeyListener methods (event type KeyEvent)
| Method | Called when |
|---|---|
keyPressed(KeyEvent e) | a key is pressed down (works for all keys, including action keys) |
keyReleased(KeyEvent e) | a key is released |
keyTyped(KeyEvent e) | a Unicode character is typed |
Useful KeyEvent methods are getKeyChar() and getKeyCode(), and for the mouse getX(), getY() and getClickCount().
import java.awt.*;
import java.awt.event.*;
public class ListenerDemo extends Frame implements MouseListener, KeyListener {
Label l = new Label("Interact with me");
ListenerDemo() {
add(l);
addMouseListener(this);
addKeyListener(this);
setSize(300, 150); setVisible(true);
}
public void mouseClicked(MouseEvent e) { l.setText("Clicked at " + e.getX() + "," + e.getY()); }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { l.setText("Mouse entered"); }
public void mouseExited(MouseEvent e) { l.setText("Mouse exited"); }
public void keyPressed(KeyEvent e) { l.setText("Key pressed: " + e.getKeyChar()); }
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { }
public static void main(String[] a) { new ListenerDemo(); }
}
All methods of the interface must be implemented, or an adapter class (MouseAdapter, KeyAdapter) can be used.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 8 marks
What is java.net? Write a program of sending and receiving of datagram packet by datagram socket?
Answer
java.net
java.net is the Java package for network programming. It contains classes for TCP sockets (Socket, ServerSocket), UDP communication (DatagramSocket, DatagramPacket), addresses (InetAddress) and web resources (URL, URLConnection, HttpURLConnection).
Datagram communication uses UDP, which is connectionless and fast but gives no guarantee of delivery or order. DatagramPacket holds the data, length, address and port, and DatagramSocket sends and receives the packets.
Receiver (run first)
import java.net.*;
public class UDPReceiver {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(9876);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp); // blocks until a packet arrives
String msg = new String(dp.getData(), 0, dp.getLength());
System.out.println("Received: " + msg);
ds.close();
}
}
Sender
import java.net.*;
public class UDPSender {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
byte[] data = "Hello UDP".getBytes();
InetAddress ip = InetAddress.getByName("localhost");
DatagramPacket dp = new DatagramPacket(data, data.length, ip, 9876);
ds.send(dp);
ds.close();
}
}
The receiver prints Received: Hello UDP.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 7 marks
Define proxy server. Write down Java code to read content of http://www.pu.edu.np using URL and URL Connection class.
Answer
Proxy server
A proxy server is an intermediary between a client and the Internet. The client sends requests to the proxy, which forwards them to the target server and returns the reply. It provides caching, content filtering, access control, logging and hides the client's IP address.
Program to read the content of http://www.pu.edu.np
import java.io.*;
import java.net.*;
public class ReadURL {
public static void main(String[] args) {
try {
URL url = new URL("http://www.pu.edu.np");
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (MalformedURLException e) {
System.out.println("Bad URL: " + e.getMessage());
} catch (IOException e) {
System.out.println("I/O error: " + e.getMessage());
}
}
}
URL represents the address, openConnection() returns a URLConnection, and getInputStream() gives the stream used to read the HTML text line by line.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 8 marks
Write a program to extract the user information such as roll, name and address from the database and display in the console.
Answer
import java.sql.*;
public class ReadUsers {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/college";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "password");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT roll, name, address FROM users");
System.out.println("Roll\tName\tAddress");
while (rs.next()) {
int roll = rs.getInt("roll");
String name = rs.getString("name");
String address = rs.getString("address");
System.out.println(roll + "\t" + name + "\t" + address);
}
rs.close();
st.close();
con.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
Steps: load the driver, connect with DriverManager, create a Statement, run the SELECT query to get a ResultSet, loop over rows with rs.next(), read columns with getXxx(), and close the resources. The table users(roll INT, name VARCHAR, address VARCHAR) is assumed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 5 marks
Write short notes on: Swing vs AWT
Answer
Swing vs AWT
AWT (Abstract Window Toolkit, java.awt) is Java's original GUI toolkit. Its components (Button, TextField, Label) are heavyweight: each one is backed by a native peer from the operating system, so the look changes from platform to platform. Swing (javax.swing) is built on top of AWT. Most of its components (JButton, JTextField, JLabel) are lightweight: they are drawn by Java itself, not by the OS.
| Basis | AWT | Swing |
|---|---|---|
| Package | java.awt | javax.swing |
| Component type | Heavyweight (native peers) | Lightweight (pure Java) |
| Look and feel | Depends on the platform | Pluggable look and feel, same on all platforms |
| Platform independence | Partly | Fully |
| Components | Few and basic | Rich set: JTable, JTree, JTabbedPane, JOptionPane |
| Architecture | No MVC | Based on MVC |
| Speed | Faster to load, uses native resources | Slightly slower, needs more memory |
| Naming | Button, Frame | JButton, JFrame |
Both use the same event-handling model (listeners such as ActionListener). Swing is preferred today because it is more flexible and portable.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 Fall · 5 marks
Write short notes on: JVM Architecture
Answer
JVM Architecture
The Java Virtual Machine (JVM) is the abstract machine that loads and executes Java bytecode (.class files). It makes Java platform independent: the compiler produces bytecode once, and each platform's JVM runs it.
Main components:
- Class loader subsystem: loads, links and initialises classes.
- Loading: Bootstrap, Extension (Platform) and Application class loaders read the
.classfile. - Linking: verification (bytecode is checked for safety), preparation (static variables get default values) and resolution (symbolic references become direct references).
- Initialisation: static variables get their assigned values and static blocks run.
- Loading: Bootstrap, Extension (Platform) and Application class loaders read the
- Runtime data areas (memory):
- Method area: class structures, method code, constant pool and static data (shared by all threads).
- Heap: all objects and arrays are created here; it is shared and managed by the garbage collector.
- Stack area: each thread has its own stack of frames; a frame holds local variables, the operand stack and a reference to the constant pool.
- PC register: each thread has one, holding the address of the instruction being executed.
- Native method stack: used for native (non-Java) methods.
- Execution engine: executes the bytecode.
- Interpreter: reads and executes bytecode instruction by instruction.
- JIT compiler: compiles frequently used code ("hot spots") to native machine code to improve speed.
- Garbage collector: frees memory of objects that are no longer referenced.
- Native method interface (JNI) and native libraries: allow Java code to call C/C++ libraries.
Flow: .java -> compiler (javac) -> .class bytecode -> class loader -> runtime data areas -> execution engine -> machine.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from PU BCA 2025 Spring (New) Data Structure and Algorithms (Pokhara University BCA, Spring 2025), PU BCA 2024 Fall (New) Data Structure and Algorithms (Pokhara University BCA, Fall 2024), PU BCA 2024 Spring Data Structure and Algorithms (Pokhara University BCA, Spring 2024), PU BCA 2023 Spring Data Structure and Algorithms (Pokhara University BCA, Spring 2023), PU BCA 2022 Fall Data Structure and Algorithms (Pokhara University BCA, Fall 2022), PU BCA 2025 Spring Object Oriented Programming using Java (Pokhara University BCA, Spring 2025), PU BCA 2024 Fall Object Oriented Programming using Java (Pokhara University BCA, Fall 2024), PU BCA 2024 Spring Java Programming (Pokhara University BCA, Spring 2024), PU BCA 2023 Spring Java Programming (Pokhara University BCA, Spring 2023), PU BCA 2022 Fall Java Programming (Pokhara University BCA, Fall 2022), PU BCA 2025 Spring (New) Operating System (Pokhara University BCA, Spring 2025), PU BCA 2024 Fall (New) Operating System (Pokhara University BCA, Fall 2024), PU BCA 2024 Spring Operating System (Pokhara University BCA, Spring 2024), PU BCA 2023 Spring Operating System (Pokhara University BCA, Spring 2023), PU BCA 2022 Fall Operating System (Pokhara University BCA, Fall 2022), PU BCA 2021 Spring Operating System (Pokhara University BCA, Spring 2021), PU BCA 2025 Spring System Analysis and Project Management (Pokhara University BCA, Spring 2025), PU BCA 2024 Spring System Analysis and Design (Pokhara University BCA, Spring 2024), PU BCA 2023 Spring System Analysis and Design (Pokhara University BCA, Spring 2023), PU BCA 2022 Fall System Analysis and Design (Pokhara University BCA, Fall 2022), PU BCA 2025 Spring (New) Web Technologies I (Pokhara University BCA, Spring 2025, new syllabus), PU BCA 2025 Spring Web Technologies I (Pokhara University BCA, Spring 2025), PU BCA 2024 Spring Web Technologies I (Pokhara University BCA, Spring 2024), PU BCA 2023 Spring Web Technologies I (Pokhara University BCA, Spring 2023), PU BCA 2022 Fall Web Technologies I (Pokhara University BCA, Fall 2022) and PU BCA 2021 Spring Web Technologies I (Pokhara University BCA, Spring 2021). Answers are written for this site; check them against your class notes.