1 Programming In Java

Advanced Java Programming · Unit 1 · 8 hrs

Programming in Java

Exam-focused notes for Programming in Java (Advanced Java Programming, CSC419): what the TU syllabus asks and how it has actually been tested, with 25 solved past questions from this unit.

Programming in Java in short

This unit lays the groundwork for advanced Java by covering how the JVM compiles and runs a program, the language features that define Java, its core object oriented building blocks, exception handling, concurrency, and file handling, all of which the rest of the course builds on.

Programming in Java: notes

Java Architecture

A Java program begins life as source code in a .java file. The Java compiler (javac) translates this source code into bytecode, a platform-neutral instruction set stored in a .class file. Bytecode is not native machine code; it is object code meant for the Java Virtual Machine (JVM), not for any particular processor.

When the program runs, the class loader locates and loads the .class files the program needs, whether they come from the local file system or over a network. Before execution, the bytecode verifier checks that the code obeys the JVM specification: that it does not access memory without authorization, cannot overflow the stack, and performs no illegal type conversions (such as treating a float as an object reference). Once verified, the JVM's just in time (JIT) compiler translates the bytecode into native machine code for the host processor, caching the translated code so it can be reused without recompiling on every call. The Java Runtime Environment (JRE), which bundles the JVM with the core class libraries, then hands this native code to the operating system for execution. This compile-once, verify-and-translate-at-runtime pipeline is what lets the same .class file run unmodified on any platform that has a JVM.

Java Buzzwords

Sun Microsystems described Java using a set of buzzwords that summarize its design goals.

  • Simple: Java's syntax is close to C and C++, but confusing, rarely used features such as explicit pointers and operator overloading were left out.
  • Object oriented: a Java program is organized as a collection of objects, each bundling data (attributes) and behaviour (methods); almost everything in Java is an object.
  • Distributed: features such as Remote Method Invocation (RMI) and Enterprise JavaBeans (EJB) let a Java program cooperate with code running on other machines.
  • Robust: automatic memory management (garbage collection), the absence of raw pointers, and mandatory exception handling and type checking reduce whole classes of runtime failures.
  • Secure: programs run inside the JVM sandbox, which keeps them from touching memory outside their authorized area, and the absence of pointers rules out a common route to memory corruption.
  • Portable: the phrase "write once, run anywhere" captures the idea that the same bytecode runs on any operating system that has a compatible JVM.
  • High performance: performance approaches native code because the JIT compiler translates and caches hot bytecode rather than reinterpreting it every time.
  • Multithreaded: a Java program can run several threads at once, and those threads share the same process memory, which makes multithreading efficient.

Path and ClassPath Variables

PATH is an operating system environment variable that tells the shell where to find executables such as java and javac; it points at the bin directory of the installed JDK. CLASSPATH is a separate variable that tells the compiler and the JVM where to find the compiled .class files and library .jar files a program depends on. In short, PATH locates the JDK's own tools, while CLASSPATH locates the classes a program uses. An IDE such as Eclipse or IntelliJ sets both automatically; PATH and CLASSPATH only need to be configured by hand when compiling and running from the command line.

Sample Java Program

Every standalone Java program needs a class containing a main method, which is where the JVM begins execution:

class Sample {
    public static void main(String[] args) {
        System.out.println("Hello Java");
    }
}

The file must be saved as Sample.java, matching the public class name. To read input from the console, Java provides the Scanner class in the java.util package:

import java.util.Scanner;

class UserInputDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string: ");
        String str = sc.nextLine();
        System.out.println("You have entered: " + str);
    }
}

Compiling and Running Java Programs

Compilation and execution are two separate steps. javac Sample.java invokes the compiler, which checks the source for syntax errors and, if it compiles cleanly, produces Sample.class containing bytecode. java Sample then starts the JVM, which loads Sample.class, verifies it, and calls its main method. The class name passed to java must match the name of the class that declares main, not the file name, though for a single public class the two are the same.

Arrays

An array is a collection of elements of the same type stored under one variable name, in contiguous memory. Java arrays are objects, so their length is fixed once created and is available through the length field.

A single dimensional array is declared and used as follows:

class TestArray {
    public static void main(String[] args) {
        int[] arr = new int[5];   // declaration
        arr[0] = 10;              // initialization
        arr[1] = 20;
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

A multidimensional array, such as int[][] arr = new int[3][3];, models a grid: here, 3 rows by 3 columns, accessed as arr[row][col].

For Each Loop

The for-each loop is an alternative way to traverse an array or any Iterable collection without managing an index:

int[] a = {10, 11, 12, 13};
for (int i : a) {
    System.out.println(i);
}

Its advantage is readability and the elimination of off-by-one indexing bugs; its limitation is that it always moves forward through every element and cannot skip elements or run in reverse, because it is not index based.

What this unit covers

  • Java Architecture
  • Java Buzzwords
  • Path and ClassPath variables
  • Sample Java Program
  • Compiling and Running Java Programs
  • Arrays
  • for each loop
  • Class and Object
  • Overloading
  • Access Privileges
  • Interface
  • Inner Class
  • Final and Static Modifiers
  • Packages
  • Inheritance
  • Overriding
  • Handling Exceptions: Try, Catch, Finally, Throws, and Throw keywords
  • Creating Exception Class
  • Concurrency: Introduction, Thread States, Writing Multithreaded Programs, Thread Properties, Thread Synchronization, Thread Priorities
  • Working with Files: Byte Stream Classes, Character Stream Classes, Random Access File, Reading and Writing Objects

Path and ClassPath variables

2081 · 10 marks

Differentiate between path and class path in Java. When do you prefer anonymous inner class? Consider the following program and answer the given questions. 1) Name the list of class file created after compiling above program 2) Rewrite the above program using for loop[10]

--- Feature PATH CLASSPATH --------- Definition A mediator between the developer and the operating system to inform the binary/executable file location A mediator between the developer and the compiler to inform the library file path used in source code Points to Location of JRE (Java Runtime Env...

Open this answer on its own page →

Working with Files

2081 · 5 marks

Assume that a text file named 'ONE.TXT' contains a paragraph of text. Write a program to copy the word that starts with vowel from 'ONE.TXT' to another file 'TWO.TXT'. [5]

Show solved answer

Copying Words Starting with Vowels from ONE.TXT to TWO.TXT

Approach

  • Read the content of ONE.TXT word by word
  • Check if each word starts with a vowel (a, e, i, o, u -- both uppercase and lowercase)
  • If yes, write that word to TWO.TXT

Java Program

import java.io.*;

public class CopyVowelWords {

    public static void main(String[] args) {

        // Declare file reader and writer references
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            // Open ONE.TXT for reading
            br = new BufferedReader(new FileReader("ONE.TXT"));

            // Open TWO.TXT for writing
            bw = new BufferedWriter(new FileWriter("TWO.TXT"));

            String line;

            // Read file line by line
            while ((line = br.readLine()) != null) {

                // Split each line into words by spaces/punctuation
                String[] words = line.split("[\\s.,;:!?]+");

                for (String word : words) {

                    // Check if word is non-empty
                    if (word.length() > 0) {

                        // Get the first character of the word
                        char firstChar = word.charAt(0);

                        // Check if first character is a vowel
                        if (firstChar == 'a' || firstChar == 'e' ||
                            firstChar == 'i' || firstChar == 'o' ||
                            firstChar == 'u' || firstChar == 'A' ||
                            firstChar == 'E' || firstChar == 'I' ||
                            firstChar == 'O' || firstChar == 'U') {

                            // Write the vowel-starting word to TWO.TXT
                            bw.write(word);
                            bw.newLine();
                        }
                    }
                }
            }

            System.out.println("Words starting with vowels copied to TWO.TXT successfully.");

        } catch (FileNotFoundException e) {
            System.out.println("File ONE.TXT not found: " + e.getMessage());

        } catch (IOException e) {
            System.out.println("IO Error occurred: " + e.getMessage());

        } finally {
            // Close streams in finally block to ensure they always close
            try {
                if (br != null) br.close();
                if (bw != null) bw.close();
            } catch (IOException e) {
                System.out.println("Error closing files: " + e.getMessage());
            }
        }
    }
}

Sample Input (ONE.TXT)

An apple is a fruit. Orange and mango are tasty.
Every student enjoys learning.

Sample Output (TWO.TXT)

An
apple
is
a
Orange
and
are
Every
enjoys

Key Points

ConceptDetail
FileReaderReads characters from ONE.TXT
BufferedReaderReads line by line efficiently
FileWriterWrites characters to TWO.TXT
BufferedWriterWrites output efficiently
split("[\\s.,;:!?]+")Splits line into individual words
charAt(0)Gets the first character of each word
finally blockEnsures streams are always closed
Open this answer on its own page →

2080 · 5 marks

Suppose that 9 integers are written in a file named 'magic.txt' in the arrangement of 3 x 3 separated by space. Write a program to check whether the integers in all rows, all columns, and both diagonals sum to the same constant or not. [5]

Show solved answer

Given

  • Input file: magic.txt
  • Contains 9 integers arranged as a $3 \times 3$ grid, separated by spaces.
  • Task: Verify whether all 3 rows, all 3 columns, and both diagonals sum to the same constant (magic square check).

No specific numeric values are given for the integers in the question; the file contents are supplied at runtime. This is a programming problem, so no numeric computation is required unless sample data is chosen for demonstration.


STEP 2 - SOLVE: Model Answer

Approach

  1. Read the 9 integers from magic.txt into a $3 \times 3$ array.
  2. Compute the target constant using the sum of the first row.
  3. Compare every row sum, every column sum, and both diagonal sums against this constant.
  4. Report whether it is a magic square.

Java Program

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class MagicSquareChecker {
    public static void main(String[] args) {
        int[][] m = new int[3][3];

        // Step 1: Read 9 integers from magic.txt
        try (Scanner sc = new Scanner(new File("magic.txt"))) {
            for (int i = 0; i < 3; i++)
                for (int j = 0; j < 3; j++)
                    if (sc.hasNextInt())
                        m[i][j] = sc.nextInt();
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
            return;
        }

        // Display the matrix
        System.out.println("Matrix read from magic.txt:");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++)
                System.out.print(m[i][j] + "\t");
            System.out.println();
        }

        // Step 2: Target constant = sum of first row
        int constant = m[0][0] + m[0][1] + m[0][2];
        boolean isMagic = true;

        // Step 3: Check all rows
        for (int i = 0; i < 3; i++) {
            int rowSum = m[i][0] + m[i][1] + m[i][2];
            if (rowSum != constant) isMagic = false;
        }

        // Check all columns
        for (int j = 0; j < 3; j++) {
            int colSum = m[0][j] + m[1][j] + m[2][j];
            if (colSum != constant) isMagic = false;
        }

        // Check main diagonal
        int diag1 = m[0][0] + m[1][1] + m[2][2];
        if (diag1 != constant) isMagic = false;

        // Check anti-diagonal
        int diag2 = m[0][2] + m[1][1] + m[2][0];
        if (diag2 != constant) isMagic = false;

        // Step 4: Final result
        if (isMagic)
            System.out.println("All rows, columns and diagonals sum to "
                               + constant + ". It IS a Magic Square.");
        else
            System.out.println("The sums are NOT all equal. It is NOT a Magic Square.");
    }
}

Sample magic.txt

2 7 6
9 5 1
4 3 8

Verification of Sums (for the sample)

Rows:

  • $2+7+6 = 15$
  • $9+5+1 = 15$
  • $4+3+8 = 15$

Columns:

  • $2+9+4 = 15$
  • $7+5+3 = 15$
  • $6+1+8 = 15$

Diagonals:

  • Main: $2+5+8 = 15$
  • Anti: $6+5+4 = 15$

All eight sums equal $15$, the magic constant.

Sample Output

Matrix read from magic.txt:
2    7    6
9    5    1
4    3    8
All rows, columns and diagonals sum to 15. It IS a Magic Square.

Key Points

CheckFormula
Row $i$$m[i][0]+m[i][1]+m[i][2]$
Column $j$$m[0][j]+m[1][j]+m[2][j]$
Main diagonal$m[0][0]+m[1][1]+m[2][2]$
Anti-diagonal$m[0][2]+m[1][1]+m[2][0]$

The program is logically correct: it reads from the file, catches FileNotFoundException, and compares all eight sums to the first-row constant. The sample result gives a magic constant of $15$.

Open this answer on its own page →

2077 · 10 marks

Describe the responsibility of Serializable interface. Write a program to read an input string from the user and write the vowels of that string in VOWEL.TXT and consonants in CONSONANT.TXT.[10]

The Serializable interface in Java is found in the java.io package. It is a marker interface, meaning it has no methods or fields. Its sole purpose is to mark a class so that the Java runtime knows the objects of that class can be serialized and deserialized. Responsibility Description ------ Mar...

Open this answer on its own page →

2076 · 5 marks

Write a simple Java program that reads a file named 'Test.txt' and displays its contents. [5]

Java provides the java.io package for file handling. To read a file, we use FileReader wrapped with BufferedReader for efficient line-by-line reading. If the file is not found or cannot be read, an exception is thrown, which must be handled properly. --- --- Step Code Purpose --------------------...

Open this answer on its own page →

Concurrency

2080 · 10 marks

Why do we need to synchronize the thread? Justify with an example. An array with an odd number of elements is said to be centered if all elements (except the middle one) are strictly greater than the value of the middle element. Note that only arrays with an odd number of elements have a middle element. Write a function that accepts an integer array and returns 1 if it is a centered array, otherwise it returns 0.[10]

Show solved answer

Thread Synchronization and Centered Array


Part 1: Why Do We Need to Synchronize Threads? (with Example)

What is Thread Synchronization?

Thread synchronization is the mechanism that ensures that two or more concurrent threads do not simultaneously execute a critical section (a segment of code that accesses shared resources). Without synchronization, multiple threads accessing and modifying shared data can produce inconsistent or incorrect results, a situation known as a race condition.


Why Do We Need Synchronization?

When multiple threads share a common resource (such as a variable, file, or object), the following problems can occur without synchronization:

ProblemDescription
Race ConditionTwo threads read/write shared data simultaneously, causing unpredictable results
Data InconsistencyShared data gets corrupted because updates from one thread overwrite another
Thread InterferenceOperations of one thread interfere with operations of another thread

Synchronization solves these problems by allowing only one thread at a time to access the critical section using the synchronized keyword in Java.


Example: Without Synchronization (Problem)

class Counter {
    int count = 0;

    // No synchronization - PROBLEM
    public void increment() {
        count++;
    }
}

class MyThread extends Thread {
    Counter c;

    MyThread(Counter c) {
        this.c = c;
    }

    public void run() {
        for (int i = 0; i < 1000; i++) {
            c.increment();
        }
    }
}

public class WithoutSync {
    public static void main(String[] args) throws InterruptedException {
        Counter c = new Counter();

        MyThread t1 = new MyThread(c);
        MyThread t2 = new MyThread(c);

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

        t1.join();
        t2.join();

        // Expected: 2000, but actual result is unpredictable (e.g., 1768, 1854...)
        System.out.println("Count: " + c.count);
    }
}

Problem: Both t1 and t2 access count++ simultaneously. The operation count++ is not atomic - it involves three steps:

  1. Read the value of count
  2. Increment it
  3. Write it back

Two threads can read the same value before either writes back, causing lost updates.


Example: With Synchronization (Solution)

class Counter {
    int count = 0;

    // Synchronized method - only one thread can execute at a time
    public synchronized void increment() {
        count++;
    }
}

class MyThread extends Thread {
    Counter c;

    MyThread(Counter c) {
        this.c = c;
    }

    public void run() {
        for (int i = 0; i < 1000; i++) {
            c.increment();
        }
    }
}

public class WithSync {
    public static void main(String[] args) throws InterruptedException {
        Counter c = new Counter();

        MyThread t1 = new MyThread(c);
        MyThread t2 = new MyThread(c);

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

        t1.join();
        t2.join();

        // Always prints: Count: 2000 (correct and consistent)
        System.out.println("Count: " + c.count);
    }
}

How it works:

  • The synchronized keyword places a lock (monitor) on the object.
  • When t1 enters increment(), it acquires the lock.
  • t2 must wait until t1 releases the lock before it can enter.
  • This guarantees mutual exclusion and data consistency.

Summary of Synchronization Benefits

  • Prevents race conditions
  • Ensures data consistency across threads
  • Provides mutual exclusion for critical sections
  • Enables safe communication between threads

Part 2: Centered Array Function

Problem Definition

An array with an odd number of elements is centered if:

  • All elements except the middle one are strictly greater than the middle element.

Return: 1 if centered, 0 otherwise.


Logic / Algorithm

Step 1: Check if the array length is odd.
        If even, return 0 (no middle element exists).

Step 2: Find the middle index = length / 2

Step 3: Get the middle element = array[middleIndex]

Step 4: Loop through all elements except the middle one.
        If any element is <= middle element, return 0.

Step 5: If all elements pass the check, return 1.

Java Implementation

public class CenteredArray {

    // Function to check if array is centered
    public static int isCentered(int[] arr) {

        int n = arr.length;

        // Step 1: Check if number of elements is odd
        if (n % 2 == 0) {
            return 0; // Even number of elements, no middle element
        }

        // Step 2: Find the middle index and middle element
        int midIndex = n / 2;
        int midValue = arr[midIndex];

        // Step 3: Check all elements except the middle one
        for (int i = 0; i < n; i++) {
            if (i != midIndex) {
                // Every other element must be STRICTLY GREATER than middle
                if (arr[i] <= midValue) {
                    return 0; // Not centered
                }
            }
        }

        // Step 4: All conditions satisfied
        return 1;
    }

    // Main method to test
    public static void main(String[] args) {

        int[] arr1 = {3, 5, 1, 4, 2}; // middle = arr[2] = 1, all others > 1
        int[] arr2 = {5, 3, 4, 2, 6}; // middle = arr[2] = 4, but 3 <= 4, not strictly greater, so not centered

        System.out.println("Array 1 result: " + isCentered(arr1)); // Expected: 1 (centered)
        System.out.println("Array 2 result: " + isCentered(arr2)); // Expected: 0 (not centered)
    }
}

Dry Run

Array 1 = {3, 5, 1, 4, 2}: length = 5 (odd), midIndex = 2, midValue = 1. Checking the remaining elements: 3 > 1, 5 > 1, 4 > 1, 2 > 1, all strictly greater, so the function returns 1.

Array 2 = {5, 3, 4, 2, 6}: length = 5 (odd), midIndex = 2, midValue = 4. Checking the remaining elements in order: 5 > 4 passes, but 3 > 4 fails (3 <= 4), so the function immediately returns 0.


Conclusion

Thread synchronization is needed whenever multiple threads share mutable state, because without it, interleaved reads and writes to the same variable produce race conditions and lost updates, as shown by the count++ example above. The isCentered function above solves the array problem in a single pass: it rejects even-length arrays immediately, then checks every non-middle element against the middle value, returning 0 the moment any element fails the strictly-greater-than condition, and 1 only if every element passes.

Open this answer on its own page →

2079 · 5 marks

What is multithreading? How can you create multithreaded program in Java? Explain. [5]

Show solved answer

Multithreading in Java

What is Multithreading?

Multithreading is a feature of Java that allows concurrent execution of two or more parts (threads) of a program to maximize CPU utilization. A thread is a lightweight process that has its own files and stacks but can access shared data from other threads within the same process.

The main advantages of multithreading are:

  • Provides simultaneous execution of two or more parts of a program
  • Shares the same memory, making it more efficient than separate processes
  • Maximizes CPU time utilization

Creating a Multithreaded Program in Java

There are two ways to create a thread in Java:


Method 1: Extending the Thread Class

A class extends the built-in Thread class and overrides its run() method.

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

public class MultiThreadDemo {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();  // Create thread object
        MyThread t2 = new MyThread();  // Create another thread object
        t1.start();  // Start thread 1 (calls run() internally)
        t2.start();  // Start thread 2
    }
}

Key Points:

  • start() method is called to begin execution; it internally calls run()
  • Do not call run() directly, as it will not create a new thread

Method 2: Implementing the Runnable Interface

A class implements the Runnable interface and provides the body of the run() method. This is preferred when the class already extends another class (since Java does not support multiple inheritance).

class MyRunnable implements Runnable {
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Runnable Thread: " + i);
        }
    }
}

public class MultiThreadDemo2 {
    public static void main(String[] args) {
        MyRunnable obj = new MyRunnable();
        Thread t1 = new Thread(obj);  // Pass Runnable object to Thread
        Thread t2 = new Thread(obj);
        t1.start();
        t2.start();
    }
}

Comparison of Both Methods

FeatureExtending ThreadImplementing Runnable
InheritanceCannot extend other classCan extend another class
FlexibilityLess flexibleMore flexible
PreferredSimple programsReal-world programs

Thread Life Cycle

A thread passes through the following states:

  1. New - Thread object is created
  2. Runnable - start() is called
  3. Running - Thread is executing
  4. Blocked/Waiting - Thread is waiting for a resource
  5. Terminated - Thread finishes execution

Summary

Multithreading in Java enables multiple tasks to run simultaneously, improving performance and CPU utilization. It can be implemented either by extending the Thread class or implementing the Runnable interface, with Runnable being the more flexible and commonly preferred approach.

Open this answer on its own page →

2077 · 5 marks

Why synchronization is essential in multithreading? Describe. [5]

In a multithreaded environment, multiple threads share the same process resources (memory, data, objects). When two or more threads try to access and modify a shared object or variable simultaneously, it leads to data inconsistency and race conditions. Synchronization is the mechanism that preven...

Open this answer on its own page →

2075 · 5 marks

Write down the life cycle of thread. Write a program to execute multiple threads in priority base. [5]

State Description -------------------- New Thread object is created but start() is not yet called Runnable Thread is ready to run; waiting for CPU scheduling Running Thread is currently executing its run() method Blocked/Waiting Thread is waiting due to sleep(), wait(), or I/O operation Dead/Term...

Open this answer on its own page →

Class and Object

2079 · 10 marks

Explain feature of object-oriented programming. Create a class Distance with private variables feet of type integer and inches of type floating point. Use suitable constructor, and methods for adding and comparing two distance objects. [Hint: 1 feet = 12 inches][10]

--- OOP is a programming paradigm that organizes software as a collection of objects combining data and behaviour. The key features are: - A class is a blueprint or template that defines attributes (data) and methods (behaviour). - An object is a real-world instance of a class. - Example: Distanc...

Open this answer on its own page →

2076 · 5 marks

Define class. How do you create a class in Java? Differentiate class with interface. [5]

Show solved answer

Class in Java: Definition, Creation, and Difference with Interface


Definition of Class

A class in Java is a blueprint or template from which objects are created. It defines the properties (fields/attributes) and behaviors (methods) that the objects of that class will have. A class encapsulates data and the methods that operate on that data into a single unit.

Syntax:

class ClassName {
    // fields (attributes)
    // methods (behaviors)
}

Creating a Class in Java

A class is created using the class keyword followed by the class name. It can contain:

  • Fields (variables to store data)
  • Methods (functions to define behavior)
  • Constructors (to initialize objects)

Example:

class Student {
    // Fields
    int rollNo;
    String name;

    // Constructor
    Student(int r, String n) {
        rollNo = r;
        name = n;
    }

    // Method
    void display() {
        System.out.println("Roll No: " + rollNo + ", Name: " + name);
    }
}

// Using the class
public class Main {
    public static void main(String[] args) {
        Student s = new Student(1, "Ram");  // object creation
        s.display();
    }
}

Difference Between Class and Interface

BasisClassInterface
KeywordDeclared using class keywordDeclared using interface keyword
MethodsCan have both abstract and concrete (implemented) methodsAll methods are abstract by default (empty body)
FieldsCan have instance variables of any typeAll fields are public, static, and final by default
InstantiationObjects can be created directly from a classCannot be instantiated directly
InheritanceSupports single inheritance (extends)Supports multiple inheritance (a class can implement multiple interfaces)
Access ModifiersMethods can have any access modifierMethods are public and abstract by default
ConstructorCan have constructorsCannot have constructors
PurposeUsed to define object structure and behaviorUsed to achieve abstraction and loose coupling
ImplementationA class uses extends to inherit another classA class uses implements to use an interface

Key Note

An interface is a blueprint of a class used to achieve:

  • Abstraction
  • Multiple inheritance (not supported directly with classes in Java)
  • Loose coupling

A class that implements an interface must implement all the methods declared in that interface.

Open this answer on its own page →

2075 · 5 marks

Define the chain of constructor. What is the purpose of private constructor? [5]

--- Constructor chaining is the process of calling one constructor from another constructor within the same class or from a parent class. This creates a "chain" of constructor calls that executes in sequence. Constructor chaining is achieved using: - this() keyword -- to call another constructor ...

Open this answer on its own page →

Sample Java Program

2079 · 5 marks

Write Java program that send messages with each other using TCP socket. [5]

TCP (Transmission Control Protocol) socket programming in Java uses the java.net package. Communication requires two programs: a Server and a Client. --- 1. Create object of ServerSocket class 2. Accept connection from client 3. Get input and output streams 4. Read/Write data to socket 5. Close s...

Open this answer on its own page →

Final and Static Modifiers

2079 · 5 marks

Write short notes on: a. Final class b. Result set [2.5+2.5]

--- The final modifier in Java is used for finalizing the implementations of classes, methods, and variables. A final class is a class that is declared using the final keyword. Once a class is declared as final, it cannot be subclassed (inherited). This means no other class can extend a final cla...

Open this answer on its own page →

2075 · 5 marks

When do we use final method and final class? Differentiate between function overloading and function overriding. [5]

--- A final method is a method declared with the final keyword. It cannot be overridden by any subclass. When to use: - When you want to prevent a subclass from changing the implementation of a method. - When the method contains critical logic that must remain unchanged throughout inheritance. --...

Open this answer on its own page →

Java Architecture

2078 · 10 marks

Explain RMI architecture layers in detail. Write a Java programs using RMI to find product of two numbers.[10]

Remote Method Invocation (RMI) is a Java API that allows an object running in one Java Virtual Machine (JVM) to invoke methods on an object running in another JVM. It is the mechanism that makes Java truly distributed (as mentioned in Java's distributed feature using RMI and EJB). --- --- This is...

Open this answer on its own page →

Packages

2078 · 5 marks

What is package? How can you create your own package in Java? Explain with example. [5]

A package in Java is a namespace that organizes a set of related classes and interfaces together. It is essentially a folder/directory that groups related Java classes, interfaces, and sub-packages. Packages help in: - Avoiding name conflicts between classes - Controlling access (access protectio...

Open this answer on its own page →

2077 · 5 marks

What is the task of manifest file? Write the procedure to create it. [5]

A manifest file is a special metadata file included inside a JAR (Java Archive) file. It is named MANIFEST.MF and is located in the META-INF/ directory within the JAR. The main tasks of the manifest file are: - Specifies the Main Class: It tells the JVM which class contains the main() method to e...

Open this answer on its own page →

Arrays

2077 · 5 marks

A non-empty array A of length n is called an array of all possibilities if it contains all numbers between 0 and A.length-1 inclusive. Write a method named isAllPossibilities that accepts an integer array and returns 1 if the array is an array of all possibilities, otherwise it returns 0. [5]

Show solved answer

isAllPossibilities Method

Given data

  • Input: a non-empty integer array A of length n.
  • Condition: A must contain all integers from 0 to n-1 inclusive.
  • Output: return 1 if the condition holds, otherwise 0.

(No specific test arrays are mandated by the question; behaviour must be general.)

Concept

An array of length n qualifies if and only if it is a permutation of ${0, 1, 2, \dots, n-1}$. Since the array has exactly n slots and must hold n distinct values all in range $[0, n-1]$, it suffices to check:

  1. every element lies in $[0, n-1]$, and
  2. no value repeats.

If both hold across n elements, each of the n distinct values must appear exactly once (pigeonhole principle).

Java Code

public static int isAllPossibilities(int[] A) {
    int n = A.length;

    boolean[] visited = new boolean[n];   // track which numbers seen

    for (int i = 0; i < n; i++) {
        // out of range check
        if (A[i] < 0 || A[i] >= n) {
            return 0;
        }
        // duplicate check
        if (visited[A[i]]) {
            return 0;
        }
        visited[A[i]] = true;
    }

    return 1;   // all values 0..n-1 present exactly once
}

Dry Run

ArraynResultReason
{0,1,2,3}41Permutation of 0..3
{3,0,2,1}41Same set, reordered
{1,2,3,4}404 >= n out of range
{0,0,1,2}40Duplicate 0 detected
{-1,0,1,2}40-1 < 0 out of range

Complexity

  • Time: $O(n)$ - single pass.
  • Space: $O(n)$ - visited array.
Open this answer on its own page →

2075 · 5 marks

An array is called balanced if it's even numbered elements (a[0], a[2], etc) are even and its odd numbered elements (a[1], a[3], etc) are Odd. Write a function named isBalanced that accepts an array of integers and returns 1 if the array is balanced otherwise it returns 0. [5]

This is a programming problem, not a numerical one. The requirements are: - Even-indexed elements (a[0], a[2], a[4], ...) must be even. - Odd-indexed elements (a[1], a[3], a[5], ...) must be odd. - Function name: isBalanced - Input: an array of integers (size must also be passed in C). - Output: ...

Open this answer on its own page →

Handling Exceptions

2077 · 5 marks

When does the finally block is mandatory in while handling exception? Describe with a suitable scenario. [5]

The finally block in Java is a block that always executes regardless of whether an exception occurs or not. It is used to place important cleanup code such as closing connections, releasing resources, or closing files. --- The finally block becomes mandatory (strongly required / best practice) in...

Open this answer on its own page →

2076 · 10 marks

What is exception handling? Discuss the use of each keyword (try, catch, throw, throws and finally) with suitable Java program.[10]

Exception handling is a mechanism in Java that allows a program to handle runtime errors (exceptional conditions) in a controlled manner, so that the normal flow of the program can be maintained and the program does not crash abruptly. When an exception occurs, an object representing that error i...

Open this answer on its own page →

Inheritance

2077 · 5 marks

Why multiple inheritance is not allowed in Java using classes? Give an example. [5]

Java does not support multiple inheritance with classes primarily to avoid the Diamond Problem (also called the "Deadly Diamond of Death"). This is an ambiguity problem that arises when a class inherits from two or more classes that have a method with the same name. Consider the following scenari...

Open this answer on its own page →

Compiling and Running Java Programs

2076 · 5 marks

Define Java Bean. How is it different from other Java programs? What is design pattern? [5]

A Java Bean is a reusable software component written in Java that follows a specific set of conventions (rules). It is essentially a Java class that encapsulates multiple objects into a single object (the bean). - The class must be public. - It must have a public no-argument constructor (default ...

Open this answer on its own page →

Creating Exception Class

2075 · 10 marks

Why do we need to handle the exception? Distinguish error and exception. Write a program to demonstrate your own exception class.[10]

Exception handling is needed for the following reasons: 1. To maintain normal program flow: Without handling, an exception causes the program to terminate abruptly. Handling allows the rest of the code to continue executing. 2. To avoid program crash: Unhandled exceptions crash the application. H...

Open this answer on its own page →