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.
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]
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 answerHide answer
Copying Words Starting with Vowels from ONE.TXT to TWO.TXT
Approach
- Read the content of
ONE.TXTword 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
| Concept | Detail |
|---|---|
FileReader | Reads characters from ONE.TXT |
BufferedReader | Reads line by line efficiently |
FileWriter | Writes characters to TWO.TXT |
BufferedWriter | Writes output efficiently |
split("[\\s.,;:!?]+") | Splits line into individual words |
charAt(0) | Gets the first character of each word |
finally block | Ensures streams are always closed |
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 answerHide 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
- Read the 9 integers from
magic.txtinto a $3 \times 3$ array. - Compute the target constant using the sum of the first row.
- Compare every row sum, every column sum, and both diagonal sums against this constant.
- 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
| Check | Formula |
|---|---|
| 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$.
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]
2076 · 5 marks
Write a simple Java program that reads a file named 'Test.txt' and displays its contents. [5]
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 answerHide 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:
| Problem | Description |
|---|---|
| Race Condition | Two threads read/write shared data simultaneously, causing unpredictable results |
| Data Inconsistency | Shared data gets corrupted because updates from one thread overwrite another |
| Thread Interference | Operations 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:
- Read the value of
count - Increment it
- 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
synchronizedkeyword places a lock (monitor) on the object. - When
t1entersincrement(), it acquires the lock. t2must wait untilt1releases 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.
2079 · 5 marks
What is multithreading? How can you create multithreaded program in Java? Explain. [5]
Show solved answerHide 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 callsrun()- 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
| Feature | Extending Thread | Implementing Runnable |
|---|---|---|
| Inheritance | Cannot extend other class | Can extend another class |
| Flexibility | Less flexible | More flexible |
| Preferred | Simple programs | Real-world programs |
Thread Life Cycle
A thread passes through the following states:
- New - Thread object is created
- Runnable -
start()is called - Running - Thread is executing
- Blocked/Waiting - Thread is waiting for a resource
- 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.
2077 · 5 marks
Why synchronization is essential in multithreading? Describe. [5]
2075 · 5 marks
Write down the life cycle of thread. Write a program to execute multiple threads in priority base. [5]
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]
2076 · 5 marks
Define class. How do you create a class in Java? Differentiate class with interface. [5]
Show solved answerHide 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
| Basis | Class | Interface |
|---|---|---|
| Keyword | Declared using class keyword | Declared using interface keyword |
| Methods | Can have both abstract and concrete (implemented) methods | All methods are abstract by default (empty body) |
| Fields | Can have instance variables of any type | All fields are public, static, and final by default |
| Instantiation | Objects can be created directly from a class | Cannot be instantiated directly |
| Inheritance | Supports single inheritance (extends) | Supports multiple inheritance (a class can implement multiple interfaces) |
| Access Modifiers | Methods can have any access modifier | Methods are public and abstract by default |
| Constructor | Can have constructors | Cannot have constructors |
| Purpose | Used to define object structure and behavior | Used to achieve abstraction and loose coupling |
| Implementation | A class uses extends to inherit another class | A 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.
2075 · 5 marks
Define the chain of constructor. What is the purpose of private constructor? [5]
Sample Java Program
2079 · 5 marks
Write Java program that send messages with each other using TCP socket. [5]
Final and Static Modifiers
2079 · 5 marks
Write short notes on: a. Final class b. Result set [2.5+2.5]
2075 · 5 marks
When do we use final method and final class? Differentiate between function overloading and function overriding. [5]
Java Architecture
2078 · 10 marks
Explain RMI architecture layers in detail. Write a Java programs using RMI to find product of two numbers.[10]
Packages
2078 · 5 marks
What is package? How can you create your own package in Java? Explain with example. [5]
2077 · 5 marks
What is the task of manifest file? Write the procedure to create it. [5]
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 answerHide answer
isAllPossibilities Method
Given data
- Input: a non-empty integer array
Aof lengthn. - Condition:
Amust contain all integers from0ton-1inclusive. - Output: return
1if the condition holds, otherwise0.
(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:
- every element lies in $[0, n-1]$, and
- 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
| Array | n | Result | Reason |
|---|---|---|---|
{0,1,2,3} | 4 | 1 | Permutation of 0..3 |
{3,0,2,1} | 4 | 1 | Same set, reordered |
{1,2,3,4} | 4 | 0 | 4 >= n out of range |
{0,0,1,2} | 4 | 0 | Duplicate 0 detected |
{-1,0,1,2} | 4 | 0 | -1 < 0 out of range |
Complexity
- Time: $O(n)$ - single pass.
- Space: $O(n)$ - visited array.
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]
Handling Exceptions
2077 · 5 marks
When does the finally block is mandatory in while handling exception? Describe with a suitable scenario. [5]
2076 · 10 marks
What is exception handling? Discuss the use of each keyword (try, catch, throw, throws and finally) with suitable Java program.[10]
Inheritance
2077 · 5 marks
Why multiple inheritance is not allowed in Java using classes? Give an example. [5]
Compiling and Running Java Programs
2076 · 5 marks
Define Java Bean. How is it different from other Java programs? What is design pattern? [5]
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]
Make Unit 1 stick
Practice CSC419 with flashcards & quizzes