Java Exam Notes 2
Java Exam Notes 2
Packages, Exceptions, Methods, File Handling, Basic Java, Control Statements & Extra Notes |
Total: 183 marks
package bank;
↓ creates
package packagename;
Step 2: Define the class to be put in the package, and declare it public.
package myapp;
Step 3: Create a subdirectory under the directory where the main source file is stored. The
subdirectory name must match the package name.
Step 4: Store the listing as the [Link] file inside the subdirectory created.
myapp/
[Link]
Step 5: Compile the file — this creates the corresponding .class file inside the subdirectory.
javac -d . [Link]
myapp/
[Link]
[Link]
Step 6: Create a main class, import the package, and use it.
Write a separate program (outside the package folder) that imports the package and uses its class.
import [Link];
class Main {
public static void main(String args[]) {
Student s = new Student();
[Link]();
}
}
javac [Link]
java Main
Output:
Real-life example: It is like a company creating an HR department (package) with its records (class),
and a manager (main class) importing / accessing that department's records to actually use them — the
final result (output) is the work getting done using those records.
package shapes;
Compile with:
javac -d . [Link]
package shapes;
Compile with:
javac -d . [Link]
Both .class files now sit inside the same shapes/ folder:
shapes/
[Link]
[Link]
import [Link];
import [Link];
class Main {
public static void main(String args[]) {
Drawable d = new Circle();
[Link]();
}
}
javac [Link]
java Main
Output:
Drawing a Circle
Important rule: The class or interface must be declared public if it needs to be accessed from outside
its package (using import). Without public, it stays accessible only within the same package.
Real-life example: Adding a new employee's file to the "HR" folder — you label the file as belonging to
HR and place it there; it instantly becomes part of HR's records. But if that record needs to be visible to
other departments too, it has to be officially marked "shared" (public) — otherwise it stays private to HR.
Example:
package [Link];
Exception Handling
Q7a. What is an Exception? (4 marks)
An exception is an unwanted or unexpected event that disrupts the normal flow of a program's
execution during runtime. In Java, an exception is an object that represents an error condition, created
by the JVM (or the programmer) when something goes wrong. Java provides a robust mechanism —
try, catch, finally, throw, throws — to detect and handle such situations without crashing the whole
program.
Real-life example: A sudden power cut while a washing machine is running a wash cycle. It is an
unexpected event, but a well-designed machine does not just break down — it pauses safely and can
resume. Similarly, a well-written Java program "catches" the problem and handles it gracefully instead
of terminating abnormally.
Without handling, this program terminates abruptly — exception handling prevents that.
2. NullPointerException — the program tries to use an object reference that has the value null.
String s = null;
[Link]([Link]()); // throws NullPointerException
[Link]("[Link]");
// throws ClassNotFoundException if class is missing
6. FileNotFoundException — an attempt to open a file at a specified path fails because the file
does not exist.
Compiler output:
Run-time error:
An error that occurs while the program is executing, after it has compiled successfully — usually due to
an illegal operation or unexpected condition. These are also called exceptions, and unlike compile-time
errors, they can be handled using try-catch.
int a = 10, b = 0;
int c = a / b; // compiles fine, fails only when run
Output:
Key differences:
A compile-time error is detected by the compiler A run-time error is detected by the JVM while the
before the program is executed, during the program is actually being executed, after
compilation phase itself. compilation is already complete.
It is identified by the Java compiler (javac) when it It is identified by the Java Virtual Machine (JVM)
checks the source code for correct syntax and when an illegal operation is attempted during
structure. program execution.
It is mainly caused by syntax mistakes such as It is mainly caused by logical issues that appear
missing semicolons, undeclared variables, or type only while running, such as division by zero or
mismatches in the code. accessing an invalid array index.
Since the error is found during compilation, the Since the program compiles successfully, the
.class (bytecode) file is not generated at all until .class file is generated, and the error appears only
the mistake is corrected. when that file is actually run.
This type of error cannot be handled using This type of error (exception) can be handled
try-catch blocks, because the program never even gracefully using try-catch-finally blocks, allowing
reaches the execution stage. the program to continue running.
It is also known as a syntax error, and it must be It is also known as a runtime exception, and Java's
fixed manually in the source code before the exception-handling mechanism is specifically
program can run at all. designed to manage it.
Syntax:
try {
// risky code
} catch (ExceptionType1 e1) {
// handler for first exception type
} catch (ExceptionType2 e2) {
// handler for second exception type
} finally {
// cleanup code - always executes
}
Output:
Explanation:
• The try block attempts 10/0, which throws an ArithmeticException.
• The catch block catches it and prints a message instead of letting the program crash.
• The finally block executes regardless — printing its message.
• The program then continues normally to the next line, instead of terminating abruptly.
Real-life example: It is like trying to unlock a door (try). If the key does not work (exception), you have a
backup plan — call a locksmith (catch). Either way, once you are done, you always lock up your toolbox
before leaving (finally) — whether the key worked or not.
Method Constructor
A method can have any valid identifier as its name, A constructor must always have the exact same
chosen freely by the programmer to describe what name as the class it belongs to, with no
it does. exceptions.
A method must always be declared with a return A constructor never has a return type at all, not
type, which can be void if it does not return any even void, since its only purpose is to initialize the
value. object.
Methods are inherited by subclasses and can be Constructors are not inherited by subclasses,
overridden to change their behaviour in the child although a child class constructor can invoke the
class. parent's constructor using super().
class Student {
String name;
// Constructor
Student(String n) {
name = n;
[Link]("Constructor called - object created");
}
// Method
void display() {
[Link]("Student name: " + name);
}
}
class Student {
Student() {
[Link]("Default constructor invoked");
}
Student(String name) {
[Link]("Parameterized constructor invoked for " + name);
}
}
Output:
A constructor can also be invoked from another constructor of the same class using this(), or from
the parent class constructor using super() — but it can never be called directly by an object using dot
notation like a method.
Output:
Explanation:
• All four methods share the same name, area() — that is what makes this overloading.
• Java tells them apart by their signature (number and type of parameters): area(int side) for Square,
area(double radius) for Circle, area(double, double) for Rectangle, and area(int, int) for Triangle.
• When [Link](5) is called, the compiler matches it to area(int side) because 5 is an int. Similarly,
[Link](3.5) matches area(double radius) because 3.5 is a double.
• This is resolved entirely at compile time — hence the name static polymorphism.
Real-life example: It is like a single word "cut" meaning different things depending on context — "cut
the cake," "cut the grass," "cut the cloth." The action name stays the same, but what actually happens
depends on what you give it to act on — just like area() behaves differently depending on the
type/number of arguments passed.
File Handling
Q10. What is File Handling in Java?
File handling in Java refers to the set of operations — creating, reading, writing, appending, renaming,
and deleting files — that a program performs on files stored on disk, using classes from the [Link]
package such as FileInputStream, FileOutputStream, File, and RandomAccessFile. Unlike variables,
which exist only in memory while the program runs, files let data persist permanently on disk even after
the program ends.
Real-life example: It is the difference between writing something on a notepad (a file — permanent)
and saying it out loud (a variable — temporary, gone the moment the conversation ends). File handling
lets a Java program "write things down" so the data survives after the program finishes.
OutputStream:
An abstract class in [Link] representing a stream of bytes being written out of a program to a
destination such as a file, console, or network connection. All byte-output classes (like
FileOutputStream) extend it, and the basic method used to write data is write().
Key differences:
InputStream OutputStream
An InputStream is used to read data into a An OutputStream is used to write data out of a
program from a source such as a file, keyboard, or program to a destination such as a file, console, or
network. network.
The direction of data flow for an InputStream is The direction of data flow for an OutputStream is
from the external source towards the program. from the program towards the external destination.
The basic method used by InputStream classes to The basic method used by OutputStream classes
fetch data, one byte at a time, is the read() to send data, one byte at a time, is the write()
method. method.
An InputStream's read() method returns -1 once An OutputStream has no concept of EOF, since
the end of the stream (EOF) has been reached. the program itself decides how much data to write.
Q12b. How does append mode differ from write mode? (2 marks)
Write mode — new FileOutputStream("[Link]") — opens the file and, if it already has content, erases
it completely before writing new data. If the file does not exist, it is created fresh.
Append mode — new FileOutputStream("[Link]", true) — opens the file and adds new data after the
existing content, without erasing anything. The second true argument is what switches it into append
mode.
Q14. WAP to accept two files via command-line arguments and compare
their content
import [Link];
import [Link];
try {
fis1 = new FileInputStream(args[0]);
fis2 = new FileInputStream(args[1]);
do {
ch1 = [Link]();
ch2 = [Link]();
if (ch1 != ch2) {
same = false;
break;
}
} while (ch1 != -1 && ch2 != -1);
if (same)
[Link]("Files are the same");
else
[Link]("Files are different");
} catch (IOException e) {
[Link]("Error: " + [Link]());
} finally {
try {
if (fis1 != null) [Link]();
if (fis2 != null) [Link]();
} catch (IOException e) {
[Link]("Error closing files");
}
}
}
}
Output:
javac [Link]
java CompareFiles [Link] [Link]
Files are the same
Q15. WAP to accept a file name via command-line argument and delete the
file, showing "File not found" if it does not exist
import [Link];
if ([Link]()) {
if ([Link]())
[Link]("File deleted: " + [Link]());
else
[Link]("File could not be deleted");
} else {
[Link]("File not found");
}
}
}
Output:
javac [Link]
java DeleteFileProgram [Link]
File deleted: [Link]
Q16. WAP to read a text file and count the total number of vowels (14
marks)
import [Link];
import [Link];
import [Link];
int vowelCount = 0;
try {
fis = new FileInputStream(fileName);
int ch;
} catch (IOException e) {
[Link]("File not found: " + [Link]());
} finally {
try {
if (fis != null) [Link]();
} catch (IOException e) {
[Link]("Error closing file");
}
}
[Link]();
}
}
Output:
Q17. WAP to read a text file and count the total number of consonants (14
marks)
import [Link];
import [Link];
import [Link];
int consonantCount = 0;
try {
fis = new FileInputStream(fileName);
int ch;
} catch (IOException e) {
[Link]("File not found: " + [Link]());
} finally {
try {
if (fis != null) [Link]();
} catch (IOException e) {
[Link]("Error closing file");
}
}
[Link]();
}
}
Output:
Q18. WAP to read a text file and count the total number of words (14
marks)
(Logic: number of words = number of spaces + 1)
import [Link];
import [Link];
import [Link];
int spaceCount = 0;
try {
fis = new FileInputStream(fileName);
int ch;
} catch (IOException e) {
[Link]("File not found: " + [Link]());
} finally {
try {
if (fis != null) [Link]();
} catch (IOException e) {
[Link]("Error closing file");
}
}
[Link]();
}
}
Output:
Q19. WAP to read a text file and count the total number of sentences (14
marks)
(Logic: a sentence ends at a full stop . or a semicolon ;)
import [Link];
import [Link];
import [Link];
int sentenceCount = 0;
try {
fis = new FileInputStream(fileName);
int ch;
} catch (IOException e) {
[Link]("File not found: " + [Link]());
} finally {
try {
if (fis != null) [Link]();
} catch (IOException e) {
[Link]("Error closing file");
}
}
[Link]();
}
}
Output:
try {
fis = new FileInputStream("[Link]");
fileString = [Link]();
if ([Link](userInput)) {
[Link]("Password match");
} else {
[Link]("Password mismatch");
}
} catch (IOException e) {
[Link]("Error: " + [Link]());
} finally {
try {
if (fis != null) [Link]();
} catch (IOException e) {
[Link]("Error closing file");
}
}
[Link]();
}
}
Output:
Q20b. WAP in Java to copy the content of one file into another, using
FileInputStream, FileOutputStream, and Scanner
import [Link];
import [Link];
import [Link];
import [Link];
try {
fis = new FileInputStream(sourceFile);
fos = new FileOutputStream(destFile);
int ch;
while ((ch = [Link]()) != -1) {
[Link](ch);
}
} catch (IOException e) {
[Link]("File not found: " + [Link]());
} finally {
try {
if (fis != null) [Link]();
if (fos != null) [Link]();
} catch (IOException e) {
[Link]("Error closing files");
}
}
[Link]();
}
}
Output:
Basic Java
Q21. Why is Java so popular? (5 marks)
1 Java is platform-independent, meaning a program written and compiled once can run on any device or
operating system that has a Java Virtual Machine installed, without needing to be rewritten.
2 Java has built-in support for object-oriented programming, which makes large software systems easier
to design, organise, and maintain through concepts like classes, objects, inheritance, and
polymorphism.
3 Java provides automatic memory management through garbage collection, which frees the
programmer from manually allocating and deallocating memory and reduces the risk of memory leaks.
4 Java has a vast collection of built-in libraries and a strong open-source ecosystem, which allows
developers to build applications quickly without writing every feature from scratch.
5 Java has robust security features, such as the absence of explicit pointers and a security manager that
restricts what untrusted code can do, making it a trusted choice for enterprise and web applications.
Real-life example: It is like a universal power adapter that works in any country's socket without
needing a different charger for each place — Java's "write once, run anywhere" nature lets the same
program work unchanged across Windows, Linux, and Mac.
Real-life example: It is like a book translated once into a universal intermediate language, where each
country's reader (JVM) then interprets it into their own native tongue — the same original book
(program) can be understood everywhere without ever being rewritten.
Control Statements
Q24. Difference between while loop and do-while loop (7 marks)
for loop:
An entry-controlled loop that combines initialization, condition-checking, and increment/decrement into a
single line, making it ideal when the number of iterations is known in advance.
while loop:
An entry-controlled loop that checks the test condition first, before executing the loop body; if the
condition is false at the very first check, the body executes zero times.
int i = 1;
while (i <= 5) {
[Link](i);
i++;
}
do-while loop:
An exit-controlled loop that executes the loop body first, and checks the test condition only afterward;
this guarantees the body executes at least once, even if the condition is false from the start.
int i = 1;
do {
[Link](i);
i++;
} while (i <= 5);
Key differences:
In a while loop, the condition is checked first; if it is In a do-while loop, the body executes first, and the
false, the loop body is skipped completely. condition is checked only afterward.
A while loop may execute the loop body zero times A do-while loop always executes the loop body at
if the condition is false from the start. least once, no matter what the condition is.
The syntax of a while loop is while(condition) { ... }, The syntax of a do-while loop is do { ... }
with no semicolon needed at the end. while(condition);, ending with a semicolon.
A while loop is generally used when the number of A do-while loop is generally used when the loop
iterations depends entirely on a condition that may body must run at least once, such as showing a
never be true. menu before asking the user whether to continue.
int day = 3;
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Invalid day");
}
if-else-if:
A control statement that evaluates a series of boolean conditions one after another, executing the block
belonging to the first condition that evaluates to true.
int day = 3;
if (day == 1) {
[Link]("Monday");
} else if (day == 2) {
[Link]("Tuesday");
} else if (day == 3) {
[Link]("Wednesday");
} else {
[Link]("Invalid day");
}
Key differences:
A switch statement tests one variable or An if-else-if ladder can test several different
expression against several fixed values. conditions, even on different variables.
A switch statement works only with int, char, An if-else-if ladder works with any data type that
String, and enum types. can form a boolean expression.
A switch statement uses an optional default block An if-else-if ladder uses an optional final else block
for unmatched values. for when no condition is true.
Extra Notes
Q26. What is a method signature? (3 marks)
A method signature consists of the method's name together with the number, types, and order of its
parameters. It does not include the return type or the access modifier. Java uses the signature to tell
overloaded methods apart, so two methods cannot share the exact same signature within the same
class.
Real-life example: It is like a person's name combined with their specific role in a company directory —
even if two employees share the same name, the unique combination (name + department + ID) tells
them apart, just like Java tells overloaded methods apart by their signature.
Q28. WAP in Java to accept an integer number from the user and display
the sum of its digits (9 marks)
Logic: The last digit of a number can be extracted using the modulus operator (num % 10), and the last
digit can be removed using integer division (num / 10). Repeating this in a loop until the number
becomes 0 lets every digit be visited exactly once, and adding each extracted digit to a running total
gives the sum of digits.
import [Link];
while (n != 0) {
int digit = n % 10;
sum = sum + digit;
n = n / 10;
}
[Link]();
}
}
Output:
The loop stops once n becomes 0, leaving sum = 15 as the final answer.
Output:
Max: 20
int max;
if (a > b) {
max = a;
} else {
max = b;
}
Real-life example: It is a one-line shortcut for a quick decision, like "if it is raining, take an umbrella;
otherwise, take sunglasses" — condensed into a single compact expression instead of writing a full
if-else block.
class ClassName {
// fields (data members)
// methods (member functions)
}
1 Encapsulation — wrapping data and methods together into a single unit (a class), and restricting
direct access to some of an object's components.
2 Inheritance — allowing a new class to acquire the properties and behaviours of an existing class.
3 Polymorphism — allowing one method name to take many forms, such as through method
overloading and overriding.
4 Abstraction — hiding complex implementation details and showing only the essential features to the
user.
Real-life example: Think of a car — the driver only needs to know how to use the steering wheel and
pedals (abstraction), the engine and wiring stay protected under the hood (encapsulation), a sports car
"is-a" car with extra features (inheritance), and pressing the accelerator behaves differently in a manual
versus an automatic car (polymorphism).
Q33. WAP in Java to illustrate class creation, object creation, and basic
OOPs concepts
class Student {
// fields - kept private (encapsulation)
private String name;
private int age;
[Link]();
[Link]();
}
}
Output:
Explanation:
• Student is the class — the blueprint defining what every student will have (a name and an age) and
what it can do (display itself).
• s1 and s2 are objects — two separate instances created from the same class, each holding its own
independent copy of the data.
• Keeping name and age private and accessing them only through the constructor and the display()
method demonstrates encapsulation.
• The same display() method produces a different result for each object, since it works on that object's
own data — the basic idea behind object-oriented behaviour.
Compiler output:
error: ';' expected
Real-life example: It is like writing a sentence with a missing full stop or a misspelt word — a reader
(the compiler) can immediately tell something is grammatically wrong, even before understanding what
the sentence was trying to say.