Board paper

Object Oriented Programming in Java 2023 Board Question Paper

ITM 152 · Object Oriented Programming in Java

examination paper loaded.
Programme
BIM
Academic year
Semester 2
Exam year
2023 AD
Sitting
regular
Full marks
60
Duration
180 minutes

Tribhuvan University

Faculty of Management

Office of the Dean

2023 AD / Regular Examination

Course: ITM 152 · Object Oriented Programming in Java

Level: Bachelor of Information Management (BIM) · Semester 2

Full Marks: 60

Time: 3 hrs.

Time: 3 Hrs. | Full Marks: 60 | Pass Marks: 30

Subjective Questions

  1. What is the significance of bytecode?

    [2]
    View model solution

    Significance of Bytecode in Java

    Java Bytecode is the highly optimized, intermediate machine-independent instruction set produced by the Java compiler (javac) from source code (.java files), stored in .class binary files.

    Key Significance:

    1. Platform Independence (“Write Once, Run Anywhere - WORA”): Bytecode is not targeted to any specific CPU architecture. Any operating system (Windows, Linux, macOS) equipped with a Java Virtual Machine (JVM) can execute the exact same bytecode.
    2. Security Sandbox: Bytecode is verified by the JVM Bytecode Verifier before execution, ensuring it does not perform illegal memory operations or violate access controls.
    3. Execution Efficiency: Bytecode can be quickly interpreted or compiled into native machine code at runtime by the Just-In-Time (JIT) compiler.
  2. Why main() is declared as static?

    [2]
    View model solution

    Why main() is Declared as static in Java

    In Java, the entry-point method is declared as:

    public static void main(String[] args)
    

    Reason:

    1. Execution Without Object Instantiation: The static keyword indicates that the method belongs to the class itself rather than to an instance of the class.
    2. When the JVM starts up, no objects of the class containing main() exist in heap memory.
    3. If main() were non-static, the JVM would have to create an object of the class first. However, the class constructor might require complex parameters, creating an ambiguous initialization problem.
    4. By making it static, the JVM can directly call ClassName.main() immediately after class loading.
  3. What is the task of scanner class?

    [2]
    View model solution

    Task of the Scanner Class in Java

    The Scanner class, located in the java.util package, is a text scanner used to parse and read primitive data types and strings from various input streams (such as standard console input System.in, strings, or disk files) using regular expressions.

    Common Tasks:

    1. Console Input: Reads formatted user input easily using methods like nextInt(), nextDouble(), next(), and nextLine().
    2. Tokenization: Breaks the input stream into tokens based on whitespace delimiters by default.
    3. Validation: Checks if the next token matches expected types using hasNextInt(), hasNextDouble(), etc.
  4. Define encapsulation.

    [2]
    View model solution

    Definition of Encapsulation

    Encapsulation is one of the four foundational Object-Oriented Programming (OOP) principles. It is the technique of binding data fields (variables) and the methods that operate on them together into a single cohesive unit (a class) while restricting direct unauthorized access to internal components from outside the class.

    How It is Implemented in Java:

    1. Declare the instance variables of a class as private (Data Hiding).
    2. Provide public getter and setter methods to inspect and modify variable values with validation logic.
    public class Student {
        private int roll; // Hidden field
        public int getRoll() { return roll; }
        public void setRoll(int r) { if (r > 0) this.roll = r; }
    }
    
  5. Write syntax for defining a package in Java.

    [2]
    View model solution

    Syntax for Defining a Package in Java

    A package in Java is defined using the package keyword. It must be the first non-comment statement at the very top of the Java source file.

    General Syntax:

    package package_name;
    

    Hierarchical/Subpackage Syntax:

    package com.university.fom.bitm;
    
    public class Course {
        // Class body
    }
    

    Note: The package name directly corresponds to the directory structure on disk (e.g., com/university/fom/bitm/Course.java).

  6. Define method overloading.

    [2]
    View model solution

    Definition of Method Overloading

    Method Overloading (also known as Compile-time or Static Polymorphism) is a feature in Java that allows a single class to have two or more methods with the exact same name, provided they have different parameter lists (signatures).

    Variations in Signature Allowed:

    1. Different number of arguments (e.g., add(int, int) vs add(int, int, int)).
    2. Different data types of arguments (e.g., add(int, int) vs add(double, double)).
    3. Different sequence of parameter data types (e.g., print(int, String) vs print(String, int)).

    Note: Changing only the return type does not constitute method overloading and results in a compile-time error.

  7. What is the role of this keyword?

    [2]
    View model solution

    Role of the this Keyword in Java

    In Java, this is a reference variable that refers to the current object instance whose method or constructor is currently executing.

    Primary Roles:

    1. Differentiate Instance Variables from Shadowing Parameters: Resolves naming ambiguity when constructor or method parameter names match instance field names (e.g., this.roll = roll;).
    2. Explicit Constructor Invocation (Constructor Chaining): Calls another overloaded constructor within the same class using this(arg1, arg2); (must be the first line in constructor).
    3. Pass Current Object: Can be passed as an argument in method calls or returned from a method (return this;).
  8. Differentiate between Checked and Unchecked exception.

    [2]
    View model solution

    Differences Between Checked and Unchecked Exceptions

    Parameter Checked Exception Unchecked Exception
    Detection Time Checked at compile time. Occurs at runtime.
    Compiler Enforcement Compiler strictly enforces handling via try-catch or declaring with throws. Compiler does not force handling; usually preventable by defensive coding.
    Inheritance Directly extends java.lang.Exception (except RuntimeException). Extends java.lang.RuntimeException or java.lang.Error.
    Typical Causes External environmental failures outside program control (missing file, bad network). Programming logic bugs and invalid usage (bad index, null pointer).
    Examples IOException, SQLException, ClassNotFoundException. NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException.
  9. Differentiate between super class and sub class.

    [2]
    View model solution

    Differences Between Super Class and Sub Class in Java

    Basis of Comparison Super Class (Parent / Base Class) Sub Class (Child / Derived Class)
    Definition The class whose members (fields/methods) are inherited by another class. The class that inherits existing members from another class using the extends keyword.
    Scope & Generality Contains general, high-level features shared by all subtypes. Contains specialized, concrete attributes and customized behaviors.
    Code Reuse Provides reusable code template. Reuses code from superclass and extends it with new methods or overrides existing ones.
    Access to Members Cannot access specific new members added in the subclass. Can access all public and protected members of the superclass.
  10. Write an importance of generic class.

    [2]
    View model solution

    Importance of Generic Classes in Java

    Generics, introduced in Java 5, enable classes, interfaces, and methods to operate on parameterized types (<T>).

    Key Importance:

    1. Strong Compile-Time Type Safety: Detects incompatible type assignments at compile-time rather than producing a runtime ClassCastException.
    2. Elimination of Explicit Type Casting: Values retrieved from generic data structures do not require manual casting (e.g., list.get(0) returns type T directly instead of Object).
    3. Algorithm Reusability: Allows developers to write a single generalized collection, queue, or sorting algorithm that works seamlessly across all object types (e.g., ArrayList<String>, ArrayList<Integer>).
  11. Write a program to find the second largest integer from an array.

    [5]
    View model solution

    Java Program: Find Second Largest Integer in an Array

    import java.util.Scanner;
    
    public class SecondLargestFinder {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    
            System.out.println("=== Second Largest Integer in Array ===");
            System.out.print("Enter number of elements (>= 2): ");
            int n = sc.nextInt();
    
            if (n < 2) {
                System.out.println("Error: Array must contain at least two elements.");
                return;
            }
    
            int[] arr = new int[n];
            System.out.println("Enter " + n + " integers:");
            for (int i = 0; i < n; i++) {
                arr[i] = sc.nextInt();
            }
    
            // Single-pass algorithm O(n)
            int largest = Integer.MIN_VALUE;
            int secondLargest = Integer.MIN_VALUE;
    
            for (int num : arr) {
                if (num > largest) {
                    secondLargest = largest;
                    largest = num;
                } else if (num > secondLargest && num != largest) {
                    secondLargest = num;
                }
            }
    
            if (secondLargest == Integer.MIN_VALUE) {
                System.out.println("All elements in the array are equal; no distinct second largest element exists.");
            } else {
                System.out.println("Largest Element        : " + largest);
                System.out.println("Second Largest Element : " + secondLargest);
            }
        }
    }
    
  12. Define and mention the use of final data member, final method and final class.

    [5]
    View model solution

    Definition and Use of final Data Member, Method, and Class

    In Java, the final non-access modifier is used to apply immutability, prevent inheritance, or prohibit overriding:

    1. final Data Member (Variable):

    • Definition: A variable whose value, once initialized, cannot be reassigned. It behaves as a constant.
    • Usage: Used to declare constants (e.g., public static final double PI = 3.14159;).

    2. final Method:

    • Definition: A method that cannot be overridden by any subclass.
    • Usage: Preserves critical core algorithm logic or security routines from being altered in subclasses (e.g., public final void validateAccountCredentials()).

    3. final Class:

    • Definition: A class that cannot be inherited or subclassed (prevents extension).
    • Usage: Used to create completely immutable classes or secure utility classes (e.g., java.lang.String, java.lang.Math, and all wrapper classes are final).
  13. Why do we need wrapper classes? Explain.

    [5]
    View model solution

    Why We Need Wrapper Classes in Java

    A Wrapper Class in Java is a class whose object wraps or encapsulates a primitive data type (e.g., Integer for int, Double for double, Boolean for boolean).

    Primary Reasons We Need Wrapper Classes:

    1. Java Collection Framework Compatibility: Java collections (such as ArrayList, HashMap, HashSet) can only store Objects, not raw primitive values. Thus, ArrayList<int> is illegal, requiring ArrayList<Integer>.
    2. Null Value Representation: Primitives always hold default values (e.g., 0 or false) and cannot represent null. In database operations, missing or SQL NULL fields must be mapped to objects.
    3. Data Type Conversion Utility Methods: Provide essential parsing methods (e.g., Integer.parseInt("123"), Double.parseDouble("3.14"), Integer.toHexString(255)).
    4. Multithreading & Synchronization: Objects are needed to provide synchronization locks in concurrent programming.
  14. Write a Java program to display whether a character is an alphabet or not.

    [5]
    View model solution

    Java Program: Check Whether a Character is an Alphabet

    import java.util.Scanner;
    
    public class AlphabetChecker {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    
            System.out.println("=== Alphabet Character Checker ===");
            System.out.print("Enter a single character: ");
            char ch = sc.next().charAt(0);
    
            // Check using character range comparison
            if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
                System.out.println("'" + ch + "' is an ALPHABET.");
            } else {
                System.out.println("'" + ch + "' is NOT an alphabet (Digit / Special Symbol).");
            }
    
            // Alternative using Character wrapper class:
            // boolean isAlpha = Character.isLetter(ch);
        }
    }
    
  15. Write an example program of inner class.

    [5]
    View model solution

    Java Program: Example of Inner Class

    An inner class is a non-static class defined inside another enclosing class. It has direct access to all members (including private fields) of the outer class.

    class OuterUniversity {
        private String universityName = "Tribhuvan University";
    
        // Member Inner Class
        class Department {
            private String deptName;
    
            Department(String deptName) {
                this.deptName = deptName;
            }
    
            void displayInfo() {
                // Accessing private field of outer class directly
                System.out.println("Institution : " + universityName);
                System.out.println("Department  : " + deptName);
            }
        }
    
        void showDepartment() {
            Department d = new Department("Faculty of Management (BITM)");
            d.displayInfo();
        }
    }
    
    public class InnerClassDemo {
        public static void main(String[] args) {
            System.out.println("=== Inner Class Demonstration ===");
            OuterUniversity outer = new OuterUniversity();
            outer.showDepartment();
        }
    }
    
  16. Write an example program that contains a generic class.

    [5]
    View model solution

    Java Program: Example of Generic Class

    // Generic class with type parameter <T>
    class StorageBox<T> {
        private T item;
    
        public void setItem(T item) {
            this.item = item;
        }
    
        public T getItem() {
            return this.item;
        }
    
        public void printDetails() {
            System.out.println("Stored Item Type : " + item.getClass().getName());
            System.out.println("Stored Value     : " + item);
        }
    }
    
    public class GenericClassDemo {
        public static void main(String[] args) {
            System.out.println("=== Generic Class Demonstration ===\n");
    
            // 1. Generic instance holding Integer
            StorageBox<Integer> intBox = new StorageBox<>();
            intBox.setItem(2082);
            intBox.printDetails();
    
            System.out.println();
    
            // 2. Generic instance holding String
            StorageBox<String> strBox = new StorageBox<>();
            strBox.setItem("Paper Khoj BITM Archive");
            strBox.printDetails();
        }
    }
    
  17. Create an interface Exam with methods setExam(String division, int mark) and showExam(). Create a class named test that implements the interface Exam and then display the records.

    [5]
    View model solution

    Java Program: Interface Exam and Class Test

    // Interface definition
    interface Exam {
        void setExam(String division, int mark);
        void showExam();
    }
    
    // Class test implementing the interface Exam
    class Test implements Exam {
        private String division;
        private int mark;
    
        @Override
        public void setExam(String division, int mark) {
            this.division = division;
            this.mark = mark;
        }
    
        @Override
        public void showExam() {
            System.out.println("=== Exam Record ===");
            System.out.println("Marks Obtained : " + this.mark);
            System.out.println("Division       : " + this.division);
        }
    }
    
    public class InterfaceExamDemo {
        public static void main(String[] args) {
            // Create an instance of Test
            Test studentTest = new Test();
    
            // Set records
            studentTest.setExam("First Division with Distinction", 88);
    
            // Display records
            studentTest.showExam();
        }
    }
    
  18. Create a class named Book with instance variables title and price. Add a method named setVar to pass parameters for title and price. Add another method named showVar to display values of these variables. Now in main (), declare 4 objects of book and display the records of book that starts with “Java”.

    [5]
    View model solution

    Java Program: Class Book and Filtering by “Java” Prefix

    class Book {
        private String title;
        private double price;
    
        public void setVar(String title, double price) {
            this.title = title;
            this.price = price;
        }
    
        public void showVar() {
            System.out.printf("Title: %-30s | Price: Rs. %.2f%n", this.title, this.price);
        }
    
        public String getTitle() {
            return this.title;
        }
    }
    
    public class BookSearchDemo {
        public static void main(String[] args) {
            // Declare array of 4 Book objects
            Book[] books = new Book[4];
            for (int i = 0; i < 4; i++) {
                books[i] = new Book();
            }
    
            // Initialize records
            books[0].setVar("Java: The Complete Reference", 1250.0);
            books[1].setVar("Database System Concepts", 890.0);
            books[2].setVar("Java Programming for Beginners", 750.0);
            books[3].setVar("Structured Programming in C", 600.0);
    
            System.out.println("=== Books Starting with 'Java' ===");
            for (Book b : books) {
                if (b.getTitle().startsWith("Java")) {
                    b.showVar();
                }
            }
        }
    }
    
  19. Create a class name Movie (id, genre). Write the object of Movie class into file named “Comedy.dat” having comedy as genre.

    [5]
    View model solution

    Java Program: Serialize Movie Object with Genre “Comedy” to File

    import java.io.*;
    
    // Class Movie implementing Serializable interface
    class Movie implements Serializable {
        private static final long serialVersionUID = 1L;
        private int id;
        private String genre;
    
        public Movie(int id, String genre) {
            this.id = id;
            this.genre = genre;
        }
    
        public String getGenre() {
            return this.genre;
        }
    
        @Override
        public String toString() {
            return "Movie [ID=" + id + ", Genre=" + genre + "]";
        }
    }
    
    public class MovieSerializationDemo {
        public static void main(String[] args) {
            Movie m1 = new Movie(101, "Comedy");
            Movie m2 = new Movie(102, "Thriller");
            Movie m3 = new Movie(103, "comedy");
    
            Movie[] playlist = {m1, m2, m3};
    
            // Write only comedy movies into "Comedy.dat"
            try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Comedy.dat"))) {
                for (Movie m : playlist) {
                    if (m.getGenre().equalsIgnoreCase("comedy")) {
                        oos.writeObject(m);
                        System.out.println("Written to Comedy.dat: " + m);
                    }
                }
                System.out.println("Serialization completed successfully.");
            } catch (IOException e) {
                System.err.println("File I/O Error: " + e.getMessage());
            }
        }
    }
    
  20. Write a program to create a class student with data member roll and name. Sort the 10 objects of this class on the basis of name.

    [5]
    View model solution

    Java Program: Sort 10 Student Objects by Name

    class Student {
        int roll;
        String name;
    
        Student(int roll, String name) {
            this.roll = roll;
            this.name = name;
        }
    
        void display() {
            System.out.printf("Roll: %-4d | Name: %s%n", roll, name);
        }
    }
    
    public class StudentSortDemo {
        public static void main(String[] args) {
            Student[] students = {
                new Student(1, "Suresh"),
                new Student(2, "Aayush"),
                new Student(3, "Binod"),
                new Student(4, "Pooja"),
                new Student(5, "Deepak"),
                new Student(6, "Kiran"),
                new Student(7, "Anil"),
                new Student(8, "Ramesh"),
                new Student(9, "Gita"),
                new Student(10, "Manish")
            };
    
            // Bubble Sort based on Student Name (Alphabetical)
            for (int i = 0; i < students.length - 1; i++) {
                for (int j = 0; j < students.length - i - 1; j++) {
                    if (students[j].name.compareToIgnoreCase(students[j + 1].name) > 0) {
                        Student temp = students[j];
                        students[j] = students[j + 1];
                        students[j + 1] = temp;
                    }
                }
            }
    
            System.out.println("=== 10 Students Sorted Alphabetically by Name ===");
            for (Student s : students) {
                s.display();
            }
        }
    }
    
  21. Define Exception. Why should we handled an Exception? Write a Java program to create a class Mobile (type, Phone_no). Customize the exception such that if the user give phone_no having less than or greater than 10 digit, then the program has to throw an exception with the message “Invalid Phone number”.

    [10]
    View model solution

    Exception Concept & Custom Exception for Mobile Phone Number

    1. Concept of Exception & Why We Handle It:

    An exception is an abnormal condition or event that arises during program execution, disrupting the normal flow of instructions.

    • Why Handle Exceptions?
      • Prevents catastrophic abrupt program termination.
      • Preserves user data and gracefully closes open system resources (database connections, file streams).
      • Distinguishes error-handling code from normal operational business logic.

    2. Java Program with Custom Exception:

    // Custom Checked Exception
    class InvalidPhoneNumberException extends Exception {
        public InvalidPhoneNumberException(String message) {
            super(message);
        }
    }
    
    class Mobile {
        private String type;
        private String phone_no;
    
        public Mobile(String type, String phone_no) throws InvalidPhoneNumberException {
            this.type = type;
            setPhoneNo(phone_no);
        }
    
        public void setPhoneNo(String phone_no) throws InvalidPhoneNumberException {
            // Validate if phone_no consists strictly of exactly 10 digits
            if (phone_no == null || phone_no.length() != 10 || !phone_no.matches("\\d{10}")) {
                throw new InvalidPhoneNumberException("Invalid Phone number: Must be exactly 10 digits!");
            }
            this.phone_no = phone_no;
        }
    
        public void display() {
            System.out.println("Mobile Type     : " + type);
            System.out.println("Phone Number    : " + phone_no);
        }
    }
    
    public class CustomExceptionDemo {
        public static void main(String[] args) {
            System.out.println("=== Custom Phone Number Exception Validation ===\n");
    
            // Valid Mobile
            try {
                Mobile m1 = new Mobile("Smartphone", "9841234567");
                m1.display();
            } catch (InvalidPhoneNumberException e) {
                System.err.println("Exception Caught: " + e.getMessage());
            }
    
            System.out.println();
    
            // Invalid Mobile (less than 10 digits)
            try {
                Mobile m2 = new Mobile("Feature Phone", "984123");
                m2.display();
            } catch (InvalidPhoneNumberException e) {
                System.err.println("Exception Caught: " + e.getMessage());
            }
        }
    }
    
  22. Define Inheritance. List different types of inheritance. Explain the chain of constructor and destructor between sub class and super class.

    [10]
    View model solution

    Inheritance, Inheritance Types, and Constructor Chaining in Java

    1. Definition of Inheritance:

    Inheritance is the OOP mechanism through which a new class (subclass) acquires the fields and methods of an existing class (superclass), enabling code reuse and establishing an is-a relationship.

    2. Types of Inheritance:

    1. Single Inheritance: A single subclass extends a single superclass (class B extends A).
    2. Multilevel Inheritance: A class extends another subclass forming an inheritance chain (class C extends B extends A).
    3. Hierarchical Inheritance: Multiple subclasses inherit from a single superclass (class B extends A and class C extends A).
    4. Multiple Inheritance (via Interfaces): A class implements multiple interfaces (class D implements I1, I2). (Java does not support multiple class inheritance to avoid the Diamond Problem).

    3. Chain of Constructor and Destructor Mechanism:

    • Constructor Chaining (Top-Down Execution): When a subclass object is instantiated, the superclass constructor executes first, followed by the subclass constructor. Java automatically inserts super() as the first line of every subclass constructor if not explicitly written.

    • Destructor Handling in Java: Unlike C++, Java has no explicit destructors because memory is managed automatically by the Garbage Collector (GC). Cleanups are handled via try-with-resources (AutoCloseable) or java.lang.ref.Cleaner.

    class SuperClass {
        SuperClass() {
            System.out.println("1. SuperClass Constructor Executed.");
        }
    }
    
    class SubClass extends SuperClass {
        SubClass() {
            super(); // Invokes superclass constructor first
            System.out.println("2. SubClass Constructor Executed.");
        }
    }
    
    public class ConstructorChainDemo {
        public static void main(String[] args) {
            SubClass obj = new SubClass();
        }
    }