Chapter 8
Java Programming I (old course)
TU BIM past exam questions
Past questions and answers
91 questions set from this chapter, 2 of them more than once. Most repeated first.
- Asked 2 times
- 2014 AD Model · 1 mark
- 2019 AD · 1 mark
What do you mean by garbage collection?
Answer
Garbage collection is the automatic process by which the JVM finds objects that are no longer referenced by the program and frees the memory they occupy. The programmer does not have to release memory manually. It can be requested (not forced) using System.gc().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- Asked 2 times
- 2015 AD · 1 mark
- 2019 AD · 1 mark
What do you mean by enumeration?
Answer
An enumeration (enum) is a special Java type that defines a fixed set of named constants, for example enum Day { SUN, MON, TUE }. It makes code more readable and type-safe.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 1 mark
What is use of valueOf() function?
Answer
The valueOf() method converts a value to the corresponding wrapper object, for example Integer.valueOf("25") returns an Integer object from a string or primitive. In wrapper classes it is used to create objects without using the constructor and for boxing a primitive.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 1 mark
What is use of interface?
Answer
An interface declares a set of abstract methods (and constants) that implementing classes must define. It is used to achieve abstraction and a form of multiple inheritance, since a class can implement many interfaces, and to specify a common contract for unrelated classes.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 1 mark
Why are comments used in programs?
Answer
Comments explain the code to human readers. They make a program easier to understand, maintain and debug, and can be used to temporarily disable code. The compiler ignores them. In Java: // single line, /* multi-line */, and /** documentation */.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 1 mark
What do you mean by CLASSPATH?
Answer
CLASSPATH is an environment variable (or the -cp option) that tells the JVM and the Java compiler where to find user-defined classes and packages, as directories, JAR or ZIP files. Example: java -cp .;lib/mylib.jar MyClass.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 1 mark
List any three bitwise operators.
Answer
Three bitwise operators in Java are:
&(bitwise AND)|(bitwise OR)^(bitwise XOR)
Others are ~ (complement), << (left shift) and >> (right shift).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 1 mark
Write syntax of any one of the control statements.
Answer
Syntax of the if-else statement:
if (condition) {
// statements when condition is true
} else {
// statements when condition is false
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 1 mark
For which purpose Serialization process is used?
Answer
Serialization converts an object's state into a byte stream so that it can be saved to a file or database, or sent across a network, and later rebuilt (deserialized) into an object. The class must implement the java.io.Serializable interface.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 1 mark
What do you mean by thread priority?
Answer
Thread priority is an integer from 1 (Thread.MIN_PRIORITY) to 10 (Thread.MAX_PRIORITY), with default 5 (Thread.NORM_PRIORITY). It hints to the thread scheduler which thread should get the CPU first. It is set with setPriority(int) and read with getPriority().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 1 mark
What is auto boxing?
Answer
Auto-boxing is the automatic conversion by the Java compiler of a primitive value into its wrapper class object, for example int to Integer: Integer x = 10;. The reverse conversion is called unboxing.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 4 marks
Write a Java program to display all the numbers between -300 to -1 which when divided by 17 gives 7 as remainder and also displays sum of those numbers.
Answer
Java's % operator gives a negative result for negative numbers, so Math.floorMod is used to get the mathematical remainder 7.
public class RemainderSeven {
public static void main(String[] args) {
int sum = 0;
for (int n = -300; n <= -1; n++) {
if (Math.floorMod(n, 17) == 7) {
System.out.println(n);
sum += n;
}
}
System.out.println("Sum = " + sum);
}
}
The numbers displayed are (18 numbers, each of the form ). Their sum is
so the program prints Sum = -2781.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 4 marks
Make two threads, one displays odd number after one second and another thread display even number after half second between -200 and -10.
Answer
class OddThread extends Thread {
public void run() {
try {
for (int i = -199; i <= -11; i += 2) { // odd numbers
System.out.println("Odd: " + i);
Thread.sleep(1000); // 1 second
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
class EvenThread extends Thread {
public void run() {
try {
for (int i = -200; i <= -10; i += 2) { // even numbers
System.out.println("Even: " + i);
Thread.sleep(500); // half second
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
public class TwoThreads {
public static void main(String[] args) {
new OddThread().start();
new EvenThread().start();
}
}
Both threads run concurrently: the odd thread prints every second and the even thread every 500 ms, covering the range -200 to -10.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 4 marks
Write a program that displays all the read-only files of a given folder.
Answer
import java.io.File;
public class ReadOnlyFiles {
public static void main(String[] args) {
File folder = new File(args.length > 0 ? args[0] : ".");
File[] files = folder.listFiles();
if (files == null) {
System.out.println("Not a valid folder");
return;
}
for (File f : files) {
if (f.isFile() && f.canRead() && !f.canWrite()) {
System.out.println(f.getName());
}
}
}
}
canRead() is true and canWrite() is false for a read-only file, so only those files of the given folder are displayed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 4 marks
Make a class named student with private member variables name, age, and public functions to set, display and return values of member variables. Then create ten objects of the student class, set them and display the name of youngest student in the main function of another class named student_demo.
Answer
import java.util.Scanner;
class student {
private String name;
private int age;
public void setData(String n, int a) {
name = n;
age = a;
}
public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
public String getName() { return name; }
public int getAge() { return age; }
}
public class student_demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
student[] s = new student[10];
for (int i = 0; i < 10; i++) {
s[i] = new student();
System.out.print("Enter name and age of student " + (i + 1) + ": ");
String n = sc.next();
int a = sc.nextInt();
s[i].setData(n, a);
}
int y = 0;
for (int i = 1; i < 10; i++) {
if (s[i].getAge() < s[y].getAge()) y = i;
}
System.out.println("Youngest student: " + s[y].getName());
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 4 marks
Write a super class named furniture with member variables weight and price. From this furniture class derive class named chair. These both super and sub classes have functions to set values of their member variables. In another class, named furn_demo make objects of class chair and display values of member variables of those objects.
Answer
class furniture {
double weight;
double price;
void setFurniture(double w, double p) {
weight = w;
price = p;
}
}
class chair extends furniture {
int legs;
String material;
void setChair(int l, String m) {
legs = l;
material = m;
}
}
public class furn_demo {
public static void main(String[] args) {
chair c1 = new chair();
chair c2 = new chair();
c1.setFurniture(5.5, 2500);
c1.setChair(4, "Wood");
c2.setFurniture(3.2, 1800);
c2.setChair(4, "Plastic");
System.out.println("Chair 1: weight=" + c1.weight + " price=Rs " + c1.price
+ " legs=" + c1.legs + " material=" + c1.material);
System.out.println("Chair 2: weight=" + c2.weight + " price=Rs " + c2.price
+ " legs=" + c2.legs + " material=" + c2.material);
}
}
chair inherits weight, price and setFurniture() from furniture and adds its own members and setter.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 5 marks
What is exception? Explain ArrayIndexOutOfBoundsException with an example.
Answer
An exception is an abnormal event that occurs during execution and disrupts the normal flow of the program, such as dividing by zero or accessing an invalid array index. Java handles exceptions with try, catch, finally, throw and throws, so the program can recover instead of terminating abruptly.
ArrayIndexOutOfBoundsException is thrown at run time when an array is accessed with an index that is negative or greater than or equal to its length. Valid indices of an array of size are to .
public class ArrayDemo {
public static void main(String[] args) {
int[] a = new int[5]; // valid indices 0..4
try {
a[5] = 10; // invalid index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
}
System.out.println("Program continues");
}
}
Output:
Exception caught: java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
Program continues
Without the try-catch, the program would stop at a[5] = 10.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2014 AD Model · 5 marks
Write the steps required to create package with an example.
Answer
A package is a group of related classes and interfaces, used to organise code and avoid name conflicts.
Steps:
- Choose a package name and write the
packagestatement as the first line of the source file. - Write the class (declare it
publicso it can be used from other packages). - Save the file in a folder with the same name as the package.
- Compile with the
-doption to place the class file in the package folder. - Import the package in another program and use its classes.
Example:
mypack/Message.java:
package mypack;
public class Message {
public void show() {
System.out.println("Hello from package");
}
}
Compile: javac -d . Message.java (creates the folder mypack with Message.class).
Test.java:
import mypack.Message;
public class Test {
public static void main(String[] args) {
Message m = new Message();
m.show();
}
}
Compile and run: javac Test.java then java Test. If the package is stored elsewhere, set the CLASSPATH so Java can find it.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
What is JVM?
Answer
JVM (Java Virtual Machine) is a software-based virtual machine that loads and executes Java bytecode (.class files), making Java programs platform independent.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
What is operator? List arithmetic operators.
Answer
An operator is a symbol that tells the compiler to perform a specific operation on one or more operands (values or variables).
Arithmetic operators: + (addition), - (subtraction), * (multiplication), / (division), % (modulus/remainder), plus ++ (increment) and -- (decrement).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
Differentiate between interface and base class.
Answer
An interface contains only abstract method declarations (and constants) and is implemented with implements; a class can implement many interfaces. A base class (superclass) can have fields, constructors and fully defined methods, is extended with extends, and a class can extend only one base class.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
Write syntax of switch case statement.
Answer
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements if no case matches
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
What is wrapper class?
Answer
A wrapper class is a class that wraps (encapsulates) a primitive data type into an object, such as Integer for int, Double for double, Character for char and Boolean for boolean. It allows primitives to be used where objects are needed, for example in collections.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
Define thread.
Answer
A thread is a lightweight unit of execution within a program; it is an independent path of execution, and a Java program can run several threads concurrently (multithreading).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
How constant variable is declared in java?
Answer
A constant is declared with the final keyword, which means its value cannot be changed once assigned. By convention it is written in capital letters and is often also static:
final double PI = 3.14159;
public static final int MAX = 100;
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
What is garbage collection?
Answer
Garbage collection is the automatic process in which the JVM finds objects that are no longer referenced by the program and frees the memory they occupy, so the programmer does not need to release memory manually.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 1 mark
What is method overriding?
Answer
Method overriding is when a subclass provides its own implementation of a method that is already defined in its superclass, with the same name, parameters and return type. The version called is decided at run time (runtime polymorphism).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 4 marks
Write a Java program to display all the even numbers from 1 to 500.
Answer
public class EvenNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 500; i++) {
if (i % 2 == 0) {
System.out.print(i + " ");
}
}
}
}
The loop runs from 1 to 500 and prints i only when the remainder after dividing by 2 is 0. The output is 2 4 6 ... 500 (250 numbers). (Looping with i += 2 starting from 2 gives the same result.)
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 4 marks
Make a thread using runnable interface to display number from 1 to 20; each number should be displayed in the interval of 2 seconds.
Answer
class NumberTask implements Runnable {
public void run() {
for (int i = 1; i <= 20; i++) {
System.out.println(i);
try {
Thread.sleep(2000); // wait 2 seconds
} catch (InterruptedException e) {
System.out.println("Interrupted: " + e);
}
}
}
}
public class RunnableDemo {
public static void main(String[] args) {
Thread t = new Thread(new NumberTask());
t.start();
}
}
The class implements Runnable and puts the code in run(). A Thread object is created with the task and start() begins execution. Thread.sleep(2000) pauses the thread for 2000 ms after each number.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 4 marks
Write a program that reads line of text from keyboard and write to file. Also read the content of the same file and display on monitor.
Answer
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
try {
// read a line from keyboard
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a line of text:");
String line = kb.readLine();
// write to file
FileWriter fw = new FileWriter("data.txt");
fw.write(line);
fw.close();
// read the file and display
BufferedReader fr = new BufferedReader(new FileReader("data.txt"));
String s;
System.out.println("Content of file:");
while ((s = fr.readLine()) != null) {
System.out.println(s);
}
fr.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
The text typed by the user is written to data.txt with FileWriter, then the same file is opened with FileReader (wrapped in BufferedReader) and its content is printed on the screen.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 4 marks
Make class "Rectangle" with attributes length and breadth. The class contains methods compute Area and display Area. Write a program with main method that creates two objects of Rectangle class and find their areas and display area of larger rectangle.
Answer
class Rectangle {
double length, breadth;
Rectangle(double length, double breadth) {
this.length = length;
this.breadth = breadth;
}
double computeArea() {
return length * breadth;
}
void displayArea() {
System.out.println("Area = " + computeArea());
}
}
public class RectangleDemo {
public static void main(String[] args) {
Rectangle r1 = new Rectangle(10, 5);
Rectangle r2 = new Rectangle(8, 7);
double a1 = r1.computeArea();
double a2 = r2.computeArea();
System.out.println("Area of first rectangle = " + a1);
System.out.println("Area of second rectangle = " + a2);
System.out.print("Larger rectangle: ");
if (a1 > a2) {
r1.displayArea();
} else {
r2.displayArea();
}
}
}
Area of first = 50, area of second = 56, so the output shows Area = 56.0 for the larger rectangle.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 4 marks
Make an interface named num with two functions int add(int x, int y) and int diff(int x, int y) then make a class that implements that interface num.
Answer
interface num {
int add(int x, int y);
int diff(int x, int y);
}
class Calculator implements num {
public int add(int x, int y) {
return x + y;
}
public int diff(int x, int y) {
return x - y;
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println("Sum = " + c.add(10, 4));
System.out.println("Difference = " + c.diff(10, 4));
}
}
The interface only declares the methods. The class Calculator implements it and must define both methods as public. Output: Sum = 14 and Difference = 6.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 5 marks
What is exception? Explain nested try-catch statement with example.
Answer
An exception is an abnormal event or runtime error that occurs during program execution and disrupts the normal flow of instructions, for example dividing by zero, accessing an array index out of range or opening a file that does not exist. Java handles exceptions using try, catch, finally, throw and throws, so the program can recover instead of terminating abruptly.
Nested try-catch statement
A try block can be placed inside another try (or catch) block. The inner try handles specific exceptions; if it has no matching catch, the exception passes to the catch blocks of the outer try.
public class NestedTry {
public static void main(String[] args) {
try { // outer try
int[] a = {10, 20, 30};
System.out.println("Outer block started");
try { // inner try
int result = a[1] / 0; // ArithmeticException
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Inner catch: division by zero");
}
System.out.println(a[5]); // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Outer catch: invalid array index");
} finally {
System.out.println("Finally block executed");
}
}
}
Output:
Outer block started
Inner catch: division by zero
Outer catch: invalid array index
Finally block executed
The division error is handled by the inner catch. The invalid index occurs in the outer try and is handled by the outer catch. If the inner catch did not match the exception type, control would go to the outer catch blocks.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2015 AD · 5 marks
Define package? Write down steps to create package. Explain with examples.
Answer
A package is a collection of related classes and interfaces grouped under one name. It organises code, avoids name conflicts, provides access protection and makes classes easy to reuse. Java has built-in packages (java.util, java.io) and user-defined packages.
Steps to create a package
- Write the
packagestatement as the first line of the source file. - Declare the class (and its needed members) as
publicso that it can be used outside the package. - Save the file in a folder with the same name as the package.
- Compile it with the
-doption so that the class file is placed in the package folder. - Import the package in another program with
importand use the class.
Example
File mypack/Message.java:
package mypack;
public class Message {
public void show() {
System.out.println("Hello from package mypack");
}
}
Compile: javac -d . Message.java
File TestPackage.java:
import mypack.Message;
public class TestPackage {
public static void main(String[] args) {
Message m = new Message();
m.show();
}
}
Compile and run: javac TestPackage.java then java TestPackage. Output: Hello from package mypack.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
Define recursion.
Answer
Recursion is a technique in which a method calls itself, directly or indirectly, to solve a problem by breaking it into smaller sub-problems, until a base condition stops the calls (for example, computing a factorial).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
Why is Java known as a strongly typed language?
Answer
Java is strongly typed because every variable and expression must have a declared data type, which is checked at compile time, and the compiler does not allow incompatible types to be mixed without explicit conversion (casting).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
Differentiate between private and public constructor.
Answer
A public constructor can be accessed from any class, so objects of the class can be created anywhere. A private constructor can be accessed only inside its own class, so outside classes cannot create objects directly; it is used in the singleton pattern and for utility classes.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
Why identifiers can't be used as keywords?
Answer
Keywords are reserved words that have a predefined meaning for the compiler (such as class, int, if). If an identifier used the same name, the compiler could not tell whether it means the keyword or the user-defined name, causing ambiguity and syntax errors. So keywords cannot be used as identifiers.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
What is the role of JVM?
Answer
The JVM loads the compiled bytecode (.class files), verifies it, and executes it by interpreting it or compiling it to machine code with the JIT compiler. It also manages memory (including garbage collection) and provides a runtime environment, which makes Java platform independent.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
List out 3 OOP principles.
Answer
Three OOP principles: encapsulation, inheritance and polymorphism (abstraction is another).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
What is the use of finalize() method?
Answer
The finalize() method is called by the garbage collector just before an object is destroyed, and is used to perform clean-up actions such as releasing resources (closing files or connections) held by the object.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
What are the different threads states?
Answer
The states of a thread are: New, Runnable, Running, Blocked/Waiting (including Timed Waiting/Sleeping) and Terminated (Dead).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
How can variable length arguments be helpful?
Answer
Variable length arguments (varargs, declared as type... name) let a method accept any number of arguments of the same type, including none. The compiler packs them into an array, so one method replaces many overloaded versions and callers need not build an array by hand.
static int sum(int... n) { int s = 0; for (int x : n) s += x; return s; }
// sum(), sum(1,2), sum(1,2,3,4) all work
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 1 mark
Define auto-boxing.
Answer
Auto-boxing is the automatic conversion by the Java compiler of a primitive value into its corresponding wrapper class object. For example, Integer a = 10; converts the int 10 into an Integer object without calling Integer.valueOf() explicitly.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 4 marks
Write a Java program that asks the user to enter numbers in an array of size 'n'. Then displays only the numbers that are divisible by 2 and 3.
Answer
import java.util.Scanner;
public class DivisibleBy2And3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter size n: ");
int n = sc.nextInt();
int[] a = new int[n];
System.out.println("Enter " + n + " numbers:");
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
System.out.println("Numbers divisible by both 2 and 3:");
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 0 && a[i] % 3 == 0) {
System.out.println(a[i]);
}
}
sc.close();
}
}
A number divisible by both 2 and 3 is divisible by 6; the condition a[i] % 2 == 0 && a[i] % 3 == 0 tests this.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 4 marks
Create a class Student with instance variables roll no and two methods to read and display the roll no. Then, create another class Test that inherits class Student, consisting of its own instance variables to hold the marks of two subjects and also methods to read and display the marks. Finally, create another class Result which inherits class Test. It also has its own instance variable total to hold off two marks scored by the student. Similarly, it has methods to calculate and display the total. Create some instances of above classes and demonstrate inheritance.
Answer
import java.util.Scanner;
class Student {
int rollNo;
Scanner sc = new Scanner(System.in);
void readRoll() {
System.out.print("Enter roll no: ");
rollNo = sc.nextInt();
}
void displayRoll() {
System.out.println("Roll no: " + rollNo);
}
}
class Test extends Student {
int m1, m2;
void readMarks() {
System.out.print("Enter marks of two subjects: ");
m1 = sc.nextInt();
m2 = sc.nextInt();
}
void displayMarks() {
System.out.println("Marks: " + m1 + ", " + m2);
}
}
class Result extends Test {
int total;
void calculateTotal() {
total = m1 + m2;
}
void displayTotal() {
System.out.println("Total: " + total);
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Result r1 = new Result();
r1.readRoll();
r1.readMarks();
r1.calculateTotal();
r1.displayRoll();
r1.displayMarks();
r1.displayTotal();
Result r2 = new Result();
r2.readRoll();
r2.readMarks();
r2.calculateTotal();
r2.displayRoll();
r2.displayMarks();
r2.displayTotal();
}
}
This is multilevel inheritance: Result inherits from Test, which inherits from Student, so a Result object can use the methods of all three classes.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 4 marks
Create an interface shape which has method get_data() and display_area(). Create two classes Rectangle and Square which implements this interface. Define the instance variables of these classes as per requirement in class itself. Create some instances of Rectangle and Square classes and demonstrate interface implementation by classes.
Answer
import java.util.Scanner;
interface Shape {
void get_data();
void display_area();
}
class Rectangle implements Shape {
double length, breadth;
public void get_data() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter length and breadth: ");
length = sc.nextDouble();
breadth = sc.nextDouble();
}
public void display_area() {
System.out.println("Area of rectangle = " + (length * breadth));
}
}
class Square implements Shape {
double side;
public void get_data() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter side: ");
side = sc.nextDouble();
}
public void display_area() {
System.out.println("Area of square = " + (side * side));
}
}
public class ShapeDemo {
public static void main(String[] args) {
Shape r = new Rectangle();
Shape s = new Square();
r.get_data();
r.display_area();
s.get_data();
s.display_area();
}
}
Both classes provide bodies for every method of the interface (declared public), and an interface reference can point to either object.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 4 marks
Define a string array size 10 and store 10 countries' name in it. Then list name of countries that ends with letter 'a'.
Answer
import java.util.Scanner;
public class CountriesEndingWithA {
public static void main(String[] args) {
String[] countries = new String[10];
Scanner sc = new Scanner(System.in);
System.out.println("Enter 10 country names:");
for (int i = 0; i < 10; i++) {
countries[i] = sc.nextLine().trim();
}
System.out.println("Countries ending with 'a':");
for (String c : countries) {
if (c.toLowerCase().endsWith("a")) {
System.out.println(c);
}
}
}
}
For example, India, China, America and Canada are listed; Nepal is not.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 4 marks
Write a program to take employee id, name, address, DOB and phone number from user and the store it in a file "Emp.txt". Also display the contents of "Emp.txt".
Answer
import java.io.*;
import java.util.Scanner;
public class EmployeeFile {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.print("Employee id: ");
String id = sc.nextLine();
System.out.print("Name: ");
String name = sc.nextLine();
System.out.print("Address: ");
String address = sc.nextLine();
System.out.print("DOB: ");
String dob = sc.nextLine();
System.out.print("Phone number: ");
String phone = sc.nextLine();
try (PrintWriter pw = new PrintWriter(new FileWriter("Emp.txt"))) {
pw.println("Id: " + id);
pw.println("Name: " + name);
pw.println("Address: " + address);
pw.println("DOB: " + dob);
pw.println("Phone: " + phone);
}
System.out.println("\nContents of Emp.txt:");
try (BufferedReader br = new BufferedReader(new FileReader("Emp.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 5 marks
What is multithreading? Write a program to demonstrate multithreading in Java.
Answer
Multithreading is the ability of a program to run two or more threads (independent paths of execution) concurrently within one process. Threads share the same memory, so they are lightweight. It improves CPU utilisation and responsiveness, for example one thread handling user input while another downloads a file.
In Java a thread is created by extending the Thread class or implementing the Runnable interface.
class Printer extends Thread {
private String label;
Printer(String label) {
this.label = label;
}
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(label + " : " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class MultiThreadDemo {
public static void main(String[] args) {
Printer t1 = new Printer("Thread-A");
Printer t2 = new Printer("Thread-B");
t1.start();
t2.start();
}
}
Calling start() makes the JVM run run() in a new thread, so the outputs of Thread-A and Thread-B are interleaved.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2017 AD · 5 marks
Explain user define exception in Java with a suitable example.
Answer
A user-defined (custom) exception is an exception class created by the programmer for an application-specific error condition that the built-in exceptions do not describe. It is made by extending Exception (checked) or RuntimeException (unchecked). It is raised with throw and, if checked, declared with throws and handled with try-catch.
Steps:
- Create a class that extends
Exceptionand passes a message tosuper(). - Detect the error condition and
throw newthe exception. - Catch it with
catch.
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
super(msg);
}
}
public class CustomExceptionDemo {
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());
}
}
}
Output:
Eligible to vote
Caught: Age 15 is not eligible to vote
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
What is the significance of package?
Answer
A package groups related classes and interfaces into one namespace. Its significance: it organises code, avoids name conflicts between classes, gives access protection (package-private and protected access), and makes classes easy to find and reuse through import.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
List any 4 features of Java Programming Language.
Answer
- Simple: easy to learn, with no pointers or operator overloading.
- Object-oriented: supports classes, inheritance, encapsulation and polymorphism.
- Platform independent: bytecode runs on any system that has a JVM.
- Robust and secure: strong type checking, exception handling and automatic garbage collection.
(Multithreaded and distributed are also features.)
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
Why java is called architecture neutral language?
Answer
Java source code is compiled into bytecode, which does not depend on any processor architecture. Primitive types also have fixed sizes (an int is always 32 bits) on every machine. The bytecode can therefore run on any hardware that has a JVM, so Java is called architecture neutral.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
How has the concept of exception handling helped Java to robust?
Answer
Exception handling lets a program detect runtime errors with try, catch, throw, throws and finally and recover from them instead of crashing. Normal code is separated from error-handling code, resources are released in finally, and the program keeps running in a controlled way. This makes Java programs reliable, that is, robust.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
Differentiate between constructor and method.
Answer
| Constructor | Method |
|---|---|
| Has the same name as the class | Can have any valid name |
Has no return type (not even void) | Must have a return type or void |
Called automatically when an object is created with new | Called explicitly on an object or class |
| Used to initialise the object | Used to perform operations or define behaviour |
| Not inherited | Inherited by subclasses |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
What is the advantage of variable length argument?
Answer
A variable length argument (type... name) lets a method take any number of arguments, even zero. This avoids writing many overloaded methods and avoids creating an array manually before the call, which makes the code shorter and more flexible.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
What is the use of Serialization process?
Answer
Serialization converts an object's state into a byte stream so that it can be saved to a file or database, or sent over a network. Deserialization rebuilds the object from the stream. The class must implement java.io.Serializable. It is used for persisting objects and for communication such as RMI.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
What are the uses of "extends" and "implements" keywords?
Answer
extendsis used by a class to inherit from another class (class B extends A), and by an interface to inherit from other interfaces.implementsis used by a class to implement one or more interfaces (class C implements I1, I2), so it must define all their abstract methods.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
How does interface differ from abstract class?
Answer
| Interface | Abstract class |
|---|---|
Declares behaviour; methods are abstract by default (plus default and static methods) | Can have both abstract and concrete methods |
Variables are public static final constants | Can have instance variables of any kind |
| A class can implement many interfaces | A class can extend only one abstract class |
| Has no constructors | Can have constructors |
Uses implements | Uses extends |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 1 mark
Define Autoboxing.
Answer
Autoboxing is the automatic conversion of a primitive type into an object of its wrapper class by the Java compiler, for example Integer x = 5; (int to Integer) or Double d = 2.5;. The reverse conversion is called unboxing.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 4 marks
Write a program that asks the user to enter elements in a matrix of size m x n and then display the sum of elements.
Answer
import java.util.Scanner;
public class MatrixSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows m and columns n: ");
int m = sc.nextInt();
int n = sc.nextInt();
int[][] a = new int[m][n];
int sum = 0;
System.out.println("Enter the elements:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = sc.nextInt();
sum += a[i][j];
}
}
System.out.println("Sum of all elements = " + sum);
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 4 marks
List the two ways to create a Thread. Discuss the life cycle of Thread.
Answer
Two ways to create a thread
- Extend the
Threadclass, overriderun(), create an object and callstart().
class A extends Thread {
public void run() { System.out.println("Running"); }
}
// new A().start();
- Implement the
Runnableinterface, definerun(), pass the object to aThreadconstructor and callstart().
class B implements Runnable {
public void run() { System.out.println("Running"); }
}
// new Thread(new B()).start();
Life cycle of a thread
- New: the thread object is created but
start()has not been called. - Runnable: after
start(), the thread is ready and waits for the CPU (or is running). - Running: the scheduler gives the thread the CPU and
run()executes. - Blocked / Waiting / Timed waiting: the thread is temporarily inactive because of
sleep(),wait(),join(), I/O or a lock held by another thread. It returns to Runnable when the condition ends. - Terminated (Dead):
run()completes or an uncaught exception occurs. The thread cannot be restarted.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 4 marks
Create an abstract class called Fmachine, having methods getdata() and putdata(). Derive a class Airplane, having instance variables code, name, capacity and methods getdata() and putdata() (that overrides Fmachine's getdata() and putdata()) to read and display the result.
Answer
import java.util.Scanner;
abstract class Fmachine {
abstract void getdata();
abstract void putdata();
}
class Airplane extends Fmachine {
int code;
String name;
int capacity;
void getdata() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter code: ");
code = sc.nextInt();
sc.nextLine();
System.out.print("Enter name: ");
name = sc.nextLine();
System.out.print("Enter capacity: ");
capacity = sc.nextInt();
}
void putdata() {
System.out.println("Code: " + code);
System.out.println("Name: " + name);
System.out.println("Capacity: " + capacity);
}
}
public class FmachineDemo {
public static void main(String[] args) {
Fmachine f = new Airplane();
f.getdata();
f.putdata();
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 4 marks
Write a program to create a string array of size 'n' and prompt the user to enter 10 names in it. Then you are required to replace all 'i' with '!' and display the result.
Answer
import java.util.Scanner;
public class ReplaceI {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = 10;
String[] names = new String[n];
System.out.println("Enter " + n + " names:");
for (int i = 0; i < n; i++) {
names[i] = sc.nextLine();
}
System.out.println("After replacing 'i' with '!':");
for (int i = 0; i < n; i++) {
names[i] = names[i].replace('i', '!');
System.out.println(names[i]);
}
}
}
Only lowercase i is replaced. To replace uppercase I as well, use replaceAll("[iI]", "!").
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 4 marks
Write a program that ask the user to enter his/her name, address and college and store it in a file called "student.txt". Then copy the contents of "student.txt" to "pupil.txt". Also display the contents of "pupil.txt".
Answer
import java.io.*;
import java.util.Scanner;
public class StudentFileCopy {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.print("Name: ");
String name = sc.nextLine();
System.out.print("Address: ");
String address = sc.nextLine();
System.out.print("College: ");
String college = sc.nextLine();
try (PrintWriter pw = new PrintWriter(new FileWriter("student.txt"))) {
pw.println(name);
pw.println(address);
pw.println(college);
}
try (BufferedReader br = new BufferedReader(new FileReader("student.txt"));
PrintWriter pw = new PrintWriter(new FileWriter("pupil.txt"))) {
String line;
while ((line = br.readLine()) != null) {
pw.println(line);
}
}
System.out.println("Contents of pupil.txt:");
try (BufferedReader br = new BufferedReader(new FileReader("pupil.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 5 marks
Define exception. Explain how try with catch is different from try with finally with suitable examples.
Answer
Exception: an exception is an abnormal event that occurs during program execution and disrupts the normal flow of instructions, for example dividing by zero or accessing an array element out of range. In Java it is an object of a subclass of Throwable that can be handled.
try with catch: the try block holds code that may throw an exception. If one occurs, control passes to the matching catch block, which handles it. If no exception occurs, the catch block is skipped. It is used to handle the error.
try {
int r = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
System.out.println("Program continues");
try with finally: the finally block always executes, whether or not an exception occurs, and is used for clean-up such as closing files. With only try and finally (no catch), the exception is not handled: the finally block runs and then the exception propagates upward and may terminate the program.
try {
int r = 10 / 0;
} finally {
System.out.println("Cleanup always runs");
}
// ArithmeticException then propagates and the program terminates
Difference
| try-catch | try-finally |
|---|---|
| Catches and handles the exception | Does not handle the exception |
catch runs only when the matching exception occurs | finally always runs |
| Program can continue after the block | If an exception occurs, it still propagates after finally |
| Used for error recovery | Used for resource clean-up |
The two are often combined as try-catch-finally.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2018 AD · 5 marks
What is multiple inheritance? Write a program that demonstrates how multiple inheritance is achieved in java.
Answer
Multiple inheritance means a class inherits properties and behaviour from more than one parent. Java does not support multiple inheritance through classes, because it causes ambiguity (the diamond problem) when two parents define the same method. Java achieves it through interfaces: a class can implement any number of interfaces.
interface Printable {
void print();
}
interface Showable {
void show();
}
class Document implements Printable, Showable {
public void print() {
System.out.println("Printing document");
}
public void show() {
System.out.println("Showing document");
}
}
public class MultipleInheritanceDemo {
public static void main(String[] args) {
Document d = new Document();
d.print();
d.show();
}
}
Output:
Printing document
Showing document
Document gets the behaviour of both Printable and Showable. Since the interface methods have no implementation, there is no ambiguity.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
Java is called platform independent. Why?
Answer
The Java compiler converts source code into platform-neutral bytecode (.class files), not machine code. This bytecode can run on any operating system that has a Java Virtual Machine (JVM), because the JVM translates it for that platform. Hence "write once, run anywhere".
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
Define AND operator.
Answer
The AND operator combines two conditions and gives true only when both are true. In Java the logical AND is && (short-circuit), for example (a > 0 && b > 0). The & operator is the non-short-circuit and bitwise AND.
| A | B | A && B |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
What is dynamic method dispatch?
Answer
Dynamic method dispatch is the run-time mechanism by which a call to an overridden method is resolved according to the type of the object being referred to, not the type of the reference variable. It is how Java implements run-time polymorphism.
class A { void show() { System.out.println("A"); } }
class B extends A { void show() { System.out.println("B"); } }
A ref = new B();
ref.show(); // prints B
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
What do you mean by thread priorities?
Answer
Thread priority is an integer from 1 (Thread.MIN_PRIORITY) to 10 (Thread.MAX_PRIORITY), with a default of 5 (Thread.NORM_PRIORITY). The scheduler uses it as a hint to decide which runnable thread gets the CPU first; higher-priority threads are generally preferred. It is set with setPriority(int) and read with getPriority().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
List any two relational operators with syntax.
Answer
- Greater than:
a > bgives true ifais greater thanb. - Equal to:
a == bgives true ifaandbare equal.
(Others are <, >=, <= and !=.)
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
Write the use of final keyword.
Answer
The final keyword restricts modification:
- final variable: its value cannot be changed once assigned (a constant), e.g.
final double PI = 3.14; - final method: it cannot be overridden by subclasses.
- final class: it cannot be extended (inherited), e.g.
String.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
What is autoboxing and unboxing?
Answer
Autoboxing is the automatic conversion of a primitive value into an object of its wrapper class, e.g. Integer a = 10;.
Unboxing is the automatic conversion of a wrapper object back into its primitive value, e.g. int b = a;.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 1 mark
What is synchronization?
Answer
Synchronization is the mechanism that lets only one thread at a time access a shared resource or critical section, which prevents data inconsistency when several threads work on the same data. In Java it is done with the synchronized keyword on a method or block, e.g. synchronized void deposit(int amt) { ... }.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 4 marks
Write a Java program that prints first 10 Fibonacci numbers.
Answer
public class Fibonacci {
public static void main(String[] args) {
int a = 0, b = 1;
System.out.println("First 10 Fibonacci numbers:");
for (int i = 1; i <= 10; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
}
Output:
0 1 1 2 3 5 8 13 21 34
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 4 marks
Make two threads, one display name of English months after one second and another thread display name of days after one and half second.
Answer
class MonthThread extends Thread {
public void run() {
String[] months = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
for (String m : months) {
System.out.println(m);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
class DayThread extends Thread {
public void run() {
String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
for (String d : days) {
System.out.println(d);
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class TwoThreads {
public static void main(String[] args) {
new MonthThread().start();
new DayThread().start();
}
}
Thread.sleep(1000) pauses the month thread for 1 second and Thread.sleep(1500) pauses the day thread for 1.5 seconds.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 4 marks
Create a class Number with three integer instance variables x, y and z. The class will have one constructor to initialize instance variables. The class also will contain method getMax() method that will return the largest number. Create a class NumberDemo with main method that will create an object of Number and will print the largest number.
Answer
class Number {
int x, y, z;
Number(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
int getMax() {
int max = x;
if (y > max) max = y;
if (z > max) max = z;
return max;
}
}
public class NumberDemo {
public static void main(String[] args) {
Number n = new Number(12, 45, 30);
System.out.println("Largest number = " + n.getMax());
}
}
Output: Largest number = 45
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 4 marks
Create a class Box with instance variables length, breadth and height. Add one method getVolume() to compute the volume of box. Use suitable constructors. Create a subclass BoxWeight that extends Box that add one variable weight. Add two methods setweight() and getWeight() that sets and displays the weight of box to this class. Add suitable constructors. Your class should use super keyword to call superclass constructor. Then create a class BoxDemo with main() method that creates two objects of BoxWeight and display volumes and weights of both boxes
Answer
class Box {
double length, breadth, height;
Box() {
length = breadth = height = 0;
}
Box(double l, double b, double h) {
length = l;
breadth = b;
height = h;
}
double getVolume() {
return length * breadth * height;
}
}
class BoxWeight extends Box {
double weight;
BoxWeight() {
super();
weight = 0;
}
BoxWeight(double l, double b, double h, double w) {
super(l, b, h);
weight = w;
}
void setweight(double w) {
weight = w;
}
void getWeight() {
System.out.println("Weight = " + weight);
}
}
public class BoxDemo {
public static void main(String[] args) {
BoxWeight b1 = new BoxWeight(2, 3, 4, 5.5);
BoxWeight b2 = new BoxWeight(1, 2, 3, 2.5);
System.out.println("Box 1 volume = " + b1.getVolume());
b1.getWeight();
System.out.println("Box 2 volume = " + b2.getVolume());
b2.getWeight();
}
}
Output:
Box 1 volume = 24.0
Weight = 5.5
Box 2 volume = 6.0
Weight = 2.5
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 4 marks
Write a Java program that reads content of the Directory and displays on monitor.
Answer
import java.io.File;
import java.util.Scanner;
public class ReadDirectory {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter directory path: ");
String path = sc.nextLine();
File dir = new File(path);
if (dir.exists() && dir.isDirectory()) {
File[] files = dir.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
System.out.println("[DIR] " + f.getName());
} else {
System.out.println("[FILE] " + f.getName());
}
}
}
} else {
System.out.println("Not a valid directory");
}
}
}
listFiles() returns the files and sub-directories of the directory as an array of File objects.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 5 marks
What is exception? Why is it important to handle exception? Explain.
Answer
Exception: an exception is an event that occurs at run time and disrupts the normal flow of a program, such as dividing by zero (ArithmeticException), accessing an invalid array index (ArrayIndexOutOfBoundsException), using a null reference (NullPointerException) or opening a missing file (FileNotFoundException). In Java, exceptions are objects of subclasses of Throwable.
Why handling exceptions is important
- Prevents abnormal termination: without handling, the program stops at the error. Handling lets it recover and continue.
- Separates error-handling code from normal code, which makes programs cleaner and easier to read.
- Gives meaningful error messages to the user instead of a raw stack trace.
- Resource safety: the
finallyblock can close files, connections and other resources even when an error occurs. - Propagation of errors: errors can be passed up the call stack with
throwsto a method that knows how to deal with them. - Robust, reliable software: the application stays stable even with bad input or unexpected conditions.
Example
try {
int[] a = new int[3];
a[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index: " + e.getMessage());
} finally {
System.out.println("Done");
}
Output:
Invalid index: Index 5 out of bounds for length 3
Done
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2019 AD · 5 marks
Explain importance of encapsulation and inheritance with example.
Answer
Encapsulation is the binding of data (fields) and the methods that operate on them into a single unit (class), while hiding the data from outside access by making fields private and exposing them only through public getters and setters.
Importance of encapsulation
- Data hiding and security: outside code cannot corrupt the internal state directly.
- Validation and control: setters can reject invalid values (for example, a negative balance).
- Flexibility and maintainability: the internal implementation can change without affecting the classes that use it.
- Reusability: a well-encapsulated class is a self-contained, easily tested unit.
Inheritance is the mechanism by which a subclass acquires the fields and methods of a superclass using the extends keyword, and can add or override behaviour.
Importance of inheritance
- Code reuse: common code is written once in the superclass.
- Method overriding and runtime polymorphism: a subclass can give its own implementation of an inherited method.
- Logical hierarchy: it models "is-a" relationships (a
Studentis aPerson) and makes extension easy.
Example
class Person {
private String name; // encapsulated
private int age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) {
if (age > 0) this.age = age; // validation
}
}
class Student extends Person { // inheritance
private int roll;
public void setRoll(int roll) { this.roll = roll; }
public void show() {
System.out.println(getName() + " " + getAge() + " " + roll);
}
}
public class Test {
public static void main(String[] args) {
Student s = new Student();
s.setName("Ram"); // inherited method
s.setAge(20);
s.setRoll(5);
s.show(); // Ram 20 5
}
}
Here name and age are hidden in Person (encapsulation), and Student reuses them without rewriting any code (inheritance).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 AD · 10 marks
Give reasons to justify the following statements.
a. Java is platform independent programming language.
b. Java is object oriented programming language.
Answer
(a) Java is a platform independent programming language.
- A Java source file is compiled by
javacnot into machine code of a particular processor, but into bytecode (.classfile). - Bytecode is executed by the Java Virtual Machine (JVM). A JVM exists for every major platform (Windows, Linux, macOS, etc.).
- The same
.classfile therefore runs unchanged on any system having a JVM: "Write Once, Run Anywhere". - Java also fixes the size of primitive types (an
intis always 32 bits) and has a standard library, so behaviour does not vary with the platform.
Flow: Source code (.java) → compiler → bytecode (.class) → JVM (Windows / Linux / macOS) → output.
Only the JVM is platform dependent; the program itself is not.
(b) Java is an object oriented programming language.
Java is built around classes and objects, and it supports the four main OOP principles:
- Encapsulation: data and methods are bound in a class, and data is hidden using access modifiers (
private,public, etc.). - Inheritance: a class can extend another class (
extends) and reuse its members. - Polymorphism: through method overloading (compile time) and method overriding (run time).
- Abstraction: through abstract classes and interfaces.
All code lives inside classes, and everything except the primitive types is an object (a class derives from Object). Java is therefore considered an object oriented language, although it is not purely so because it retains the eight primitive types.
class Animal { void sound() { System.out.println("Sound"); } }
class Dog extends Animal { void sound() { System.out.println("Bark"); } }
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 AD · 10 marks
Write a program that displays only the prime numbers between any two integers.
Answer
The program reads two integers, then checks every number in the range for primality. A number is prime if it has no divisor from to .
import java.util.Scanner;
public class PrimeRange {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; (long) i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first integer: ");
int a = sc.nextInt();
System.out.print("Enter second integer: ");
int b = sc.nextInt();
int start = Math.min(a, b);
int end = Math.max(a, b);
System.out.println("Prime numbers between " + start + " and " + end + ":");
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
System.out.println();
sc.close();
}
}
Sample run
Enter first integer: 10
Enter second integer: 30
Prime numbers between 10 and 30:
11 13 17 19 23 29
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 AD · 10 marks
Create a class named 'Member' having the following data members - name, age, phone, address, salary. It also has a method named 'setMemberDetails' which initializes all data members and another method 'printMemberDetails' which displays the member details. Second classes 'Employee' and 'Manager' inherit the 'Member' class. The 'Employee' and 'Manager' classes have data members 'specialization' and 'department' respectively. The 'Employee' class contains a method named 'setSpecialization' and 'printSpecialization' and 'Manager' class contains a method named 'setDepartment' and 'printDepartment'. Provide a main class and create objects of 'Employee' and 'Manager', set the details and print them.
Answer
class Member {
String name;
int age;
String phone;
String address;
double salary;
void setMemberDetails(String name, int age, String phone,
String address, double salary) {
this.name = name;
this.age = age;
this.phone = phone;
this.address = address;
this.salary = salary;
}
void printMemberDetails() {
System.out.println("Name : " + name);
System.out.println("Age : " + age);
System.out.println("Phone : " + phone);
System.out.println("Address : " + address);
System.out.println("Salary : " + salary);
}
}
class Employee extends Member {
String specialization;
void setSpecialization(String specialization) {
this.specialization = specialization;
}
void printSpecialization() {
System.out.println("Specialization : " + specialization);
}
}
class Manager extends Member {
String department;
void setDepartment(String department) {
this.department = department;
}
void printDepartment() {
System.out.println("Department : " + department);
}
}
public class MainClass {
public static void main(String[] args) {
Employee e = new Employee();
e.setMemberDetails("Sita Sharma", 28, "9841000001", "Kathmandu", 45000);
e.setSpecialization("Java Development");
Manager m = new Manager();
m.setMemberDetails("Ram Thapa", 40, "9851000002", "Lalitpur", 90000);
m.setDepartment("Finance");
System.out.println("--- Employee ---");
e.printMemberDetails();
e.printSpecialization();
System.out.println("--- Manager ---");
m.printMemberDetails();
m.printDepartment();
}
}
Employee and Manager inherit the data members and methods of Member using extends, and each adds its own member and methods.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 AD · 10 marks
Why is it important to handle exception? Write a program to illustrate exception handling using try/catch.
Answer
An exception is an abnormal event during execution (division by zero, invalid array index, missing file, bad input) that disrupts the normal flow of the program.
Why handling exceptions is important
- Prevents abnormal termination: without handling, the program crashes at the point of error.
- Keeps normal flow: the rest of the program continues to run after the error is dealt with.
- Separates error-handling code from regular logic, making code cleaner.
- User-friendly messages can be shown instead of stack traces.
- Resource safety: the
finallyblock ensures files, connections, etc. are always closed. - Reliability and robustness of the software are improved.
Program
import java.util.Scanner;
public class ExceptionDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter numerator: ");
int a = sc.nextInt();
System.out.print("Enter denominator: ");
int b = sc.nextInt();
int result = a / b; // may throw ArithmeticException
System.out.println("Result = " + result);
int[] arr = new int[3];
arr[5] = result; // may throw ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Error: division by zero is not allowed.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: invalid array index. " + e.getMessage());
} catch (Exception e) {
System.out.println("Error: " + e);
} finally {
System.out.println("Finally block executed.");
sc.close();
}
System.out.println("Program continues normally.");
}
}
For input 10 and 0, the output is "Error: division by zero is not allowed.", then "Finally block executed." and "Program continues normally."
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 AD · 10 marks
Explain different states in a thread's life cycle. Write a complete java program to create a thread.
Answer
Life cycle of a thread
A thread passes through the following states:
- New: the thread object has been created (
new Thread(...)) butstart()has not been called. - Runnable: after
start(), the thread is ready to run and waits for CPU time from the scheduler (it may also be running). - Running: the scheduler has selected the thread and its
run()method is executing. - Blocked / Waiting / Timed Waiting (non-runnable):
- Blocked: waiting to acquire a monitor lock held by another thread.
- Waiting: waiting indefinitely for another thread (
wait(),join()). - Timed waiting: waiting for a fixed time (
sleep(ms),wait(ms),join(ms)). The thread returns to Runnable when the condition ends.
- Terminated (Dead):
run()has completed or an uncaught exception ended the thread. It cannot be restarted.
Flow: New → (start) → Runnable ⇄ Running → Terminated, with Running → Blocked/Waiting → Runnable.
Program to create a thread
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(getName() + " : " + i);
try {
Thread.sleep(500); // timed waiting
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
MyThread t1 = new MyThread(); // New
t1.start(); // Runnable
t1.join(); // main waits until t1 terminates
System.out.println("Thread finished.");
}
}
A thread can alternatively be created by implementing Runnable and passing the object to new Thread(obj).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 AD · 10 marks
Write a program that stores the text "Tribhuvan University" into a file named "tu.txt" and reads same file and displays the content.
Answer
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
// Write text to tu.txt
try (FileWriter fw = new FileWriter("tu.txt")) {
fw.write("Tribhuvan University");
System.out.println("Text written to tu.txt");
} catch (IOException e) {
System.out.println("Write error: " + e.getMessage());
}
// Read the same file and display its content
try (BufferedReader br = new BufferedReader(new FileReader("tu.txt"))) {
String line;
System.out.println("Content of tu.txt:");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Read error: " + e.getMessage());
}
}
}
Output
Text written to tu.txt
Content of tu.txt:
Tribhuvan University
The try-with-resources statement closes the file automatically after use.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 AD · 10 marks
What is method overloading? Explain. Write a program to illustrate it.
Answer
Method overloading means defining two or more methods in the same class with the same name but different parameter lists (different number of parameters, different types, or different order of types). It is a form of compile-time (static) polymorphism.
Key points:
- The compiler decides which method to call from the arguments passed.
- The return type alone cannot distinguish overloaded methods.
- It improves readability, since one logical operation (such as
add) has one name for different inputs.
Program
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) { // different number of parameters
return a + b + c;
}
double add(double a, double b) { // different parameter types
return a + b;
}
}
public class OverloadDemo {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(10, 20)); // 30
System.out.println(c.add(10, 20, 30)); // 60
System.out.println(c.add(2.5, 3.5)); // 6.0
}
}
The call c.add(10, 20) matches add(int, int), c.add(10, 20, 30) matches the three-parameter version and c.add(2.5, 3.5) matches the double version, all resolved at compile time.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 AD · 10 marks
Write a program that takes two words as input from user and displays longest word.
Answer
import java.util.Scanner;
public class LongestWord {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first word: ");
String w1 = sc.next();
System.out.print("Enter second word: ");
String w2 = sc.next();
if (w1.length() > w2.length()) {
System.out.println("Longest word: " + w1);
} else if (w2.length() > w1.length()) {
System.out.println("Longest word: " + w2);
} else {
System.out.println("Both words have the same length (" + w1.length() + ").");
}
sc.close();
}
}
Sample run
Enter first word: Nepal
Enter second word: Kathmandu
Longest word: Kathmandu
The program compares the length() of the two strings and prints the longer one; if they are equal it says so.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from TU BIM Third Semester Model Questions 2023 (IT 237, ACC 201, IT 236, STT 201, IT 238) (Faculty of Management model question set 2023, BIM third semester (new course)), TU BIM Third Semester Model Question 2023 ACC 201 Financial Accounting (Faculty of Management model question 2023), TU BIM Third Semester Model Question 2023 IT 236 Microprocessor and Computer Architecture (Faculty of Management model question 2023), TU BIM Third Semester Model Question 2023 STT 201 Business Statistics (Faculty of Management model question 2023), TU BIM Third Semester Model Question 2023 IT 238 Data Structure and Algorithms (Faculty of Management model question 2023), TU BIM Third Semester Model Question 2023 STT 201 Business Statistics (Lab) (Faculty of Management model question 2023, MS-Excel practical), TU BIM 2014 Third Semester IT 215 Web Programming I (model question) (Faculty of Management model question 2014 (old course), via EducateNepal), TU BIM 2014 Third Semester IT 216 Java Programming I (model question) (Faculty of Management model question 2014 (old course), via EducateNepal), TU BIM 2014 Third Semester IT 217 Computer Organization (model question) (Faculty of Management model question 2014 (old course), via EducateNepal), TU BBA/BIM/BBM 2015 Third Semester STT 201 Business Statistics (model question) (Faculty of Management model question 2015 (old course), via EducateNepal), TU BBA/BIM/BBM 2015 Third Semester STT 201 Business Statistics Lab (model question) (Faculty of Management model question 2015, lab work using MS-Excel), TU BIM Computer Organization (IT 217) 2012 AD (Board exam paper, 2012 AD), TU BIM Computer Organization (IT 217) 2014 AD (Board exam paper, 2014 AD), TU BIM Computer Organization (IT 217) 2015 AD (Board exam paper, 2015 AD), TU BIM Computer Organization (IT 217) 2016 AD (Board exam paper, 2016 AD), TU BIM Computer Organization (IT 217) 2017 AD (Board exam paper, 2017 AD), TU BIM Computer Organization (IT 217) 2018 AD (Board exam paper, 2018 AD), TU BIM Computer Organization (IT 217) 2019 AD (Board exam paper, 2019 AD), TU BIM Computer Organization (IT 217) 2021 AD (Board exam paper, 2021 AD), TU BIM Web Programming I (IT 215) 2014 AD (Board exam paper, 2014 AD), TU BIM Web Programming I (IT 215) 2015 AD (Board exam paper, 2015 AD), TU BIM Web Programming I (IT 215) 2016 AD (Board exam paper, 2016 AD), TU BIM Web Programming I (IT 215) 2017 AD (Board exam paper, 2017 AD), TU BIM Web Programming I (IT 215) 2018 AD (Board exam paper, 2018 AD), TU BIM Web Programming I (IT 215) 2019 AD (Board exam paper, 2019 AD), TU BIM Web Programming I (IT 215) 2021 AD (Board exam paper, 2021 AD), TU BIM Java Programming I (IT 216) 2015 AD (Board exam paper, 2015 AD), TU BIM Java Programming I (IT 216) 2017 AD (Board exam paper, 2017 AD), TU BIM Java Programming I (IT 216) 2018 AD (Board exam paper, 2018 AD), TU BIM Java Programming I (IT 216) 2019 AD (Board exam paper, 2019 AD), TU BIM Java Programming I (IT 216) 2021 AD (Board exam paper, 2021 AD), TU BIM Business Statistics (STT 201) 2009 AD (Board exam paper, 2009 AD), TU BIM Business Statistics (STT 201) 2010 AD (Board exam paper, 2010 AD), TU BIM Business Statistics (STT 201) 2021 AD (Board exam paper, January 2021 (Full Marks 36, answer any six)), TU BIM Business Statistics (STT 201) 2013 AD (Board exam paper, 2013 (Full Marks 36)), TU BIM Business Statistics (STT 201) 2014 AD (Board exam paper, 2014 AD), TU BIM Business Statistics (STT 201) 2015 AD (Board exam paper, 2015 AD), TU BIM Business Statistics (STT 201) 2016 AD (Board exam paper, 2016 AD), TU BIM Business Statistics (STT 201) 2018 AD (Board exam paper, 2018 AD), TU BIM Business Statistics (STT 201) 2019 AD (Board exam paper, 2019 AD), TU BIM Financial Accounting (ACC 201) 2015 AD (Board exam paper, 2015 AD), TU BIM Financial Accounting (ACC 201) 2016 AD (Board exam paper, 2016 AD), TU BIM Financial Accounting (ACC 201) 2017 AD (Board exam paper, 2017 AD), TU BIM Financial Accounting (ACC 201) 2018 AD (Board exam paper, 2018 AD), TU BIM Financial Accounting (ACC 201) 2019 AD (Board exam paper, 2019 AD), TU BIM Financial Accounting (ACC 201) 2021 AD (Board exam paper, 2021 AD), TU BIM Financial Accounting (ACC 201) 2014 AD (Board exam paper, 2014 AD), TU BIM Financial Accounting (ACC 201) 2013 AD (Board exam paper, 2013 AD), TU BIM Financial Accounting (ACC 201) 2012 AD (Board exam paper, 2012 AD), TU BIM Financial Accounting (ACC 201) 2010 AD (Board exam paper, 2010 AD) and TU BIM Financial Accounting (ACC 201) 2009 AD (Board exam paper, 2009 AD). Answers are written for this site; check them against your class notes.