0% found this document useful (0 votes)
2 views24 pages

Java Exam Notes 1

Uploaded by

Avik Chowdhury
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views24 pages

Java Exam Notes 1

Uploaded by

Avik Chowdhury
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Programming — Exam Notes

Packages, Exceptions, Methods, File Handling, Basic Java & Control Statements | Total: 165
marks

Q1. What is a Package? (2 marks)


A package in Java is a mechanism used to group related classes, interfaces, and sub-packages
together under one name. It works like a folder/directory that organises files, helping to avoid naming
conflicts and making classes easier to locate, maintain, and reuse.
Real-life example: Just like a mobile phone stores "Photos" in one folder and "Videos" in another, Java
stores related classes in packages — e.g. all banking-related classes can be kept in a package called
bank.

package bank;

Q2. How do we design / create our own package? (5 marks)


Suppose you want to create two Java files and put them in a package. The steps are:

Main Java File & Class File

↓ creates

Package - java file


Class file

Step 1: Declare the package at the beginning of the file


using the form:

package packagename;

Step 2: Define the class to be put in the package, and declare it public.

package myapp;

public class Student {


void display() {
[Link]("Inside myapp package");
}
}

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]();
}
}

Compile and run:

javac [Link]
java Main

Output:

Inside myapp package

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.

Q3. How do we add a class or interface to a package? Give examples (5


marks)
A class or interface is added to a package by declaring the package statement as the first line of the file,
then compiling it so the .class file is placed in the matching folder.
A) Adding an interface to a package

package shapes;

public interface Drawable {


void draw();
}

Compile with:

javac -d . [Link]

B) Adding a class to a package


(implementing the interface above, so both are tied together)

package shapes;

public class Circle implements Drawable {


public void draw() {
[Link]("Drawing a Circle");
}
}

Compile with:
javac -d . [Link]

Both .class files now sit inside the same shapes/ folder:

shapes/
[Link]
[Link]

C) Using the class and interface in a program


A separate program (outside the package folder) imports both and uses them.

import [Link];
import [Link];

class Main {
public static void main(String args[]) {
Drawable d = new Circle();
[Link]();
}
}

Compile and run:

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.

Q4. Advantages of using a Package in Java (4 marks)


1 Avoids naming conflicts — classes with the same name can exist in different packages without
clashing (e.g. [Link] and [Link]).
2 Access protection — packages allow control over which classes/members are accessible from
outside, using access modifiers (public, protected, default, private).
3 Reusability — once a package is created, its classes can be reused in multiple programs/projects via
import.
4 Easy to locate and maintain — related classes are grouped together, making large projects easier to
organise, search, and maintain.

Q5. What is the first keyword used in Java application development? (2


marks)
The keyword package is the first keyword used (when present) in a Java source file. It must appear as
the very first statement, even before import statements, because it tells the compiler which package the
class belongs to.
package mypackage; // must be the first line
import [Link].*; // comes after package statement
class Demo { }

Q6. Naming convention for declaring a user-defined package (2 marks)


• Package names should be written in lowercase letters to avoid conflict with class/interface names.
• Words should not contain spaces; use dots (.) to separate sub-package levels (hierarchical naming).
• To ensure global uniqueness, organisations use the reversed domain name as a prefix.

Example:

package [Link];

Here, [Link] follows the reverse-domain convention used by companies (e.g.


[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.

public class Test {


public static void main(String[] args) {
int a = 10, b = 0;
int c = a / b; // causes ArithmeticException
[Link](c);
}
}

Without handling, this program terminates abruptly — exception handling prevents that.

Q7b. Common types of exceptions in Java, with examples (5 marks)


Exceptions in Java are broadly classified as checked (checked by the compiler at compile time, e.g.
IOException) and unchecked (occur at runtime, e.g. ArithmeticException). Some commonly occurring
exceptions are:
1. ArithmeticException — illegal arithmetic operation such as division by zero.

int a = 10 / 0; // throws ArithmeticException

2. NullPointerException — the program tries to use an object reference that has the value null.
String s = null;
[Link]([Link]()); // throws NullPointerException

3. ArrayIndexOutOfBoundsException — an array is accessed using an illegal index (negative, or


beyond its size).

int arr[] = new int[3];


arr[5] = 10; // throws ArrayIndexOutOfBoundsException

4. NumberFormatException — an attempt to convert a string with an invalid format into a


number.

int n = [Link]("abc"); // throws NumberFormatException

5. ClassNotFoundException — the JVM tries to load a class by name at runtime, but no


definition for that class can be found.

[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.

FileReader fr = new FileReader("[Link]");


// throws FileNotFoundException if file is missing

Q7c. Difference between compile-time error and run-time error (7 marks)


Compile-time error:
An error that occurs while the source code is being compiled, detected by the Java compiler (javac)
before the program is converted into bytecode. These are mainly violations of Java's syntax rules, and
are also known as syntax errors.

int x = 10 // missing semicolon

Compiler output:

error: ';' expected

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:

Exception in thread "main" [Link]: / by zero

Key differences:

Compile-time Error Run-time Error

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.

Example: int x = 10 (missing semicolon) Example: int c = a/b; where b = 0 compiles


causes a compiler error before the program ever fine but throws an ArithmeticException when
runs. executed.

Q8a. What is try, catch, finally block in Java? (3 marks)


Java provides a structured exception-handling mechanism using three keywords — try, catch, and
finally — that work together to detect and handle runtime errors without terminating the program
abnormally.
• try block: The block of code that is suspected to throw an exception is placed inside try. The JVM
monitors this code while it executes; the moment an exception occurs, execution of the try block stops
immediately, and control jumps to the matching catch block.
• catch block: Follows the try block and is used to handle the exception thrown by it. It takes the
exception type as a parameter. A single try block can be followed by multiple catch blocks, each
handling a different type of exception.
• finally block: An optional block placed after the catch block(s). The code inside finally always
executes — whether an exception occurred or not, and whether it was caught or not — which makes it
ideal for cleanup work such as closing files, releasing memory, or closing database connections.

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
}

Q8b. When and how is it used? (2 marks)


When: Used whenever a block of code might throw an exception during execution — for example,
dividing numbers, accessing arrays, reading files, or parsing user input — and we want the program to
handle the problem gracefully instead of crashing.
How: The risky code is placed inside try. One or more catch blocks are written to handle specific
exception types. An optional finally block is added for cleanup code that must run regardless of the
outcome.

Q8c. Give a suitable example (6 marks)


public class Demo {
public static void main(String[] args) {
try {
int a = 10, b = 0;
int c = a / b;
[Link]("Result: " + c);
} catch (ArithmeticException e) {
[Link]("Exception caught: " + e);
} finally {
[Link]("Finally block executed");
}
[Link]("Program continues...");
}
}

Output:

Exception caught: [Link]: / by zero


Finally block executed
Program continues...

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.

Q8d. List some common types of exceptions in Java, with examples (3


marks)
• ArithmeticException — int x = 5/0;
• NullPointerException — String s = null; [Link]();
• ArrayIndexOutOfBoundsException — int arr[] = new int[2]; arr[3] = 1;

Methods, Constructors & Overloading


Q9a. What is a method and how is it different from a constructor? (4 marks)
Method: A method is a block of code/collection of statements defined inside a class that performs a
specific task. It has a return type (or void), and is called explicitly using its name whenever required —
possibly many times.
Constructor: A constructor is a special block used to initialize an object at the moment it is created. It
has the same name as the class, has no return type at all (not even void), and is called automatically —
only once — when an object is created using new.
Real-life example: A constructor is like the orientation process a new employee goes through on their
very first day — it happens automatically, once, to set up their initial details (ID card, desk, login). A
method is like a specific task the employee performs again and again during work, such as "generate
report" — called whenever it is needed.
Key differences:

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.

A method is called explicitly by the programmer


A constructor is called automatically and implicitly
using the dot operator, in the form
by the JVM the moment an object of the class is
[Link](), and only when
created using the new keyword.
needed.

A method can be called any number of times


A constructor is invoked only once for every object
during the lifetime of a program, on the same or
that is created, exactly at the time of its creation.
different objects.

A method defines the behaviour or operations that


A constructor defines how the initial state (values
an object can perform after it has already been
of variables) of an object is set up before it is used.
created.

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);
}
}

Q9b. How do we invoke a constructor? (3 marks)


A constructor is not called explicitly like a normal method. It is invoked automatically the moment an
object of the class is created, using the new keyword.
Syntax:

ClassName obj = new ClassName(arguments);

class Student {
Student() {
[Link]("Default constructor invoked");
}
Student(String name) {
[Link]("Parameterized constructor invoked for " + name);
}
}

public class Main {


public static void main(String[] args) {
Student s1 = new Student(); // default constructor
Student s2 = new Student("Riya"); // parameterized constructor
}
}

Output:

Default constructor invoked


Parameterized constructor invoked for Riya

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.

Q9c. Write a program in Java to illustrate the concept of Method


Overloading (7 marks)
Method overloading is a feature in Java that allows a class to have more than one method with the
same name, as long as their parameter lists differ — in the number of parameters or their type. It is a
form of compile-time (static) polymorphism, since the compiler decides which method to call based
on the arguments passed, at compile time itself.
Program — calculating the area of different shapes using overloaded area() methods:
class AreaCalculator {

// Area of Square - one int parameter


double area(int side) {
return side * side;
}

// Area of Circle - one double parameter


double area(double radius) {
return 3.14159 * radius * radius;
}

// Area of Rectangle - two double parameters


double area(double length, double breadth) {
return length * breadth;
}

// Area of Triangle - two int parameters


double area(int base, int height) {
return 0.5 * base * height;
}
}

public class Main {


public static void main(String[] args) {
AreaCalculator calc = new AreaCalculator();

[Link]("Area of Square: " + [Link](5));


[Link]("Area of Circle: " + [Link](3.5));
[Link]("Area of Rectangle: " + [Link](4.0, 6.0));
[Link]("Area of Triangle: " + [Link](8, 5));
}
}

Output:

Area of Square: 25.0


Area of Circle: 38.4844775
Area of Rectangle: 24.0
Area of Triangle: 20.0

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.

Q11. Difference between Input Stream and Output Stream (7 marks)


InputStream:
An abstract class in [Link] representing a stream of bytes being read into a program from a source
such as a file, keyboard, or network connection. All byte-input classes (like FileInputStream) extend it,
and the basic method used to read data is read().

FileInputStream fis = new FileInputStream("[Link]");


int ch = [Link](); // reads one byte into the program

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().

FileOutputStream fos = new FileOutputStream("[Link]");


[Link](65); // writes one byte ('A') to the file

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.

Common subclasses include FileOutputStream,


Common subclasses include FileInputStream,
ByteArrayOutputStream, and
ByteArrayInputStream, and BufferedInputStream.
BufferedOutputStream.

An OutputStream object can create a new file (or


An InputStream object is typically opened on a file
overwrite/append an existing one) to write content
that already exists, in order to read its content.
into it.
Once writing is done, the OutputStream should be
Once reading is done, the InputStream should be
closed using close() to flush the data and release
closed using close() to release the file resource.
the resource.

Q12a. What is the use of the RandomAccessFile class in Java? (3 marks)


RandomAccessFile is a class in [Link] that allows both reading and writing to a file at any position, not
just sequentially from the beginning. Unlike FileInputStream/FileOutputStream, which can only move
through a file strictly in order, RandomAccessFile maintains a movable file pointer, repositioned using
seek(), allowing data to be read or written at any byte offset. It is commonly used to update a specific
record in a file, append data, or build simple file-based record structures.

RandomAccessFile raf = new RandomAccessFile("[Link]", "rw");


[Link]([Link]()); // move pointer to end of file
[Link]("New line"); // write at that position
[Link]();

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.

FileOutputStream fos1 = new FileOutputStream("[Link]");


// write mode - old content erased

FileOutputStream fos2 = new FileOutputStream("[Link]", true);


// append mode - old content kept

Q13. Explain EOF handling in Java with example (5 marks)


EOF (End Of File) is the point in a file where no more data is left to read. Java does not throw an
exception for reaching EOF in most cases — instead, each type of stream/reader has its own signal for
it, and a program is expected to check for that signal in a loop. The common ways of detecting and
handling EOF are:
1. Using read() returning -1 (byte streams, e.g. FileInputStream)
The read() method of InputStream returns the next byte as an int, or -1 once the end of the file has been
reached. This is the most common way to detect EOF when reading raw bytes.

FileInputStream fis = new FileInputStream("[Link]");


int ch;
while ((ch = [Link]()) != -1) {
[Link]((char) ch);
}
[Link]();

2. Using readLine() returning null (character streams, e.g. BufferedReader)


When reading text line by line, readLine() returns the next line as a String, or null once there are no
more lines left in the file. This is the standard way to detect EOF while reading a file line by line.
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();

3. Using hasNext() / hasNextLine() (Scanner class)


The Scanner class provides hasNext() and hasNextLine(), which return true only if more input is
available. This avoids ever reading past the end of the file, since the check is done before each read.

Scanner sc = new Scanner(new File("[Link]"));


while ([Link]()) {
[Link]([Link]());
}
[Link]();

4. Using the EOFException (DataInputStream)


Methods like readInt() and readUTF() in DataInputStream do not return a sentinel value at all — instead,
they throw an EOFException the moment they are called after the file has ended. Here, EOF is handled
by catching that exception.

DataInputStream dis = new DataInputStream(new FileInputStream("[Link]"));


try {
while (true) {
int value = [Link]();
[Link](value);
}
} catch (EOFException e) {
[Link]("End of file reached");
} finally {
[Link]();
}

5. Using available() (InputStream)


The available() method returns an estimate of how many bytes can still be read. Once it reaches 0, it
usually signals that the end of the file is near. This method is less precise than the others, so it is
normally used only for a quick, informal check.

FileInputStream fis = new FileInputStream("[Link]");


while ([Link]() > 0) {
[Link]((char) [Link]());
}
[Link]();

Q14. WAP to accept two files via command-line arguments and compare
their content
import [Link];
import [Link];

public class CompareFiles {


public static void main(String[] args) {
if ([Link] != 2) {
[Link]("Usage: java CompareFiles <file1> <file2>");
return;
}

FileInputStream fis1 = null;


FileInputStream fis2 = null;

try {
fis1 = new FileInputStream(args[0]);
fis2 = new FileInputStream(args[1]);

int ch1, ch2;


boolean same = true;

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];

public class DeleteFileProgram {


public static void main(String[] args) {
if ([Link] != 1) {
[Link]("Usage: java DeleteFileProgram <filename>");
return;
}

File file = new File(args[0]);

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]

java DeleteFileProgram [Link]


File not found

Q16. WAP to read a text file and count the total number of vowels (14
marks)
import [Link];
import [Link];
import [Link];

public class CountVowels {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
FileInputStream fis = null;

[Link]("Enter file name: ");


String fileName = [Link]();

int vowelCount = 0;

try {
fis = new FileInputStream(fileName);
int ch;

while ((ch = [Link]()) != -1) {


char c = [Link]((char) ch);
if ("aeiou".indexOf(c) != -1) {
vowelCount++;
}
}

[Link]("Total number of vowels: " + vowelCount);

} catch (IOException e) {
[Link]("File not found: " + [Link]());
} finally {
try {
if (fis != null) [Link]();
} catch (IOException e) {
[Link]("Error closing file");
}
}

[Link]();
}
}

Output:

Enter file name: [Link]


Total number of vowels: 48

Q17. WAP to read a text file and count the total number of consonants (14
marks)
import [Link];
import [Link];
import [Link];

public class CountConsonants {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
FileInputStream fis = null;

[Link]("Enter file name: ");


String fileName = [Link]();

int consonantCount = 0;

try {
fis = new FileInputStream(fileName);
int ch;

while ((ch = [Link]()) != -1) {


char c = [Link]((char) ch);
if (c >= 'a' && c <= 'z' && "aeiou".indexOf(c) == -1) {
consonantCount++;
}
}

[Link]("Total consonants: " + consonantCount);

} catch (IOException e) {
[Link]("File not found: " + [Link]());
} finally {
try {
if (fis != null) [Link]();
} catch (IOException e) {
[Link]("Error closing file");
}
}

[Link]();
}
}

Output:

Enter file name: [Link]


Total consonants: 112

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];

public class CountWords {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
FileInputStream fis = null;

[Link]("Enter file name: ");


String fileName = [Link]();

int spaceCount = 0;

try {
fis = new FileInputStream(fileName);
int ch;

while ((ch = [Link]()) != -1) {


char c = (char) ch;
if (c == ' ') {
spaceCount++;
}
}

int wordCount = spaceCount + 1;


[Link]("Total number of words: " + wordCount);

} catch (IOException e) {
[Link]("File not found: " + [Link]());
} finally {
try {
if (fis != null) [Link]();
} catch (IOException e) {
[Link]("Error closing file");
}
}

[Link]();
}
}

Output:

Enter file name: [Link]


Total number of words: 21

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];

public class CountSentences {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
FileInputStream fis = null;

[Link]("Enter file name: ");


String fileName = [Link]();

int sentenceCount = 0;

try {
fis = new FileInputStream(fileName);
int ch;

while ((ch = [Link]()) != -1) {


char c = (char) ch;
if (c == '.' || c == ';') {
sentenceCount++;
}
}

[Link]("Total sentences: " + sentenceCount);

} catch (IOException e) {
[Link]("File not found: " + [Link]());
} finally {
try {
if (fis != null) [Link]();
} catch (IOException e) {
[Link]("Error closing file");
}
}

[Link]();
}
}

Output:

Enter file name: [Link]


Total sentences: 5

Q20. WAP to check a user-entered password against the content of a


password file
import [Link];
import [Link];
import [Link];

public class PasswordCheck {


public static void main(String[] args) {
FileInputStream fis = null;
Scanner sc = new Scanner([Link]);

try {
fis = new FileInputStream("[Link]");

String fileString = "";


int ch;

while ((ch = [Link]()) != -1) {


fileString = fileString + (char) ch;
}

fileString = [Link]();

[Link]("Enter password: ");


String userInput = [Link]().trim();

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:

Enter password: java123


Password match

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.

Q22. Why is Java platform independent? (4 marks)


Java achieves platform independence because Java source code is not compiled directly into machine
code specific to a particular operating system. Instead, the Java compiler (javac) converts the source
code into an intermediate form called bytecode (.class files), which is identical regardless of the
underlying hardware or OS. This bytecode is then executed by the Java Virtual Machine (JVM), and
since a separate JVM implementation is built for each platform (Windows, Linux, Mac, etc.), the very
same bytecode file can run unmodified on any machine that has its own JVM installed. This is
summarised by Java's famous motto, "Write Once, Run Anywhere" (WORA).

javac [Link] // compiles to platform-independent bytecode


java HelloWorld // JVM (specific to this OS) runs the bytecode

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.

Q23. What is JVM and Bytecode in Java? (5 marks)


JVM (Java Virtual Machine): An abstract computing machine that provides the runtime environment in
which Java bytecode is executed. It loads class files, verifies the bytecode for safety, converts it into
native machine code (using a Just-In-Time compiler), manages memory through garbage collection,
and provides platform independence since a separate JVM implementation exists for every operating
system.
Bytecode: The intermediate, platform-independent code generated by the Java compiler (javac) when
a .java source file is compiled. It is stored in .class files and consists of a set of instructions that the JVM
understands and executes, regardless of the underlying hardware. Because bytecode is not tied to any
specific machine, it is what allows Java programs to be portable across platforms.
Flow:
Source code ([Link])
| compiled by javac
v
Bytecode ([Link])
| executed by the JVM
v
Output (runs on Windows, Linux, Mac, ...)

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.

for (int i = 1; i <= 5; i++) {


[Link](i);
}

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:

while loop do-while loop

A while loop is known as an entry-controlled loop, A do-while loop is known as an exit-controlled


since the condition is tested at the entry point, loop, since the condition is tested at the exit point,
before the loop body runs. after the loop body runs.

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.

Q25. Difference between switch case and if-else-if (7 marks)


switch case:
A control statement that compares a single variable or expression against multiple constant values
(cases) and executes the matching block of code; it uses the keywords switch, case, break, and default.

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:

switch case if-else-if

A switch statement compares one variable against An if-else-if ladder evaluates a separate boolean
several fixed constant values, for example condition at each step, for example day==1,
switch(day) checking case 1, case 2, case 3 in day>5, or [Link]("Sam"), which need not all
turn. relate to the same variable.

A switch statement can only test for exact equality An if-else-if ladder can test any boolean
with constant values such as int, char, String, or expression, including ranges and complex
enum, for example case 3: matches only when the conditions, for example if(marks >= 40 && marks <
value is exactly 3. 60), which a switch cannot express directly.

Inside a switch block, each matching case must


Inside an if-else-if ladder, only the block of the first
usually end with a break statement, otherwise
true condition runs, and the rest are automatically
execution falls through into the next case, for
skipped, with no equivalent of fall-through to worry
example forgetting break after case 1 also runs
about.
case 2's code.

A switch statement is generally more efficient


An if-else-if ladder checks each condition
when there are many fixed values to check, since
sequentially from top to bottom, so its performance
the compiler can sometimes use a jump table
can degrade as more conditions are added.
instead of testing each value one by one.
The readability of a switch statement is usually The readability of an if-else-if ladder is usually
better when checking one variable against many better when the conditions involve ranges or
discrete values, such as printing the name of a day multiple different variables, such as grading marks
from a number 1 to 7. into A, B, C, D bands.

A switch statement supports an optional default An if-else-if ladder supports an optional final else
block, which runs only if none of the case values block, which runs only if none of the preceding
match, for example default: conditions were true, serving the same purpose as
[Link]("Invalid day");. default.

A switch statement in modern Java can also be An if-else-if ladder has no equivalent expression
written as a switch expression that directly returns form; it can only be used as a series of statements,
a value using arrow syntax, for example case 3 -> not as a single expression that returns a value
"Wednesday";. directly.

You might also like