0% found this document useful (0 votes)
4 views182 pages

Core Java Finale

Java supports multiple programming paradigms including Object-Oriented, Structured, and Concurrent. It has different editions like Java SE for desktop applications and Java EE for enterprise-level applications, emphasizing its versatility. Key features include platform independence through bytecode, automatic memory management via garbage collection, and robust security measures.

Uploaded by

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

Core Java Finale

Java supports multiple programming paradigms including Object-Oriented, Structured, and Concurrent. It has different editions like Java SE for desktop applications and Java EE for enterprise-level applications, emphasizing its versatility. Key features include platform independence through bytecode, automatic memory management via garbage collection, and robust security measures.

Uploaded by

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

Short Question

[Link] are the different programming paradigms supported by Java?


👉 Java supports Object-Oriented, Structured (Procedural), and Concurrent (Multithreading)
paradigms.

2. Explain any two flavors (editions) of Java and their use cases.
👉 Java SE (Standard Edition): Used for desktop and core Java applications.
👉 Java EE (Enterprise Edition): Used for web-based and enterprise-level applications.

3. What was the primary design goal behind the creation of Java?
👉 The main goal was to create a portable, platform-independent, and secure programming
language.

4. List any three key features of the Java language.


👉 Platform Independent, Object-Oriented, and Automatic Memory Management (Garbage
Collection).

5. What is the role of the JVM (Java Virtual Machine) in Java?


👉 JVM executes the compiled bytecode and makes Java programs run on any platform.

6. How does Java achieve platform independence?


👉 Java code is compiled into bytecode, which can run on any system having a JVM.

7. What is bytecode in Java, and why is it called "Java’s magic"?


👉 Bytecode is the intermediate code generated by the compiler.
It’s called “magic” because it lets Java programs run anywhere using JVM.

8. Differentiate between JDK, JRE, and JVM.

Term Full Form Function

JDK Java Development Kit Used for developing Java programs (includes JRE + tools).

JRE Java Runtime Environment Used for running Java programs (includes JVM + libraries).

JVM Java Virtual Machine Executes bytecode.

9. Why is Java considered a secure language?


👉 Java doesn’t use pointers, runs in a sandbox environment, and has bytecode verification and
security manager.
10. How does garbage collection work in Java?
👉 Java’s Garbage Collector automatically removes unused objects from memory, freeing space and
preventing memory leaks.

Long Question
1. Explain the different programming paradigms supported by Java. Compare and contrast
procedural, object-oriented, and functional programming with examples in Java.
2. Discuss the various flavors (editions) of Java (J2SE, J2EE, J2ME). Explain their key
features, applications, and how they differ from each other.
3. What were the primary design goals behind the creation of Java? Discuss how features
like platform independence, security, and simplicity contribute to these goals.
4. Explain the major features of the Java programming language, such as portability,
multithreading, robustness, and security. Provide examples where applicable.
5. Describe the Java Virtual Machine (JVM) in detail. Explain its architecture, components,
and how it enables "Write Once, Run Anywhere" (WORA) capability.
Perfect 👍 Uzma!

1. Explain the different programming paradigms supported by Java. Compare and contrast
procedural, object-oriented, and functional programming with examples in Java.
Java supports three main programming paradigms – Procedural, Object-Oriented, and
Functional.
1. Procedural Programming
 Focuses on step-by-step instructions.
 The program is divided into functions or methods.
 Data and functions are separate.
Example:
public class Sum {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(10, 20);
[Link]("Sum = " + result);
}
}
 Real-life example:
Cooking with a recipe — you follow steps one by one.

2. Object-Oriented Programming (OOP)


 Everything is treated as an object that contains data (variables) and behavior (methods).
 Uses concepts like inheritance, polymorphism, abstraction, and encapsulation.
 Example:
class Car {
void start() {
[Link]("Car is starting...");
}
}
public class Test {
public static void main(String[] args) {
Car c = new Car();
[Link]();
}
}
 Real-life example:
A car is an object — it has data (color, model) and behavior (start, stop).

3. Functional Programming
 Focuses on functions as first-class citizens.
 Uses lambda expressions and avoids changing data (immutability).
 Example:
import [Link].*;
public class Example {
public static void main(String[] args) {
List<Integer> numbers = [Link](1, 2, 3, 4);
[Link](n -> [Link](n * n)); // print squares
}
}
 Real-lifee example
Like giving a rule — “for every student, print their marks × 2” — instead of manually doing it
one by one.

Comparison Table:
Paradigm Focus Example
Procedural Functions & steps add(a,b)
Object-Oriented Objects & classes [Link]()
[Link]
Functional Functions & expressions
ch()

2. Discuss the various flavors (editions) of Java (J2SE, J2EE, J2ME). Explain their key features,
applications, and how they differ from each other.
Java comes in different editions to serve different purposes:
1. J2SE (Java 2 Standard Edition)
 Used for core Java programming.
 Includes features like OOP concepts, I/O, Collections, Exception handling, etc.
 Used for desktop and console-based applications.
 Example: Making a calculator app or a school management system for PC.

2. J2EE (Java 2 Enterprise Edition)


 Used for large-scale web and business applications.
 Supports Servlets, JSP, EJB, and Web Services.
 Used by companies to build online shopping sites, banking systems, etc.
 Example: Amazon, Flipkart backend servers run on enterprise Java.

3. J2ME (Java 2 Micro Edition)


 Used for mobile devices and embedded systems.
 Lightweight and designed for devices with limited memory and power.
 Example: Old Nokia mobile games and apps were made using J2ME.

Difference Table:
Edition Full Form Used For Example
J2SE Standard Edition Core/desktop apps Calculator app
J2EE Enterprise Edition Web/business apps Online banking
J2ME Micro Edition Mobile/embedded apps Old phone games

3. What were the primary design goals behind the creation of Java? Discuss how features like
platform independence, security, and simplicity contribute to these goals.
The main goal of Java was to create a language that is:
 Simple
 Secure
 Portable
 Platform Independent

1. Platform Independence
 Java code is compiled into bytecode, which runs on any system having JVM.
 “Write Once, Run Anywhere (WORA)” means one code can work on Windows, Linux, or
Mac.
 Example: A Java game developed on Windows can run on Android or Mac too.

2. Security
 Java does not use pointers, so memory cannot be accessed directly.
 Java programs run in a sandbox, preventing viruses or unauthorized access.
 Example: Online banking applications use Java because of its high security.

3. Simplicity
 Java syntax is easy to read and similar to C/C++, but without complex parts like pointers.
 It handles memory automatically using garbage collection.

4. Robustness
 Java checks code both at compile time and runtime to prevent errors.
 Example: If a student app crashes, Java shows clear error messages, making it easier to fix.

4. Explain the major features of the Java programming language, such as portability,
multithreading, robustness, and security. Provide examples where applicable.
1. Portability
 Java programs can run on any platform that has a JVM.
 Example: A Java attendance app developed on Windows can also run on Linux.

2. Multithreading
 Java allows multiple tasks to run at the same time.
 Example: A music app plays songs while downloading another one.
class Task extends Thread {
public void run() {
[Link]("Task running...");
}
}
public class Test {
public static void main(String[] args) {
new Task().start();
}
}

3. Robustness
 Java handles errors and memory safely.
 It avoids crashes using exception handling and garbage collection.
 Example: If your app tries to open a missing file, Java shows an exception instead of crashing.

4. Security
 Java provides a secure execution environment.
 Features: No pointers, bytecode verification, sandbox model.
 Example: Java is used in ATM software for safety reasons.

5. Describe the Java Virtual Machine (JVM) in detail. Explain its architecture, components, and
how it enables "Write Once, Run Anywhere" (WORA) capability.
What is JVM?
 JVM stands for Java Virtual Machine.
 It is a part of JRE that executes Java bytecode.
 It allows Java programs to run on any platform, making it platform independent.

Architecture of JVM
1. Class Loader:
o Loads .class (bytecode) files into memory.
o Example: When you run a Java program, class loader loads it first.
2. Bytecode Verifier:
o Checks if the bytecode is safe and valid.
o Prevents unauthorized code execution.
3. Interpreter:
o Converts bytecode into machine code line by line.
4. JIT (Just-In-Time) Compiler:
o Improves performance by compiling bytecode into native code during runtime.
5. Memory Areas:
o Heap Area: Stores objects.
o Stack Area: Stores method calls and variables.
o Method Area: Stores class structure and methods.
o PC Register: Keeps track of current instruction.
6. Execution Engine:
o Executes the compiled code efficiently.

How JVM enables WORA (Write Once, Run Anywhere):


 When you compile a Java file, it becomes bytecode (.class).
 JVM on any device reads and executes this bytecode.
 That’s why the same Java program runs on Windows, Mac, or Android.

Real-life example:
If you create a Java billing software in college using Windows,
the same software can run on your teacher’s Linux computer without any changes — because of
JVM.

6. What is bytecode in Java? Explain how Java achieves platform independence using bytecode and
JVM. Compare it with traditional compiled and interpreted languages.

What is Bytecode?

 Bytecode is an intermediate code created when Java source code (.java) is compiled.

 It is stored in .class files and can be executed on any system that has a Java Virtual Machine
(JVM).

 It is not machine code, but a special code that JVM understands.

Example:

public class Hello {

public static void main(String[] args) {

[Link]("Hello Java");

When compiled → [Link] → contains bytecode.

How Java achieves Platform Independence

1. Java compiler converts code into bytecode.

2. The JVM on each platform (Windows, Linux, Mac, etc.) translates this bytecode into machine
code for that system.

3. So, one Java program can run anywhere — this is called “Write Once, Run Anywhere”
(WORA).

Real-life Example:
If you create a Java attendance system on Windows, your teacher can run it on Linux without any
changes — because the JVM makes it platform-independent.
Comparison with other languages

Example
Type Working Limitation
Language

Compiled Directly converted to machine


C, C++ Works only on that platform
Language code for one OS

Interpreted
Python Executes line by line, slower Platform independent but slower
Language

Compiled to bytecode, then Platform independent and faster


Java (Hybrid) Java
executed by JVM than interpreted

7. Discuss the role of Just-In-Time (JIT) compiler in JVM. How does it improve Java’s performance
compared to purely interpreted languages?

What is JIT Compiler?

 The Just-In-Time (JIT) compiler is a part of the JVM.

 It improves performance by converting bytecode into machine code at runtime (when the
program is running).

 This avoids interpreting each line again and again.

How it Works

1. Java compiler → creates bytecode.

2. JVM starts running it line by line (interpreting).

3. JIT compiler detects frequently used code (called “hot spots”) and compiles it into native
machine code.

4. Next time, JVM runs that part directly without reinterpreting — making it faster.

Why JIT Improves Performance

 Less time spent interpreting code.

 Reuses compiled native code for repeated tasks.

 Faster execution compared to purely interpreted languages.

Comparison:
Type Example Performance

Interpreted Python, JavaScript Slower – reads line by line

JIT Compiled (Java) Java Faster – compiles while running

Fully Compiled C++ Fastest – machine code from start, but not portable

Real-life example:
If you open a Java-based online form daily, JIT remembers and optimizes the code — so it loads faster
the next time.

8. Explain the significance of garbage collection in Java. How does it work? Compare it with manual
memory management in languages like C/C++.

What is Garbage Collection?

 Garbage Collection (GC) in Java automatically removes unused objects from memory.

 It helps in managing memory efficiently without the programmer doing it manually.

How it Works

1. Java program creates objects in memory (Heap area).

2. When an object is no longer referenced, it becomes “garbage.”

3. The Garbage Collector identifies and deletes such unused objects.

4. This frees up space for new objects automatically.

Example:

class Example {

public static void main(String[] args) {

String name = new String("Uzma");

name = null; // object is now garbage

[Link](); // suggest garbage collection

Benefits

 Prevents memory leaks.

 Improves application performance.

 Reduces programmer errors.


Comparison with C/C++

Feature Java C/C++

Memory Management Automatic (Garbage Collector) Manual (malloc, free)

Error Chances Less High (memory leaks, dangling pointers)

Programmer Effort Easy Hard

Real-life Example:
It’s like having a house cleaner who automatically removes trash — you don’t need to remember
what to throw away.

9. What are the security features in Java? Discuss how the JVM, bytecode verifier, and Security
Manager contribute to making Java a secure language.

Java’s Security Features

Java is known as a secure language because it provides a safe environment to run programs without
harming the system.

1. No Pointers

 Java doesn’t use pointers to access memory directly.

 This avoids memory corruption and hacking attempts.

2. Bytecode Verification

 Before execution, JVM’s bytecode verifier checks the code for illegal instructions, type
errors, or unauthorized access.

3. JVM Sandbox

 Programs run inside a sandbox, a safe area where they can’t access system files directly.

4. Security Manager

 It defines rules and permissions — like whether a program can read or write files, or connect
to the internet.

5. ClassLoader

 Loads only trusted classes and keeps untrusted code separate.

Example:

If you download a Java applet from the internet, JVM checks:

1. Is it safe code (bytecode verification)?

2. Is it allowed to access your local files (security manager)?


3. Is it isolated from your system (sandbox)?

Thus, your computer remains protected.

Comparison:

Language Security Reason

Java High No pointers, bytecode verification

C++ Low Direct memory access

Python Medium Depends on interpreter sandbox

Real-life example:
Running an unknown Java app online is like opening it in a safe box — it can’t damage your
computer.

10. Critically analyze Java’s strengths and weaknesses as a programming language. Compare it with
other languages like Python or C++.

Strengths of Java

1. Platform Independent:

o Works on any OS with JVM — “Write Once, Run Anywhere.”

o ✅ Example: Same Java banking app can run on Windows or Linux.

2. Object-Oriented:

o Easy to model real-world systems using objects.

o ✅ Example: In a school system, Student and Teacher can be separate classes.

3. Automatic Memory Management:

o Garbage Collector frees unused memory automatically.

4. Secure:

o No pointers, sandbox model, bytecode verification.

5. Rich Libraries:

o Ready-made classes for networking, file handling, GUI, etc.

6. Multithreading:

o Handles multiple tasks together — good for games, servers, etc.

Weaknesses of Java

1. Slower than C++:


o Because Java runs on JVM, not directly on hardware.

2. More Memory Usage:

o JVM and garbage collector consume extra memory.

3. Verbose Syntax:

o Requires more lines of code than Python.

4. Not Ideal for Small Scripts:

o Python is simpler for small automation tasks.

Comparison Table:

Feature Java Python C++

Speed Medium Slow Fast

Ease of Learning Moderate Very Easy Hard

Memory Management Automatic Automatic Manual

Platform Independence Yes (via JVM) Yes No

Security High Medium Low

Web, mobile, System, gaming, hardware-level


Use Case AI, data science
enterprise apps

Conclusion:

Java is a balanced, powerful, and secure language — best suited for web apps, mobile apps, and
enterprise systems.
While Python is easier for beginners and C++ is faster for system-level work, Java stands strong as a
multi-purpose, reliable language.
SSCA2022 – Core Java
Question Bank

Short Questions
1. A __________ error occurs when the code violates the rules of the programming language.
2. To check intermediate values during code execution, programmers often use __________
statements.
3. De ine debugging in one sentence.
4. Which of the following is a runtime error in Java?
[Link] semicolon
B. NullPointerException
C. Undeclared variable
[Link] brackets
5. Which tool is commonly used to ind and ix errors in Java programs?
[Link]
B. Javadoc
C. Debugger D. Git
Short Questions
1. What is a logic error? Give one example.
2. Differentiate between syntax error and runtime error.
3. What is a NullPointerException in Java?
4. List any two debugging techniques used in Java. 5. Explain the use of error messages in debugging.
6. Mention any two resources available to a Java developer for debugging.
7. What is the purpose of commenting code while debugging?
8. How does the use of debugging tools improve problem-solving in Java?
9. What is an Arithme cExcep on? Give a simple example where it may occur.
10. De ine IndexOutOfBoundsExcep on and mention when it is commonly encountered.
11. Why is understanding error messages important in debugging?
12. How do runtime errors differ from logic errors?
🌸 Very Short Questions
1. A syntax error occurs when the code violates the rules of the programming language.
2. To check intermediate values during code execution, programmers often use print statements.
3. Debugging is the process of finding and fixing errors in a program.
4. Which of the following is a runtime error in Java?
✅ B. NullPointerException
5. Which tool is commonly used to find and fix errors in Java programs?
✅ C. Debugger

🌼 Short Questions
1. What is a logic error? Give one example.
A logic error happens when the program runs but gives the wrong output because of a mistake in logic.
👉 Example:
int a = 5, b = 10;
[Link](a - b); // instead of a + b
Output is wrong but program runs fine.

2. Differentiate between syntax error and runtime error.

Type Description Example

Syntax Error Occurs when rules of the language are broken. Missing semicolon (;)

Runtime Error Occurs while program is running. Divide by zero

3. What is a NullPointerException in Java?


It occurs when a program tries to use an object that has no value (null).
👉 Example:
String s = null;
[Link]([Link]()); // NullPointerException

4. List any two debugging techniques used in Java.


1.) Using print statements to check variable values.
2.) Using debugger tools in IDEs like Eclipse or IntelliJ.

5. Explain the use of error messages in debugging.


Error messages show what went wrong and where it happened in the code.
They help the programmer quickly locate and fix problems.

6. Mention any two resources available to a Java developer for debugging.


1.) Integrated Development Environments (IDEs) like Eclipse or IntelliJ.
2.) Java documentation or online forums like Stack Overflow.

7. What is the purpose of commenting code while debugging?


Comments help the programmer understand or disable parts of the code temporarily to test specific
areas and find errors easily.

8. How does the use of debugging tools improve problem-solving in Java?


Debugging tools allow step-by-step code execution, showing variable values and logic flow, making it
easier to find mistakes.

9. What is an ArithmeticException? Give a simple example where it may occur.


It happens when an illegal math operation occurs, like dividing by zero.
👉 Example:
int x = 10 / 0; // ArithmeticException

10. Define IndexOutOfBoundsException and mention when it is commonly encountered.


This error happens when we try to access an index outside the size of an array or list.
👉 Example:
int arr[] = {1, 2, 3};
[Link](arr[5]); // IndexOutOfBoundsException

11. Why is understanding error messages important in debugging?


Because they point to the exact location and type of error, saving time and helping the programmer fix
issues quickly.

12. How do runtime errors differ from logic errors?

Type When it Occurs Effect

Runtime Error While the program is running Program crashes or stops

Program runs but gives incorrect


Logic Error After running (wrong output)
results
Module-2

Long Questions
1. Describe the debugging process with its main steps.
2. Discuss any ive common Java exceptions and how to handle them.
3. Explain how print statements and comments can help in debugging. Give examples.
4. Explain three types of errors in Java with examples: syntax, runtime, and logic errors.
5. Describe the role of an Integrated Development Environment (IDE) in debugging Java programs.
6. What are some effective problem-solving strategies used during debugging? Illustrate with
examples.
7. Discuss how debugging can be improved by using external documentation and of icial Java API
references.
8. Write a Java code snippet that generates a NullPointerException and explain step-by-step how you
would debug it.
9. How can structured debugging with systematic questioning help in locating bugs? Explain with a
scenario.

1. Describe the debugging process with its main steps.

Answer:

Debugging is the process of finding and fixing errors (bugs) in a computer program. It ensures
that the program runs smoothly and gives correct output.

The main steps in the debugging process are:

🔹 1. Identify the Problem

The first step is to notice that something is wrong — for example, wrong output or a program
crash.
The programmer observes the behavior and confirms that an error exists.

🔹 2. Reproduce the Error

The programmer tries to run the program again with the same input to make sure the error
can be repeated.
This helps to understand when and how the error occurs.

🔹 3. Analyze the Error

Next, the programmer reads the error message or uses debugging tools to find the exact line
or section where the problem occurs.

🔹 4. Find the Cause

By checking variable values and logic, the programmer finds the root cause of the error — for
example, wrong logic, missing condition, or uninitialized variable.
🔹 5. Fix the Code

Once the cause is clear, the programmer edits the code to remove or correct the mistake.

🔹 6. Test the Program Again

After fixing, the program is tested again with different inputs to confirm that the problem is
solved and no new bugs were created.

🔹 7. Document the Fix

Finally, the changes and fixes are noted down (commented) so that other programmers can
understand what was corrected.

✅ Example:
If your code shows NullPointerException,
you identify it, check where the null value occurs, correct the logic, and then run again to
confirm the fix.

2. Discuss any five common Java exceptions and how to handle them.

Answer:

In Java, exceptions are errors that occur during program execution.


They can be handled using a try-catch block to prevent program crash.

Here are five common exceptions and how to handle them:

🔹 1. ArithmeticException

Occurs when an illegal math operation happens, like dividing by zero.

try {

int a = 10 / 0;

} catch (ArithmeticException e) {

[Link]("Cannot divide by zero!");

🔹 2. NullPointerException

Occurs when a null object is accessed.

try {

String s = null;

[Link]([Link]());
} catch (NullPointerException e) {

[Link]("Object is null!");

🔹 3. ArrayIndexOutOfBoundsException

Occurs when we access an array index that does not exist.

try {

int arr[] = {1, 2, 3};

[Link](arr[5]);

} catch (ArrayIndexOutOfBoundsException e) {

[Link]("Invalid array index!");

🔹 4. NumberFormatException

Occurs when a string cannot be converted into a number.

try {

int num = [Link]("abc");

} catch (NumberFormatException e) {

[Link]("Invalid number format!");

🔹 5. FileNotFoundException

Occurs when the program tries to open a file that doesn’t exist.

try {

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

} catch (FileNotFoundException e) {

[Link]("File not found!");

}
✅ In short:
By using try-catch, Java lets us handle exceptions and continue program execution safely.

3. Explain how print statements and comments can help in debugging. Give examples.

Answer:

🔹 Print Statements in Debugging

Print statements are one of the simplest debugging tools.


They help programmers track program flow and see variable values during execution.

Example:

int total = 0;

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

total += i;

[Link]("After adding " + i + ", total = " + total);

👉 This helps to see where the logic might go wrong.

🔹 How It Helps

 Shows which part of the code is being executed.

 Displays current variable values.

 Helps locate the exact point where the program behaves unexpectedly.

🔹 Comments in Debugging

Comments are used to explain code logic or to disable a part of code temporarily.

Example:

// [Link]("Testing input value");

int result = a + b; // Adding two numbers

🔹 How It Helps

 Makes the code easier to understand.

 Helps in remembering what each part of code does.

 Allows the programmer to turn off certain lines to test specific areas.
✅ In short:
Print statements show what is happening, and comments help us understand why — both are
useful in finding and fixing bugs easily.

4. Explain three types of errors in Java with examples: syntax, runtime, and logic errors.

Answer:

Java programs can contain three main types of errors:

🔹 1. Syntax Error

 Occurs when the rules of Java language are broken.

 These errors are detected by the compiler before running the program.

Example:

[Link]("Hello World") // Missing semicolon

✅ Fix: Add a semicolon ; at the end.

🔹 2. Runtime Error

 Occurs while the program is running.

 Program compiles successfully but crashes during execution.

Example:

int a = 10 / 0; // ArithmeticException

✅ Fix: Check for zero before dividing.

🔹 3. Logic Error

 The program runs but gives the wrong output.

 These errors happen because of a mistake in logic.

Example:

int a = 5, b = 10;

[Link](a - b); // Should be a + b

✅ Fix: Correct the operation.


✅ Summary Table:

Error Type When It Occurs Detected By Example

Syntax Error During compilation Compiler Missing semicolon

Runtime Error During execution JVM Divide by zero

Logic Error After execution Programmer Wrong calculation

5. Describe the role of an Integrated Development Environment (IDE) in debugging Java programs.

Answer:

An Integrated Development Environment (IDE) is a software tool that helps programmers write,
debug, and test Java programs efficiently.
Examples include Eclipse, NetBeans, and IntelliJ IDEA.

🔹 Role of IDE in Debugging:

1. Error Highlighting

o IDE automatically shows syntax errors with red underlines or error messages before
running the program.

2. Breakpoints

o You can set breakpoints to stop the program at specific lines and check variable
values at that point.

3. Step-by-Step Execution

o IDE allows you to execute code line by line (Step Into / Step Over) to see how the
program runs.

4. Variable Watch Window

o Displays the current values of variables while the program runs — helpful to find
wrong data changes.

5. Call Stack View

o Shows the sequence of function calls to identify where an error occurred.

6. Error Console

o Displays error messages, warnings, and exceptions clearly.

7. Integrated Terminal and Tools

o Makes it easy to run and test programs without using an external command prompt.
✅ Example:
In Eclipse, if a NullPointerException occurs, the IDE highlights the exact line number, shows the
variable name, and lets you inspect its value directly.

✅ Conclusion:
An IDE makes debugging faster, easier, and more efficient by providing built-in tools to detect, trace,
and fix errors with minimal effort.

6. What are some effective problem-solving strategies used during debugging? Illustrate with
examples.

Debugging is like solving a puzzle — you have to find where the problem is and fix it.
Here are some effective strategies used during debugging:

🔹 1. Reproduce the Error

Try to run the program again with the same input or steps to make the error happen again.
This helps to understand when and how the error occurs.
👉 Example: If your program crashes when entering a name, enter the same name again to confirm the
problem.

🔹 2. Use Print Statements

Add simple print lines to check variable values and the flow of the program.
👉 Example:

[Link]("Value of x = " + x);

This tells you what’s going wrong inside your code.

🔹 3. Use Debugger Tools

Use breakpoints in your IDE (like Eclipse or IntelliJ).


They let you stop the program at a line, see variable values, and find where the error happens.

🔹 4. Check Your Logic

Sometimes there is no error message, but the output is wrong.


It means your logic is incorrect.
👉 Example: You wrote total = price - tax; instead of total = price + tax;.

🔹 5. Divide and Test (Isolate Problem)


If your program is big, test one part at a time.
👉 Example: If a student marks system gives wrong total, first test addition, then average, then grade
function.

🔹 6. Read the Error Message

Java shows the line number and reason of the error.


👉 Example: NullPointerException at line 5 tells you that something is null at that line.

🔹 7. Explain Code to Yourself (Rubber Duck Method)

Talk through your code line by line — this helps you find what you missed.

✅ In short:
Debugging becomes easy when you test, print, read, and think logically about what your code is
doing.

7. Discuss how debugging can be improved by using external documentation and official Java API
references.

Using official Java documentation (API) and other trusted sources helps you find the correct way to
fix errors.

🔹 1. Understand How Methods Work

Documentation tells how each method works, what it returns, and what errors it may throw.
👉 Example: Java Docs say that substring() throws IndexOutOfBoundsException if index is wrong.

🔹 2. Learn About Exceptions

You can check in the docs when errors like NullPointerException or FileNotFoundException may occur.

🔹 3. See Examples from Official Sources

Java Docs and tutorials give sample programs showing how to use classes and methods correctly.
👉 Example: How to use Scanner or FileReader safely.

🔹 4. Avoid Deprecated Methods

Docs also tell which methods are old or unsafe so you can use the latest ones.
👉 Example: Use [Link]() instead of FileReader.

🔹 5. Use Online Help

Websites like Stack Overflow or Oracle Java Docs help you find common errors and fixes.

✅ In short:
Reading official Java Docs helps you understand the real cause of the bug and fix it properly instead of
guessing.
8. Write a Java code snippet that generates a NullPointerException and explain step-by-step how
you would debug it.

🔹 Code Example:

public class Example {

public static void main(String[] args) {

String name = null; // name has no value

[Link]([Link]()); // This line causes NullPointerException

🔹 Step-by-Step Debugging:

1. Run the Code and See the Error


The output shows:
Exception in thread "main" [Link]
It also shows the line number where it happened.

2. Go to that Line
Check what variable is null.
Here, name is null.

3. Add Print Statements


Add a line before it:

4. [Link]("Name = " + name);

It will print Name = null, confirming the problem.

5. Find Why It’s Null


Maybe you forgot to give it a value.
Fix it by assigning:

String name = "Uzma";

6. Run Again
Now it prints the length successfully.

7. Better Solution (Avoid NPE)


Always check for null before using variables:

if (name != null) {

[Link]([Link]());

} else {

[Link]("Name is not given");


}

✅ In short:
You find a NullPointerException by checking which object is null and fixing it by assigning or checking
before use.

9. How can structured debugging with systematic questioning help in locating bugs? Explain with a
scenario.

Structured debugging means asking smart questions step by step instead of guessing.
It helps to find bugs faster and understand the real reason.

🔹 Example Scenario:

A shopping app shows the wrong total price.

Let’s ask questions step-by-step 👇

1. What is wrong?
→ The total price is showing less than expected.

2. When does it happen?


→ Only when discounts are applied.

3. Where in the code?


→ In the calculateTotal() method.

4. Why is it happening?
→ Maybe the discount is subtracted twice.

5. How to check?
→ Add print statements:

6. [Link]("Discount = " + discount);

7. [Link]("Final total = " + total);

8. Find the cause:


Output shows discount applied two times — that’s the bug.

9. Fix the issue:


Remove the extra discount line and test again.

🔹 How This Helps:

 You find the cause logically, not randomly.

 You save time because you follow a clear path.

 You understand your program better for future errors.


✅ In short:
Structured debugging = ask questions, test step-by-step, and fix logically.
It’s like being a detective — you find clues until you reach the real reason for the bug.
[Link] and Objects in Java
Short: What is the difference between a class and an object?

Medium: Explain how memory is allocated to objects in Java. Include stack vs heap in your explanation.

Long: Define a class in Java. Create an example to show object creation and memory referencing using variables.

[Link] and Initialization Blocks Short: What is a constructor in Java?

Medium: Differentiate between default and parameterized constructors with examples.

Long: Explain the purpose of instance initializer blocks. Illustrate with a program using multiple constructors and a common initialization block.

[Link] Modifiers in Java

Short: List the four access modifiers in Java.

Medium: Explain the difference between protected and default access modifiers.

Long: Describe how access modifiers control visibility across packages and subclasses with a Java program to demonstrate each case.

[Link] Classes and Nested Classes Short: What is a static nested class?

Medium: Explain method-local and anonymous inner classes with syntax examples.

Long: Describe all types of nested classes in Java. When and why would you use each?

[Link] Classes and Interfaces


Short: Can we instantiate an abstract class?

Medium: List two key differences between abstract classes and interfaces.

Long: Compare abstract classes and interfaces in Java. Include real-world scenarios and sample code to demonstrate their differences and usage.

[Link] Definition and Overloading Short: What is method overloading?

Medium: Explain the rules of method overloading with code examples.

Long: Create a class with multiple overloaded methods. Explain how Java resolves which method to call during runtime.

[Link] Members in Java

Short: What is a static method?

Medium: What is a static block? When is it executed?

Long: Explain all types of static members in Java with suitable examples showing their behavior and usage.

[Link] this Keyword in Java


Short: What does this refer to in Java?

Medium: How can this() be used to call another constructor?

Long: Describe the multiple uses of the this keyword in Java with examples showing variable differentiation, constructor chaining, and object passing.

[Link] Management and Garbage Collection Short: What is garbage collection in Java?
Medium: Explain the object lifecycle in Java with reference to garbage collection.

Long: How does Java manage memory? Describe the roles of the heap, stack, and garbage collector. Provide a sample program showing dereferencing and
GC request.

[Link] in Java
Short: Why do we use generics in Java?

Medium: Write a generic class that works with both String and Integer types.

Long: What are generics in Java? How do they enhance type safety and reusability? Explain with a detailed example of a generic class and method.

[Link] Abstract Classes and Interfaces


Short: Can a class implement multiple interfaces in Java?

Medium: Mention two advantages of using interfaces over abstract classes.

Long: Provide a feature-wise comparison between abstract classes and interfaces. Explain with a real-world example where one is more suitable than the
other.

🌼 1. Classes and Objects in Java

Short:
Q: What is the difference between a class and an object?
A:
A class is a blueprint or template that defines how an object will look and behave.
An object is a real instance of that class which stores data and performs actions.

👉 Example:
Class = plan of a house 🏠
Object = actual built house based on that plan.

Medium:

Q: Explain how memory is allocated to objects in Java. Include stack vs heap in your explanation.
A:
In Java, when we create an object using the new keyword, memory is allocated in the heap area.

 Heap memory:
Stores all objects and instance variables.
Example:

 Student s1 = new Student();

The object s1 is stored in the heap.

 Stack memory:
Stores method calls and reference variables.
In the above example, the variable s1 (reference) is stored in the stack and points to the object in the heap.

So, the stack holds references, while the heap holds actual objects.
Long:

Q: Define a class in Java. Create an example to show object creation and memory referencing using variables.
A:
A class in Java is a user-defined data type that contains data members (variables) and methods (functions). It represents the blueprint of an object.
Objects are created from classes using the new keyword.

Syntax:

class ClassName {

// variables

// methods

Example Program:

class Student {

String name;

int age;

void displayInfo() {
[Link]("Name: " + name + ", Age: " + age);

public class Main {

public static void main(String[] args) {

// Creating objects

Student s1 = new Student();

Student s2 = new Student();

// Assigning values

[Link] = "Uzma";

[Link] = 22;

[Link] = "Fatima";

[Link] = 20;
// Display info

[Link]();

[Link]();

Explanation:

 Student is a class.

 s1 and s2 are objects created in heap memory.

 The variable s1 (reference) is stored in stack memory and points to its data in heap memory.
This is how Java handles memory for class objects.

🌼 2. Constructors and Initialization Blocks

Short:

Q: What is a constructor in Java?


A:
A constructor is a special method that is automatically called when an object is created.
It initializes object values.
It has the same name as the class and no return type.

Medium:

Q: Differentiate between default and parameterized constructors with examples.

Points Default Constructor Parameterized Constructor

Meaning No arguments. Takes arguments.

Created by Java (if not written). Programmer.

Use Sets default values. Sets given values.

Syntax Student(){} Student(String name){}

Object Example Student s1 = new Student(); Student s2 = new Student("Uzma");

Output Default Constructor Name: Uzma

In short:
Default constructor → No input.
Parameterized constructor → Takes input to initialize values.

Long:
Q: Explain the purpose of instance initializer blocks. Illustrate with a program using multiple constructors and a common initialization block.
A:
An instance initializer block (IIB) is a block of code inside {} that runs every time an object is created, before the constructor.
It is used to write common code for all constructors.

Example:

class Student {

String name;

int age; // Instance initializer block

[Link]("Student object is being created...");

// Default constructor

Student() {

name = "Unknown";

age = 0;

[Link]("Default constructor called");


}

// Parameterized constructor

Student(String n, int a) {

name = n;

age = a;

[Link]("Parameterized constructor called");

void display() {

[Link]("Name: " + name + ", Age: " + age);

public class Main {


public static void main(String[] args) {

Student s1 = new Student();

Student s2 = new Student("Uzma", 22);

Output:

Student object is being created...

Default constructor called

Student object is being created...

Parameterized constructor called

Explanation:

 The block runs before every constructor.

 It avoids writing repeated setup code in multiple constructors.

🌼 3. Access Modifiers in Java


Short:

Q: List the four access modifiers in Java.


A:

1. public – Accessible everywhere.

2. private – Accessible only within the same class.

3. protected – Accessible within the same package and subclasses.

4. default (no modifier) – Accessible only within the same package.

Medium:

Q: Explain the difference between protected and default access modifiers.


A:

Points Protected Default

Meaning Used in same package & subclasses of other packages. Used only in same package.

Keyword protected No keyword

Other Package (Subclass) Accessible ✅ Not accessible ❌

Example protected int marks; int marks;


Example:

protected int marks; // accessible in subclasses

int age; // default: only in same package

Long:

Q: Describe how access modifiers control visibility across packages and subclasses with a Java program to demonstrate each case.
🌟 Answer:

In Java, access modifiers are keywords that control how accessible (or visible) classes, methods, and variables are to other parts of a program — especially
across different packages and subclasses.

There are four main access modifiers in Java:

1. public

2. protected

3. default (no modifier)

4. private

🧩 1. public

 Accessible from anywhere — within the same class, same package, subclass, or any other package.

 Used when you want your method or variable to be available for everyone.
✅ Example:

public class A {

public void show() {

[Link]("Public method: Accessible from anywhere!");

🧩 2. protected

 Accessible within the same package and also in subclasses (even if they are in different packages).

 Used when you want to allow limited access to subclasses.

✅ Example:

public class A {

protected void display() {

[Link]("Protected method: Accessible in same package and subclasses.");

}
}

🧩 3. default (no modifier)

 When no access modifier is written, it’s called default.

 Accessible only within the same package — not outside the package or in subclasses of another package.

✅ Example:

class A {

void msg() {

[Link]("Default method: Accessible only in same package.");

🧩 4. private

 Accessible only within the same class.

 Not accessible in other classes, packages, or subclasses.

 Best for hiding internal details (called encapsulation).


✅ Example:

public class A {

private void secret() {

[Link]("Private method: Accessible only in same class.");

💻 Java Program Demonstrating All Access Modifiers

📦 Package 1: pack1

// File: pack1/[Link]

package pack1;

public class A {

public int publicVar = 10;

protected int protectedVar = 20;

int defaultVar = 30;


private int privateVar = 40;

public void publicMethod() {

[Link]("Public Method");

protected void protectedMethod() {

[Link]("Protected Method");

void defaultMethod() {

[Link]("Default Method");

private void privateMethod() {

[Link]("Private Method");

}
public void showAll() {

// Accessible inside same class

[Link](publicVar);

[Link](protectedVar);

[Link](defaultVar);

[Link](privateVar);

📦 Package 2: pack2

(A) Subclass in another package

// File: pack2/[Link]

package pack2;

import pack1.A;

public class B extends A {


public void show() {

// Accessing variables from class A

[Link](publicVar); // ✅ Accessible

[Link](protectedVar); // ✅ Accessible (because subclass)

// [Link](defaultVar); // ❌ Not accessible (different package)

// [Link](privateVar); // ❌ Not accessible (private)

publicMethod(); // ✅ Accessible

protectedMethod(); // ✅ Accessible (because subclass)

// defaultMethod(); // ❌ Not accessible

// privateMethod(); // ❌ Not accessible

(B) Non-subclass in another package


// File: pack2/[Link]

package pack2;

import pack1.A;

public class C {

public void test() {

A obj = new A();

[Link]([Link]); // ✅ Accessible

// [Link]([Link]); // ❌ Not accessible (no inheritance)

// [Link]([Link]); // ❌ Not accessible

// [Link]([Link]); // ❌ Not accessible

[Link](); // ✅ Accessible

// [Link](); // ❌ Not accessible (no inheritance)

// [Link](); // ❌ Not accessible


// [Link](); // ❌ Not accessible

🧠 Summary Table:

Modifier Same Class Same Package Subclass (diff package) Other Package

public ✅ Yes ✅ Yes ✅ Yes ✅ Yes

protected ✅ Yes ✅ Yes ✅ Yes ❌ No (unless subclass)

default ✅ Yes ✅ Yes ❌ No ❌ No

private ✅ Yes ❌ No ❌ No ❌ No

💬 In Simple Words:

 public → open to everyone

 protected → open to family (same package + subclasses)

 default → open only to local people (same package)

 private → secret (only inside the same class)


Access modifiers control who can see or use variables/methods in your program.

Example:

// File: pack1/[Link]

package pack1;

public class Student {

public String name = "Uzma";

protected int marks = 90;

int age = 21; // default

private String id = "ST123";

public void show() {

[Link](name + " " + marks + " " + age + " " + id);

}
// File: pack2/[Link]

package pack2;

import [Link];

public class MainClass extends Student {

public static void main(String[] args) {

MainClass obj = new MainClass();

[Link]([Link]); // ✅ public - accessible

[Link]([Link]); // ✅ protected - accessible via subclass

// [Link]([Link]); // ❌ default - not accessible

// [Link]([Link]); // ❌ private - not accessible

Explanation:

 public: accessible everywhere


 protected: accessible in subclass of another package

 default: only inside same package

 private: only inside same class

🌼 4. Inner Classes and Nested Classes

Short:

Q: What is a static nested class?


A:
A static nested class is a class defined inside another class using the static keyword.
It can be accessed without creating an object of the outer class.

👉 Example:

class Outer {

static class Inner {

void show() {

[Link]("Static Nested Class");

}
}

class Test {

public static void main(String[] args) {

[Link] obj = new [Link]();

[Link]();

Medium:

Q: Explain method-local and anonymous inner classes with syntax examples.


A:
1. Method-local Inner Class:
A class created inside a method. It can only be used inside that method.

class Outer {

void display() {

class Inner {
void msg() {

[Link]("Hello from Method-local Inner Class");

Inner obj = new Inner();

[Link]();

2. Anonymous Inner Class:


A class without a name, usually created for one-time use like event handling.

abstract class Animal {

abstract void sound();

public class Test {

public static void main(String[] args) {


Animal obj = new Animal() {

void sound() {

[Link]("Bark!");

};

[Link]();

Long:

Q: Describe all types of nested classes in Java. When and why would you use each?
A:
There are four types of nested classes in Java:

1. Static Nested Class:

o Defined with static keyword.

o Can access only static members of outer class.

o Used when inner class does not depend on outer class object.
2. Non-static Inner Class:

o Requires an object of the outer class to access it.

o Used when inner class needs outer class data.

3. Method-local Inner Class:

o Created inside a method.

o Used for limited use only inside that method.

4. Anonymous Inner Class:

o Has no name.

o Used for quick implementation of interface or abstract class.

Example:

class Outer {

int data = 50;

static class StaticInner {

void show() { [Link]("Static Inner Class"); }


}

class NonStaticInner {

void display() { [Link]("Data: " + data); }

void method() {

class MethodInner {

void msg() { [Link]("Inside method inner class"); }

MethodInner obj = new MethodInner();

[Link]();

}
public class Main {

public static void main(String[] args) {

[Link] s = new [Link]();

[Link]();

Outer outer = new Outer();

[Link] n = [Link] NonStaticInner();

[Link]();

[Link]();

🌼 5. Abstract Classes and Interfaces

Short:
Q: Can we instantiate an abstract class?
A:
No ❌, we cannot create an object of an abstract class directly because it is incomplete.
It’s meant to be extended by other classes.

Medium:

Q: List two key differences between abstract classes and interfaces.

Abstract Class Interface

Can have both abstract and normal methods. All methods are abstract (until Java 8).

Used for sharing common behavior. Used for enforcing common rules.

Can have constructors. Cannot have constructors.

Long:

Q: Compare abstract classes and interfaces in Java. Include real-world scenarios and sample code to demonstrate their differences and usage.
A:
Both abstract classes and interfaces are used for abstraction — hiding details and showing only essential information.

🔹 Abstract Class:

 Contains abstract (unimplemented) and normal (implemented) methods.

 Used when classes are closely related.


 Supports inheritance (extends).

Example:

abstract class Animal {

abstract void sound();

void sleep() {

[Link]("Sleeping...");

class Dog extends Animal {

void sound() {

[Link]("Bark!");

}
public class Main {

public static void main(String[] args) {

Animal a = new Dog();

[Link]();

[Link]();

🔹 Interface:

 Contains only method declarations (and constants).

 Used when different classes share common behavior but are not related.

 Supports multiple inheritance using implements.

Example:

interface Vehicle {

void start();

}
class Car implements Vehicle {

public void start() {

[Link]("Car starts with key");

class Bike implements Vehicle {

public void start() {

[Link]("Bike starts with button");

public class Test {

public static void main(String[] args) {

Vehicle v1 = new Car();


Vehicle v2 = new Bike();

[Link]();

[Link]();

🔹 Real-World Comparison:

 Abstract Class: “Animal” base for Dog, Cat — all are animals.

 Interface: “Drivable” — Car, Bike, Truck — all can drive but are different types.

✅ In short:
Use abstract class when classes share structure and behavior.
Use interface when unrelated classes need to follow the same rule.

6. Method Definition and Overloading

Short:

What is method overloading?


Method overloading means defining multiple methods with the same name but with different parameters (number or type).
It allows one method name to perform different tasks based on input types.
It is an example of compile-time polymorphism.
Medium:

Rules of method overloading:

1. Same method name.

2. Different parameter type or count.

3. Return type doesn’t affect overloading.

4. Performed at compile time.

Code Example:

class Calculator {

void add(int a, int b) {

[Link](a + b);

void add(double a, double b) {

[Link](a + b);

void add(int a, int b, int c) {

[Link](a + b + c);

}
Long:

Explanation:
When a class contains several methods with the same name but different parameters, Java decides which one to call based on argument type and number.
This process is called compile-time binding.

Code Example:

class Display {

void show(int a) {

[Link]("Integer: " + a);

void show(String s) {

[Link]("String: " + s);

void show(double d) {

[Link]("Double: " + d);

public static void main(String[] args) {

Display d = new Display();

[Link](10);
[Link]("Hello");

[Link](3.14);

6. Static Members in Java

Short:

What is a static method?


A static method belongs to the class, not to an object.
You can call it directly using the class name, without creating an object.

Code Example:

class Demo {

static void greet() {

[Link]("Hello!");

public static void main(String[] args) {

[Link]();

Medium:
What is a static block? When is it executed?
A static block is used to initialize static data.
It is executed only once, when the class is first loaded — before the main method runs.

Code Example:

class Test {

static {

[Link]("Static block executed!");

public static void main(String[] args) {

[Link]("Main method executed!");

Long:

All types of static members:

1. Static variable – Shared among all objects.

2. Static method – Can be called without creating an object.

3. Static block – Runs automatically before any method.

4. Static nested class – Class defined inside another class as static.

Code Example:

class Example {
static int count;

int id;

static {

[Link]("Static block runs first!");

count = 0;

Example(int id) {

[Link] = id;

count++;

static void showCount() {

[Link]("Total objects: " + count);

public static void main(String[] args) {

Example e1 = new Example(1);

Example e2 = new Example(2);

[Link]();
}

7. The this Keyword in Java

Short:

What does this refer to?


this refers to the current object of the class — the object whose method or constructor is being executed.

Medium:

Using this() to call another constructor:


We use this() to call another constructor in the same class.
It must be the first statement in the constructor.

Code Example:

class Student {

String name;

int age;

Student() {

this("Unknown", 18);

Student(String name, int age) {


[Link] = name;

[Link] = age;

Long:

Uses of this keyword:

1. Refers to current object’s variables.

2. Calls another constructor (constructor chaining).

3. Passes current object as argument.

Code Example:

class Demo {

int a;

Demo(int a) {

this.a = a;

Demo() {

this(100);

}
void display() {

[Link]("Value of a: " + a);

void show(Demo obj) {

[Link]("Object passed: " + obj.a);

void test() {

show(this);

public static void main(String[] args) {

Demo d = new Demo();

[Link]();

[Link]();

8. Memory Management and Garbage Collection


Short:

What is garbage collection?


Garbage collection is Java’s process of automatically removing unused objects from memory to make space and avoid memory leaks.

Medium:

Object lifecycle with garbage collection:

1. Object is created with new.

2. It remains in memory while referenced.

3. When reference is removed (null), it becomes eligible for garbage collection.

Code Example:

Student s1 = new Student();

s1 = null; // eligible for GC

Long:

How Java manages memory:

Memory Area Description

Stack Holds method calls and local variables

Heap Stores objects created with new

Method Area Stores static data and class info

Garbage Collector automatically frees unused memory.

Code Example:
class Test {

public void finalize() {

[Link]("Object destroyed!");

public static void main(String[] args) {

Test t1 = new Test();

t1 = null;

[Link]();

9. Generics in Java

Short:

Why use generics?


To make code type-safe and reusable, ensuring data types are checked during compile time.

Medium:

Generic class for String and Integer:

Code Example:

class Box<T> {
T value;

void set(T value) {

[Link] = value;

T get() {

return value;

public class Main {

public static void main(String[] args) {

Box<String> strBox = new Box<>();

[Link]("Hello");

[Link]([Link]());

Box<Integer> intBox = new Box<>();

[Link](123);

[Link]([Link]());

}
}

Long:

Explanation:
Generics allow writing one class or method that works with any data type.
They prevent runtime errors and allow compile-time checking.

Code Example:

class Pair<K, V> {

K key;

V value;

Pair(K key, V value) {

[Link] = key;

[Link] = value;

void show() {

[Link]("Key: " + key + " Value: " + value);

public class Main {


public static void main(String[] args) {

Pair<Integer, String> p1 = new Pair<>(1, "One");

Pair<String, Double> p2 = new Pair<>("Price", 99.99);

[Link]();

[Link]();

10. Comparing Abstract Classes and Interfaces

Short:

Can a class implement multiple interfaces?


Yes ✅, a class can implement multiple interfaces, but it can extend only one abstract class.

Medium:

Two advantages of interfaces over abstract classes:

1. A class can implement multiple interfaces.

2. Interfaces provide full abstraction (only method declarations).

Long:

Comparison Table:
Feature Abstract Class Interface

Methods Abstract + normal Only abstract (till Java 7)

Variables Instance + static public static final only

Inheritance Single Multiple

Access Any All public

Purpose Shared behavior Common contract

Use abstract class for related objects with shared code.


Use interface when unrelated classes must follow same rules.

Code Example:

abstract class Animal {

abstract void sound();

interface Flyable {

void fly();

class Bird extends Animal implements Flyable {

void sound() { [Link]("Chirp!"); }

public void fly() { [Link]("Flying high!"); }

}
Short Question
1. Define bytecode in Java.
2. List any four Java keywords.
3. What is the purpose of the javac command?
4. Give two valid and two invalid Java identifiers.
5. Name any two Java primitive data types and mention their size.
6. Write a Java statement using a boolean literal.
7. What does JVM stand for and what is its role?
8. Mention any two types of Java literals.
9. State the difference between = and == operators.
10. What is the use of comments in Java?

Long Question
1. Explain the Java Development Process with proper diagram and steps from writing
code to execution.
2. Describe the structure of a Java source file. Illustrate with an example including
package, import, and class declaration.
3. Differentiate between JDK, JRE, and JVM. Provide their components and roles in Java
development.
4. Discuss the rules and naming conventions for Identifiers in Java. Provide examples of
valid and invalid identifiers.
5. Explain the various types of Literals in Java with suitable examples for each.
6. Compare Integer and Floating Point data types in Java. Include their ranges and
default types.
7. Describe the types of comments supported by Java and explain their significance
with examples.
8. Explain Java's 8 Primitive Data Types. Provide size, default values, and an example of
each.
9. Write a detailed note on Arithmetic, Relational, and Logical Operators in Java with
examples.
10. What is Operator Precedence? How does it affect the evaluation of expressions? Give
examples.

Short Answer:
1. Define bytecode in Java.

Bytecode is a set of instructions that Java compiler creates after compiling a .java file.
It is stored in a .class file and is not machine-specific, meaning it can run on any system that has a
JVM (Java Virtual Machine).

2. List any four Java keywords.


Keywords are reserved words that have a special meaning in Java.
Examples: class, public, static, return
(They cannot be used as variable names.)

3. What is the purpose of the javac command?

The javac command is used to compile a Java source file.


It converts the human-readable code (.java) into bytecode (.class) which can then be run by the JVM.

4. Give two valid and two invalid Java identifiers.

Identifiers are names given to variables, classes, or methods.


✅ Valid: studentName, _totalMarks
❌ Invalid: 2name (cannot start with a number), class (keyword cannot be used)

5. Name any two Java primitive data types and mention their size.

1. int – used to store whole numbers; size is 4 bytes.

2. boolean – used to store true or false; size is 1 bit (depends on JVM).

6. Write a Java statement using a boolean literal.

A boolean literal represents true or false.


Example:

boolean isJavaEasy = true;

This statement stores the value true in the variable isJavaEasy.

7. What does JVM stand for and what is its role?

JVM stands for Java Virtual Machine.


It is responsible for executing the bytecode created by the Java compiler.
JVM converts bytecode into machine code that your computer can understand.
It makes Java platform-independent.

8. Mention any two types of Java literals.

Literals are fixed values used in a program.


Examples:

1. Integer literal – represents numbers, e.g. 50

2. String literal – represents text, e.g. "Hello Java"

9. State the difference between = and == operators.


 = is the assignment operator — it stores a value in a variable.
Example: int a = 10;

 == is the comparison operator — it checks if two values are equal.


Example: a == 10

10. What is the use of comments in Java?

Comments are notes written inside the code to explain its purpose.
They help others understand the program easily and are ignored by the compiler.
Example:

// This is a single-line comment

Long Answers:
1. Explain the Java Development Process with proper diagram and steps from writing code to
execution.

Explanation:

The Java development process is a series of steps that converts your Java source code into an
executable program that runs on any platform.

Steps:

1. Writing the Code:


You write your program using a text editor or IDE (like Eclipse or IntelliJ).
The file is saved with a .java extension.
👉 Example: [Link]

2. Compilation:
The Java compiler (javac) converts the human-readable source code into bytecode, stored in
a .class file.
👉 Example: javac [Link] → creates [Link]

3. Loading the Class:


The ClassLoader loads the .class file into the JVM’s memory.

4. Bytecode Verification:
The Bytecode Verifier checks the code for security and ensures there are no illegal code
instructions.

5. Execution:
The JVM Interpreter or JIT (Just-In-Time) Compiler converts bytecode into machine code
and executes it on the computer.

Diagram:
Source Code (.java)

↓ [Compiled by javac]

Bytecode (.class)

↓ [Loaded by ClassLoader]

Bytecode Verifier

JVM Execution (Interpreter / JIT)

Program Output

Real-Life Example:

Think of writing a Java program like cooking a recipe:

 You write the recipe (Java code).

 You prepare the ingredients (compile it).

 The chef (JVM) reads your recipe and cooks (executes) it into a ready meal (output).

Code Example:

class Hello {

public static void main(String[] args) {

[Link]("Hello, World!");

Output:

Hello, World!

2. Describe the structure of a Java source file. Illustrate with an example including package, import,
and class declaration.

Explanation:

A Java source file defines how a program is organized. It usually includes these sections (in order):

1. Package Declaration (Optional):


Defines the package name to group related classes.
package myprogram;
2. Import Statements (Optional):
Used to include built-in or user-defined classes from other packages.
import [Link];

3. Class Declaration (Mandatory):


Defines the main class of the program.
public class MyClass { ... }

4. Main Method:
The entry point of the program.
public static void main(String[] args) { ... }

Code Example:

package myprogram; // 1. Package

import [Link]; // 2. Import

public class StudentInfo { // 3. Class declaration

public static void main(String[] args) {

Scanner sc = new Scanner([Link]); // Using imported class

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

String name = [Link]();

[Link]("Welcome, " + name + "!");

Output Example:

Enter your name: Uzma

Welcome, Uzma!

Real-Life Example:

Think of a Java source file like a book:

 Package → the bookshelf category (Science, History, etc.)

 Import → using pages from other books

 Class → the actual book you’re reading

 Main method → the starting page of your story


3. Differentiate between JDK, JRE, and JVM. Provide their components and roles in Java
development.

Explanation:

Component Full Form Role Contains

Java Development Used by developers to write, JRE + Compiler (javac) +


JDK
Kit compile, and run Java programs Development tools

Java Runtime
JRE Used to run Java programs JVM + Libraries
Environment

Java Virtual Executes bytecode and makes Java


JVM Interpreter + JIT Compiler
Machine platform-independent

Diagram:

JDK

├── JRE

│ ├── JVM

│ └── Class Libraries

└── Development Tools (javac, jar, javadoc)

Real-Life Example:

 JDK → Like a chef who has all cooking tools (can cook and test).

 JRE → Like a restaurant kitchen where food is only served (only runs programs).

 JVM → Like the cook who actually prepares the dish (executes the code).

Example Workflow:

1. You write code using JDK tools.

2. You run it using JRE.

3. The code is executed by the JVM.

4. Discuss the rules and naming conventions for Identifiers in Java. Provide examples of valid and
invalid identifiers.

Explanation:

Identifiers are names used for variables, classes, methods, etc.


Rules for Identifiers:

1. Must begin with a letter, underscore (_), or dollar sign ($).

2. Cannot start with a number.

3. Cannot use Java keywords like class, if, public.

4. Cannot contain spaces or special characters like @, #, %.

5. Java is case-sensitive (name and Name are different).

Naming Conventions:

 Class names: Start with Capital (e.g., StudentInfo)

 Variable and method names: Start with lowercase (e.g., studentName)

 Constants: All capital letters (e.g., MAX_VALUE)

Examples:

Valid Identifiers Invalid Identifiers Reason

studentName 2student Cannot start with a number

_marks my-name Hyphen not allowed

totalAmount class Keyword

$salary student name Space not allowed

Real-Life Example:

If your Java program is a classroom, then identifiers are the student names — each must be unique
and follow certain rules (can’t start with a number, can’t have symbols, etc.).

5. Explain the various types of Literals in Java with suitable examples for each.

Explanation:

Literals are fixed values that appear directly in your code.


They represent data like numbers, characters, or strings that do not change.

Types of Literals in Java:

1. Integer Literal

Used for whole numbers.


Example:
int age = 25;

🧠 Real-life example: Your age, like 25, is a fixed whole number.

2. Floating-Point Literal

Used for decimal numbers.


Example:

double price = 99.99;

🧠 Real-life example: The price of a book can be 99.99.

3. Character Literal

Used to store a single character inside single quotes.


Example:

char grade = 'A';

🧠 Real-life example: Your exam grade like 'A' or 'B'.

4. String Literal

Used for a group of characters (text).


Example:

String name = "Uzma";

🧠 Real-life example: Your name or a message.

5. Boolean Literal

Represents truth values — either true or false.


Example:

boolean isStudent = true;

🧠 Real-life example: Whether you are a student (true/false).

6. Null Literal

Represents no value.
Example:

String middleName = null;

🧠 Real-life example: If you don’t have a middle name, its value can be null.
Summary Table:

Literal Type Example Description

Integer int a = 10; Whole number

Floating-point float b = 3.14f; Decimal number

Character char c = 'X'; Single character

String String s = "Hello"; Text

Boolean boolean flag = true; True/False value

Null String str = null; No value

6. Compare Integer and Floating Point Data Types in Java

Explanation:

Java has two main numeric data types:

 Integer types → store whole numbers (no decimal).

 Floating-point types → store decimal or fractional numbers.

Comparison Table:

Feature Integer Data Type Floating-Point Data Type

Definition Used to store whole numbers Used to store numbers with decimals

Examples byte, short, int, long float, double

Default Type int double

Size Range From 1 byte (byte) to 8 bytes (long) float = 4 bytes, double = 8 bytes

Range Example int: -2,147,483,648 to 2,147,483,647 double: ±1.7E308 (approx)

Example Values 5, 1000, -45 5.75, -0.89, 3.14159

Use Case Counting people, items, or things Measuring weight, height, or distance

Real-Life Example:

 Integer → Number of students in a class: 25

 Floating-point → Average student marks: 89.56

Code Example:
int students = 25; // Integer

double averageMarks = 89.56; // Floating-point

[Link]("Students: " + students);

[Link]("Average Marks: " + averageMarks);

Output:

Students: 25

Average Marks: 89.56

7. Describe the Types of Comments Supported by Java and Explain Their Significance with
Examples

Explanation:

Comments in Java are notes or explanations added to the code.


They help other programmers understand your program — the compiler ignores them.

Types of Comments in Java:

1. Single-line Comment

Used for short explanations.


Starts with // — everything after it on that line is ignored.

// This line prints Hello

[Link]("Hello");

2. Multi-line Comment

Used when you need to write long notes or disable multiple lines of code.
Starts with /* and ends with */.

/* This is a multi-line comment.

It can span multiple lines.

*/

[Link]("Uzma learning Java");

3. Documentation Comment

Used to create HTML documentation for classes and methods.


Starts with /** and ends with */.
/**

* This class represents a Student.

* @author Uzma

* @version 1.0

*/

class Student {

// Class code

Real-Life Example:

Think of comments as sticky notes in your notebook — they help you remember what each page
means without affecting your answers!

8. Explain Java’s 8 Primitive Data Types with Size, Default Value, and Example

Explanation:

Primitive data types are the basic building blocks of data in Java.
They store simple values — not objects.

Table of 8 Primitive Data Types:

Default
Type Size Example Description
Value

byte 1 byte 0 byte age = 20; Small integers (range: -128 to 127)

short 2 bytes 0 short marks = 400; Medium integers

int 4 bytes 0 int population = 100000; General-purpose integer

long phone =
long 8 bytes 0L Large integers
9876543210L;

Decimal numbers with lower


float 4 bytes 0.0f float price = 45.6f;
precision

Decimal numbers with high


double 8 bytes 0.0d double weight = 65.45;
precision

char 2 bytes '\u0000' char grade = 'A'; Single character

boolean 1 bit false boolean isPass = true; True or False values


Default
Type Size Example Description
Value

(logical)

Code Example:

class DataTypes {

public static void main(String[] args) {

int age = 22;

double weight = 45.6;

char grade = 'A';

boolean isPass = true;

[Link]("Age: " + age);

[Link]("Weight: " + weight);

[Link]("Grade: " + grade);

[Link]("Passed: " + isPass);

Output:

Age: 22

Weight: 45.6

Grade: A

Passed: true

Real-Life Example:

 byte → age of a child

 int → total population

 double → temperature

 boolean → is light ON/OFF

9. Write a Detailed Note on Arithmetic, Relational, and Logical Operators in Java with Examples
Explanation:

Operators are special symbols that perform operations on variables and values.

1. Arithmetic Operators

Used for mathematical calculations.

Operator Meaning Example Result

+ Addition 10 + 5 15

- Subtraction 10 - 5 5

* Multiplication 10 * 5 50

/ Division 10 / 5 2

% Modulus (Remainder) 10 % 3 1

Code Example:

int a = 10, b = 3;

[Link](a + b); // 13

[Link](a % b); // 1

2. Relational Operators

Used to compare two values.


Always return true or false.

Operator Meaning Example Result

== Equal to 5 == 5 true

!= Not equal to 5 != 3 true

> Greater than 8>3 true

< Less than 2<8 true

>= Greater than or equal to 5 >= 5 true

<= Less than or equal to 3 <= 4 true

Code Example:

int x = 10, y = 20;

[Link](x < y); // true

[Link](x == y); // false


3. Logical Operators

Used to combine multiple conditions.

Operator Meaning Example Result

&& Logical AND (x > 5 && y < 30) true

` ` Logical OR

! Logical NOT !(x > 5) false

Code Example:

boolean a = true, b = false;

[Link](a && b); // false

[Link](a || b); // true

[Link](!a); // false

Real-Life Example:

 Arithmetic → total price = quantity × price

 Relational → checking if marks > 35

 Logical → checking if student passed and attended class

10. What is Operator Precedence? How Does It Affect the Evaluation of Expressions? Give
Examples

Explanation:

Operator precedence means the priority in which operators are executed in an expression.

If two or more operators appear in one statement, Java decides which one to execute first based on
precedence rules.

Example Table of Precedence (from high to low):

Precedence Level Operator Description

1 () Parentheses (highest priority)

2 ++, -- Increment / Decrement

3 *, /, % Multiplication, Division, Modulus

4 +, - Addition, Subtraction
Precedence Level Operator Description

5 <, >, <=, >= Relational

6 ==, != Equality

7 && Logical AND

8 `

9 = Assignment (lowest priority)

Code Example 1:

int result = 10 + 5 * 2;

[Link](result);

Explanation:
* has higher precedence than +.
→ 5 * 2 = 10, then 10 + 10 = 20
Output: 20

Code Example 2 (Using Parentheses):

int result = (10 + 5) * 2;

[Link](result);

Explanation:
Parentheses change order → 10 + 5 = 15, then 15 * 2 = 30
Output: 30

Real-Life Example:

Think of it like BODMAS rule in maths.


Multiplication happens before addition unless you use brackets.
SSCA2022 – Core Java
Question Bank

Module-5
Short Questions
1. Define inheritance in Object-Oriented Programming.
2. List any two bene its of using inheritance in Java.
3. Which keyword is used to inherit a class in Java?
4. State the difference between single inheritance and multilevel inheritance.
5. Can constructors be inherited in Java?
6. What is the role of the super keyword in inheritance?
7. Define polymorphism in the context of inheritance.
8. Give an example of data member inheritance.
9. Mention one difference between method overloading and method overriding.
10. What happens if a subclass defies a method with the same signature as its superclass?
Long Questions
1. Explain with an example the use and bene its of inheritance in Java.
2. Describe different types of inheritance in Java with suitable diagrams.
3. Write a Java program to demonstrate single inheritance and explain its output.
4. Explain how data members and methods are inherited from a superclass to a subclass with an
example.
5. Illustrate with code the role of constructors in inheritance.
6. Demonstrate method overriding in Java and explain how the super keyword can be used to call the
superclass method.
7. Write a Java program to show runtime polymorphism using inheritance.
8. Differentiate between compile-time polymorphism and runtime polymorphism with examples.
9. Explain type compatibility and type casting in inheritance with a program.
10. Design a program using a base class Person and derived classes Student and Employee to
demonstrate polymorphism and method overriding.

Short Answers:
1. Define inheritance in Object-Oriented Programming.

Inheritance is a concept where one class (child or subclass) gets the properties and methods of
another class (parent or superclass).
It helps in code reuse and reduces duplication.

2. List any two benefits of using inheritance in Java.

1. Code Reusability: You can use existing class features in a new class.

2. Easy Maintenance: Common features can be updated in one place (superclass).


3. Which keyword is used to inherit a class in Java?

The keyword extends is used to inherit a class in Java.


Example:

class Child extends Parent { }

4. State the difference between single inheritance and multilevel inheritance.

Type Description Example

Single Inheritance One subclass inherits from one superclass. A→B

Multilevel Inheritance A class inherits from another subclass forming a chain. A → B → C

5. Can constructors be inherited in Java?

No, constructors are not inherited.


But the child class can call the parent’s constructor using the super() keyword.

6. What is the role of the super keyword in inheritance?

super keyword is used to:

1. Call parent class constructor, and

2. Access parent class variables or methods that are hidden by subclass.

Example:

[Link](); // calls parent’s display() method

7. Define polymorphism in the context of inheritance.

Polymorphism means many forms — it allows the same method name to behave differently based
on the object calling it.
Example: show() method works differently in parent and child classes.

8. Give an example of data member inheritance.

When a subclass automatically gets the variables (data members) of its parent class.

Example:
class Animal {

int legs = 4;

class Dog extends Animal {

void show() {

[Link](legs); // inherited from Animal

9. Mention one difference between method overloading and method overriding.

Method Overloading Method Overriding

Occurs within the same class with different Occurs in subclass with same method name and
parameters. parameters as superclass.

10. What happens if a subclass defines a method with the same signature as its superclass?

If a subclass has a method with the same name and parameters, it overrides the parent’s method.
The child class version of the method is executed at runtime.

Long Answers:
1. Explain with an example the use and benefits of inheritance in Java

Explanation:

Inheritance allows one class to acquire (use) the properties and behaviors (methods and variables)
of another class.
The class that gives features is called the superclass (parent), and the class that receives them is
called the subclass (child).

It is one of the main features of Object-Oriented Programming.

Benefits of Inheritance:

1. Code Reusability – You don’t need to write the same code again and again.

2. Maintainability – Common features are kept in the parent class.


3. Extensibility – New classes can be created easily from old ones.

4. Less Code, More Clarity – It makes code cleaner and easier to understand.

Real-Life Example:

A “Car” class can inherit from a “Vehicle” class because both have common features like speed,
color, etc.

Java Example:

class Vehicle {

void start() {

[Link]("Vehicle starts...");

class Car extends Vehicle {

void display() {

[Link]("Car is ready to drive!");

public class Example1 {

public static void main(String[] args) {

Car c = new Car();

[Link](); // Inherited from Vehicle

[Link](); // Own method

Output:

Vehicle starts...
Car is ready to drive!

Explanation:

 The Car class inherits the start() method from Vehicle.

 We can use start() directly without writing it again in Car.

2. Describe different types of inheritance in Java with suitable diagrams

Explanation:

Java supports different forms of inheritance based on how classes are connected.

1. Single Inheritance

👉 One class inherits from another class.


Diagram:

Parent

Child

Example:

class Animal {}

class Dog extends Animal {}

2. Multilevel Inheritance

👉 One class inherits from another, and that class is inherited by another.
Diagram:

Grandparent

Parent

Child

Example:

class Animal {}
class Mammal extends Animal {}

class Dog extends Mammal {}

3. Hierarchical Inheritance

👉 Multiple classes inherit from a single parent.


Diagram:

Parent

/ \

Child1 Child2

Example:

class Animal {}

class Dog extends Animal {}

class Cat extends Animal {}

4. Multiple Inheritance (via Interface only)

👉 A class can inherit from multiple interfaces (not multiple classes).


Diagram:

Interface1 Interface2

\ /

\ /

\ /

Class

Example:

interface Animal {}

interface Pet {}

class Dog implements Animal, Pet {}

Note:

Java does not support multiple inheritance using classes directly to avoid confusion (called Diamond
Problem).
3. Write a Java program to demonstrate single inheritance and explain its output

Program:

class Person {

void eat() {

[Link]("Person is eating...");

class Student extends Person {

void study() {

[Link]("Student is studying...");

public class SingleInheritance {

public static void main(String[] args) {

Student s = new Student();

[Link](); // Inherited method

[Link](); // Own method

Output:

Person is eating...

Student is studying...

Explanation:

 The Student class inherits from Person.


 So, the Student object can use both eat() (from parent) and study() (its own method).

 This is single inheritance — one parent and one child.

Real-Life Example:

A Student is also a Person, so it inherits properties like name, age, etc., from the Person class.

4. Explain how data members and methods are inherited from a superclass to a subclass with an
example

Explanation:

When a subclass inherits a superclass:

 All non-private data members (variables) are accessible to the subclass.

 All non-private methods can also be used by the subclass.

Private members are not inherited directly, but can be accessed through public methods of the
superclass.

Example:

class Employee {

String company = "TechCorp";

void work() {

[Link]("Employee works at " + company);

class Developer extends Employee {

String language = "Java";

void showDetails() {

[Link]("Company: " + company); // inherited variable


[Link]("Language: " + language);

work(); // inherited method

public class DataMemberInheritance {

public static void main(String[] args) {

Developer d = new Developer();

[Link]();

Output:

Company: TechCorp

Language: Java

Employee works at TechCorp

Explanation:

 company (variable) and work() (method) are inherited from Employee.

 Developer can use both directly.

5. Illustrate with code the role of constructors in inheritance

Explanation:

 Constructors are not inherited, but the child class can call the parent constructor using
super().

 This helps to initialize parent class data before the child class starts.

Example:

class Parent {
Parent() {

[Link]("Parent class constructor called");

class Child extends Parent {

Child() {

super(); // calls Parent constructor

[Link]("Child class constructor called");

public class ConstructorDemo {

public static void main(String[] args) {

Child obj = new Child();

Output:

Parent class constructor called

Child class constructor called

Explanation:

 When Child object is created, first Parent() runs automatically (because of super()), then the
Child() constructor.

 This ensures proper initialization order — parent → child.

6. Demonstrate method overriding in Java and explain how the super keyword can be used to call
the superclass method
Explanation:

Method Overriding happens when a subclass defines a method with the same name, return type,
and parameters as its superclass.
This allows the subclass to provide its own version of that method.

Role of super:

The super keyword is used to call the parent class version of the overridden method.

Example:

class Animal {

void sound() {

[Link]("Animal makes a sound");

class Dog extends Animal {

void sound() {

[Link]("Dog barks");

[Link](); // calling parent class method

public class MethodOverridingDemo {

public static void main(String[] args) {

Dog d = new Dog();

[Link]();

}
Output:

Dog barks

Animal makes a sound

Explanation:

 Dog overrides the sound() method from Animal.

 The [Link]() statement allows the child to still access the original parent behavior.

Real-Life Example:

A Printer prints in black-and-white (parent class),


but a ColorPrinter (child class) overrides the method to print in color while still being able to access
the old function.

7. Write a Java program to show runtime polymorphism using inheritance.

Explanation:
Runtime polymorphism happens when a method is called through a reference of the parent class,
but the child class’s version of that method runs.
It uses method overriding — same method name and parameters in parent and child classes, but
different implementations.

Program:

class Animal {

void sound() {

[Link]("Animal makes a sound");

class Dog extends Animal {

void sound() {

[Link]("Dog barks");

}
}

class Cat extends Animal {

void sound() {

[Link]("Cat meows");

public class RuntimePolyExample {

public static void main(String[] args) {

Animal a; // reference of parent class

a = new Dog(); // object of child class

[Link](); // Dog's sound() runs

a = new Cat(); // another child object

[Link](); // Cat's sound() runs

Output:

Dog barks

Cat meows

Explanation:
Although the variable a is of type Animal, the actual method executed depends on the object
assigned at runtime. That’s why it’s called runtime polymorphism.

8. Differentiate between compile-time and runtime polymorphism with examples

Feature Compile-Time Polymorphism Runtime Polymorphism

Definition Achieved during compilation. Achieved during program


Feature Compile-Time Polymorphism Runtime Polymorphism

execution.

Dynamic binding / Late


Also called Static binding / Early binding.
binding.

Achieved by Method Overloading. Method Overriding.

Method Based on the actual object at


Based on reference type and parameters.
Selection runtime.

Overloading multiple methods with same name but Overriding a parent method in
Example
different parameters. subclass.

Example 1: Compile-Time Polymorphism

class MathOperation {

int add(int a, int b) {

return a + b;

double add(double a, double b) {

return a + b;

public class CompileTimeExample {

public static void main(String[] args) {

MathOperation m = new MathOperation();

[Link]([Link](5, 10)); // int version

[Link]([Link](2.5, 3.5)); // double version

Example 2: Runtime Polymorphism

class Vehicle {
void run() {

[Link]("Vehicle is running");

class Bike extends Vehicle {

void run() {

[Link]("Bike is running safely");

public class RuntimeExample {

public static void main(String[] args) {

Vehicle v = new Bike();

[Link](); // Calls Bike's run() at runtime

9. Explain type compatibility and type casting in inheritance with a program.

Explanation:
In Java, a child class object can be assigned to a parent class reference — this is called upcasting.
When we assign the parent reference back to a child class, it is called downcasting.

 Upcasting: Safe, automatic.

 Downcasting: Needs explicit casting.

Program:

class Parent {

void show() {

[Link]("This is Parent class");


}

class Child extends Parent {

void show() {

[Link]("This is Child class");

void childMethod() {

[Link]("Special method of Child class");

public class TypeCastingExample {

public static void main(String[] args) {

Parent p = new Child(); // Upcasting

[Link](); // Calls Child's method (runtime polymorphism)

// Downcasting

Child c = (Child) p;

[Link](); // Access Child-specific method

Output:

This is Child class

Special method of Child class

Explanation:

 When we assign Child object to Parent reference → Upcasting

 When we cast it back to Child → Downcasting


This helps Java handle objects in a flexible and reusable way.

10. Design a program using a base class Person and derived classes Student and Employee to
demonstrate polymorphism and method overriding.

Explanation:
In this example, the base class Person has a method showDetails().
Both subclasses Student and Employee override it to display their own details.
Polymorphism lets us call the same method, but it behaves differently based on the object type.

Program:

class Person {

String name;

int age;

Person(String name, int age) {

[Link] = name;

[Link] = age;

void showDetails() {

[Link]("Person Name: " + name + ", Age: " + age);

class Student extends Person {

String course;

Student(String name, int age, String course) {

super(name, age);

[Link] = course;
}

void showDetails() {

[Link]("Student Name: " + name + ", Age: " + age + ", Course: " + course);

class Employee extends Person {

double salary;

Employee(String name, int age, double salary) {

super(name, age);

[Link] = salary;

void showDetails() {

[Link]("Employee Name: " + name + ", Age: " + age + ", Salary: " + salary);

public class PolymorphismDemo {

public static void main(String[] args) {

Person p1 = new Student("Uzma", 24, "BCA");

Person p2 = new Employee("Ayaan", 28, 35000.50);

// Runtime polymorphism: same method, different outputs

[Link]();

[Link]();

}
}

Output:

Student Name: Uzma, Age: 24, Course: BCA

Employee Name: Ayaan, Age: 28, Salary: 35000.5

Explanation:

 showDetails() method is defined in all classes.

 Based on the object type (Student/Employee), the correct version runs at runtime.

 This shows the power of polymorphism — one interface, multiple behaviors.


Arrays & Strings
1. Define an array in Java. List any two advantages and disadvantages of using arrays.
2. Write a Java program to declare an integer array of size 5, store values in it, and print all
elements using a for-loop.
3. What is the difference between static initialization and dynamic initialization of arrays in Java?
Give an example of each.
4. Write a program to find the sum of all elements of an integer array.
5. Define a string in Java. Explain why strings are called immutable.
6. Write a program to count the total number of characters in a given string (without using
length()).
7. Differentiate between String and StringBuffer in Java.
8. Write a Java program to print the largest and smallest element in an array.
9. What is a multidimensional array? Write a program to create a 3×3 matrix and print it in matrix
form.
10. Write a Java program to reverse a given string using a loop.
11. Explain the use of substring(), toUpperCase(), and replace() methods of the String class with
examples.
12. Write a Java program to count the number of vowels in a given string.
13. Explain the concept of tokenizing a string. Write a program to split a string "Java,Python,C+
+,JavaScript" into separate words using split().
14. Write a Java program to check whether a given string is a palindrome.
15. Write a Java program to find the second largest element in an array.
16. Write a program to perform matrix addition of two 3×3 matrices.
17. Write a program to remove all duplicate characters from a given string.
18. Explain the difference between String, StringBuffer, and StringBuilder with examples.
19. Write a Java program to find the frequency of each word in a given string. (Hint: use split() and
loop)
20. Write a program to sort an array of strings in alphabetical order.

1. Define an array in Java. List any two advantages and disadvantages of using arrays.

Definition:
An array in Java is a collection of elements that all have the same data type, stored together in
continuous memory locations. Each element in an array is accessed using an index number that
starts from 0.

Syntax:

datatype[] arrayName = new datatype[size];

Example:

int marks[] = {85, 90, 78, 88, 95};

Here, marks[0] is 85, marks[1] is 90, and so on.


Advantages:

1. Saves memory — Instead of declaring multiple variables (mark1, mark2, etc.), we can
store all values in one array.

2. Easy to access — You can use loops (like for or while) to access all elements quickly.

Disadvantages:

1. Fixed size — Once created, you can’t increase or decrease the size of an array.

2. Same data type only — You can’t mix integers, strings, or doubles in one array.

Real-life example:
Think of an array like a row of boxes with numbers written on them — each box (index) stores
one item of the same kind.

2. Write a Java program to declare an integer array of size 5, store values in it, and print all
elements using a for-loop.

Explanation:
We will create an array of size 5, assign values to each element, and use a loop to print them one
by one.

Program:

public class ArrayExample {

public static void main(String[] args) {

int[] numbers = new int[5]; // Declaring an array of size 5

// Storing values

numbers[0] = 10;

numbers[1] = 20;

numbers[2] = 30;

numbers[3] = 40;

numbers[4] = 50;

[Link]("Array elements are:");

for (int i = 0; i < [Link]; i++) {

[Link]("Index " + i + ": " + numbers[i]);

}
}

Output:

Array elements are:

Index 0: 10

Index 1: 20

Index 2: 30

Index 3: 40

Index 4: 50

Explanation:
The loop runs 5 times, from 0 to 4 (because index starts at 0), printing each element.

3. What is the difference between static initialization and dynamic initialization of arrays in
Java? Give an example of each.

Explanation:
Java allows us to assign values to arrays in two ways — statically (at the time of declaration) and
dynamically (after declaration).

Type Description Example

int marks[] = {60, 70, 80, 90,


Static Initialization You declare and assign values together.
100};

Dynamic You declare an array first and assign values int marks[] = new int[5];
Initialization later using indexes. marks[0] = 60;

Example:

Static Initialization

int[] age = {18, 20, 22, 25, 28};

Dynamic Initialization

int[] age = new int[5];

age[0] = 18;

age[1] = 20;

age[2] = 22;

age[3] = 25;

age[4] = 28;

Difference:
In static, values are already known; in dynamic, they can be taken from user input or calculated
later.
4. Write a program to find the sum of all elements of an integer array.

public class SumArray {

public static void main(String[] args) {

int[] num = {10, 20, 30, 40, 50};

int sum = 0;

for (int i = 0; i < [Link]; i++) {

sum += num[i]; // add each element

[Link]("Sum of all elements = " + sum);

Output:

Sum of all elements = 150

Explanation:
The loop adds each value one by one. After the loop ends, sum holds the total.
This is like adding all marks of a student to get total marks.

5. Define a string in Java. Explain why strings are called immutable.

Definition:
A String in Java is a sequence of characters enclosed in double quotes " ".
Example:

String name = "Uzma";

Why Immutable?
Once a string object is created, you cannot change its content. If you try to modify it, Java creates
a new object in memory instead of changing the old one.

Example:

String s = "Hello";

s = s + " World"; // A new string "Hello World" is created

[Link](s);

The original string "Hello" still exists; "Hello World" is a new one.
Reason:
This helps make strings thread-safe, and they can be shared among many programs safely.

Real-life example:
It’s like writing on a paper with a pen — you can’t change what’s already written, only create a
new page with changes.

6. Write a program to count the total number of characters in a given string (without using
length()).

public class CountCharacters {

public static void main(String[] args) {

String str = "Java Programming";

int count = 0;

for (char c : [Link]()) {

count++;

[Link]("Total number of characters: " + count);

Output:

Total number of characters: 16

Explanation:
The loop goes through each character and increases the counter.
We didn’t use [Link]() — instead, we counted manually.

7. Differentiate between String and StringBuffer in Java.

Feature String StringBuffer

Mutability Immutable (cannot change). Mutable (can change).

Performance Slower for repeated changes. Faster for repeated modifications.

Memory Creates new object when changed. Uses same object for changes.

Thread Safety Not thread-safe. Thread-safe (synchronized).

Example String s = "Hello"; StringBuffer sb = new StringBuffer("Hello");


Feature String StringBuffer

Example:

StringBuffer sb = new StringBuffer("Hello");

[Link](" Java");

[Link](sb);

Output:

Hello Java

Explanation:
StringBuffer changes the same object, while String would create a new one.

8. Write a Java program to print the largest and smallest element in an array.

public class LargestSmallest {

public static void main(String[] args) {

int[] arr = {15, 3, 25, 8, 42, 10};

int largest = arr[0];

int smallest = arr[0];

for (int i = 1; i < [Link]; i++) {

if (arr[i] > largest)

largest = arr[i];

if (arr[i] < smallest)

smallest = arr[i];

[Link]("Largest element: " + largest);

[Link]("Smallest element: " + smallest);

Output:

Largest element: 42
Smallest element: 3

Explanation:
We assume first element as both largest and smallest, then compare each element one by one.

9. What is a multidimensional array? Write a program to create a 3×3 matrix and print it in
matrix form.

Explanation:
A multidimensional array means an array that contains another array.
A 2D array is like a table — rows and columns.

Program:

public class MatrixExample {

public static void main(String[] args) {

int[][] matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

[Link]("3x3 Matrix:");

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

[Link](matrix[i][j] + " ");

[Link]();

Output:

3x3 Matrix:

123

456

789
Real-life example:
Think of a chessboard — 8×8 grid. Each cell is accessed using a row and column number.

10. Write a Java program to reverse a given string using a loop.

public class ReverseString {

public static void main(String[] args) {

String str = "Programming";

String rev = "";

for (int i = [Link]() - 1; i >= 0; i--) {

rev = rev + [Link](i);

[Link]("Original String: " + str);

[Link]("Reversed String: " + rev);

Output:

Original String: Programming

Reversed String: gnimmargorP

Explanation:
We start from the last character and keep adding each character to rev.
In the end, we get the string in reverse order.

Real-life example:
It’s like reading a word from right to left instead of left to right.

11. Explain the use of substring(), toUpperCase(), and replace() methods of the String class with
examples.

Theory:
The String class in Java has many built-in methods to manipulate text.
Three common ones are:

1. substring(start, end) – Extracts part of a string.

2. toUpperCase() – Converts all letters to uppercase.


3. replace(oldChar, newChar) – Replaces all occurrences of a character or word.

Example:

public class StringMethods {

public static void main(String[] args) {

String text = "Hello Java World";

String sub = [Link](6, 10); // "Java"

String upper = [Link](); // "HELLO JAVA WORLD"

String replaced = [Link]("Java", "Uzma"); // "Hello Uzma World"

[Link]("Substring: " + sub);

[Link]("Uppercase: " + upper);

[Link]("Replaced: " + replaced);

Output:

Substring: Java

Uppercase: HELLO JAVA WORLD

Replaced: Hello Uzma World

12. Write a Java program to count the number of vowels in a given string.

Theory:
Vowels are a, e, i, o, u. We can check each character in a string and count vowels.

Example:

public class CountVowels {

public static void main(String[] args) {

String str = "Uzma Tadwala";

int count = 0;

str = [Link]();

for (int i = 0; i < [Link](); i++) {


char ch = [Link](i);

if (ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')

count++;

[Link]("Number of vowels: " + count);

Output:

Number of vowels: 5

13. Explain the concept of tokenizing a string. Write a program to split a string "Java,Python,C+
+,JavaScript" into separate words using split().

Theory:
Tokenizing means breaking a string into smaller parts (tokens) using a separator like , or space.
In Java, we can use split() method for this purpose.

Example:

public class TokenizeExample {

public static void main(String[] args) {

String languages = "Java,Python,C++,JavaScript";

String[] tokens = [Link](",");

[Link]("Programming Languages:");

for (String t : tokens) {

[Link](t);

Output:

Programming Languages:

Java

Python

C++
JavaScript

14. Write a Java program to check whether a given string is a palindrome.

Theory:
A palindrome is a word that reads the same backward as forward (like “madam” or “level”).
We can reverse a string and compare it to the original.

Example:

public class PalindromeCheck {

public static void main(String[] args) {

String str = "madam";

String rev = "";

for (int i = [Link]()-1; i >= 0; i--) {

rev += [Link](i);

if ([Link](rev))

[Link](str + " is a palindrome.");

else

[Link](str + " is not a palindrome.");

Output:

madam is a palindrome.

15. Write a Java program to find the second largest element in an array.

Theory:
To find the second largest, we compare all elements and track the largest and second largest.

Example:

public class SecondLargest {

public static void main(String[] args) {

int[] arr = {12, 45, 23, 67, 34};


int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;

for (int num : arr) {

if (num > first) {

second = first;

first = num;

} else if (num > second && num != first) {

second = num;

[Link]("Second largest number: " + second);

Output:

Second largest number: 45

16. Write a program to perform matrix addition of two 3×3 matrices.

Theory:
Matrix addition means adding the elements of two matrices at the same position.

Example:

public class MatrixAddition {

public static void main(String[] args) {

int[][] A = {{1,2,3},{4,5,6},{7,8,9}};

int[][] B = {{9,8,7},{6,5,4},{3,2,1}};

int[][] C = new int[3][3];

for (int i=0; i<3; i++) {

for (int j=0; j<3; j++) {

C[i][j] = A[i][j] + B[i][j];

}
[Link]("Matrix Addition:");

for (int i=0; i<3; i++) {

for (int j=0; j<3; j++) {

[Link](C[i][j] + " ");

[Link]();

Output:

Matrix Addition:

10 10 10

10 10 10

10 10 10

17. Write a program to remove all duplicate characters from a given string.

Theory:
We can use a new string and only add characters that haven’t appeared before.

Example:

public class RemoveDuplicates {

public static void main(String[] args) {

String str = "programming";

String result = "";

for (int i=0; i<[Link](); i++) {

char ch = [Link](i);

if ([Link](ch) == -1)

result += ch;

[Link]("After removing duplicates: " + result);


}

Output:

After removing duplicates: progamin

18. Explain the difference between String, StringBuffer, and StringBuilder with examples.

Theory:

Class Mutability Thread-Safe Speed Example Use

String Immutable (cannot be changed) Yes Slow When data won’t change

StringBuffer Mutable (can change) Yes Slower Multi-threaded apps

StringBuilder Mutable No Faster Single-threaded apps

Example:

public class StringTypes {

public static void main(String[] args) {

String s = "Hello";

[Link](" Java"); // not added because String is immutable

[Link](s); // Hello

StringBuffer sb = new StringBuffer("Hello");

[Link](" Java");

[Link](sb); // Hello Java

StringBuilder sb2 = new StringBuilder("Hi");

[Link](" Uzma");

[Link](sb2); // Hi Uzma

Output:

Hello

Hello Java

Hi Uzma
19. Write a Java program to find the frequency of each word in a given string.

Theory:
We can split the string into words using split(" ") and count each word using loops.

Example:

public class WordFrequency {

public static void main(String[] args) {

String text = "Java is fun and Java is powerful";

String[] words = [Link](" ");

for (int i=0; i<[Link]; i++) {

int count = 1;

for (int j=i+1; j<[Link]; j++) {

if (words[i].equals(words[j])) {

count++;

words[j] = "0"; // Mark counted word

if (words[i] != "0")

[Link](words[i] + " = " + count);

Output:

Java = 2

is = 2

fun = 1

and = 1

powerful = 1

20. Write a program to sort an array of strings in alphabetical order.


Theory:
Sorting strings means arranging them alphabetically using [Link]().

Example:

import [Link];

public class SortStrings {

public static void main(String[] args) {

String[] names = {"Uzma", "Fatima", "Aisha", "Zainab"};

[Link](names);

[Link]("Sorted Strings:");

for (String name : names) {

[Link](name);

Output:

Sorted Strings:

Aisha

Fatima

Uzma

Zainab
Module-7 Exception Handling

Long Questions

1. Explain the concept of exception handling in Java. Discuss why exceptions are used
and how they improve program reliability.

2. Differentiate between exceptions and errors in Java with suitable examples.

3. Describe the types of exceptions in Java in detail, along with examples of checked
and unchecked exceptions.

4. Explain the control flow of exception handling in Java using a neat diagram and
example program.

5. How does the Java Virtual Machine (JVM) react when an exception occurs during
program execution? Explain with examples.

6. Explain the purpose and usage of try, catch, finally, throw, and throws keywords in
Java exception handling with proper syntax and examples.

7. Discuss the difference between checked exceptions and unchecked exceptions in


Java, and explain when to use each with examples.

8. Write a Java program to demonstrate the use of multiple catch blocks and explain
how Java handles multiple exceptions.

9. Explain the difference between inbuilt (predefined) and user-defined exceptions in


Java. Write a Java program to create a custom exception.

10. Discuss best practices for handling exceptions in Java. Explain why proper
exception handling is important for secure and reliable applications.

Short Questions

1. What is an exception in Java?

2. Differentiate between exceptions and errors.

3. What are checked and unchecked exceptions? Give one example of each.

4. What is the purpose of the finally block in Java exception handling?

5. What is the difference between the throw and throws keywords in Java?

6. Give any two examples of inbuilt exceptions in Java.

7. Why is exception handling important in Java programs?

8. What happens if an exception is not handled in Java?

9. Write the syntax of a try-catch-finally block in Java.

10. What is a user-defined exception? Give one simple example scenario.


Long Answers:
1. Concept of Exception Handling in Java
Meaning:
In Java, exception handling is a mechanism that allows us to detect and manage runtime errors
(errors that happen while the program is running).
It ensures that the normal flow of the program is not interrupted when something goes wrong.
Example:
When you divide a number by zero, Java throws an ArithmeticException. Instead of crashing, we
can handle this exception using try-catch.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero!");
}
Why it is used:
 To maintain normal program flow even after an error occurs.
 To avoid program crashes.
 To handle unexpected situations like file not found, invalid input, or network failure.
Improves reliability:
Exception handling improves program reliability because it:
 Detects problems automatically.
 Gives the programmer control over what happens when an error occurs.
 Prevents abnormal termination.

2. Difference Between Exceptions and Errors


Basis Exception Error
An error represents serious problems that
An exception is a condition that a
Definition are not meant to be handled by the
program can handle during execution.
program.
Yes, exceptions can be caught and
Recoverable? No, errors usually cannot be recovered.
handled.
Package Belongs to [Link] class. Belongs to [Link] class.
ArithmeticException, OutOfMemoryError, StackOverflowError,
Examples
NullPointerException, IOException. VirtualMachineError.
Handling Handled using try-catch blocks. Usually not handled by programmers.
Example:
// Exception Example
try {
int a = 5 / 0;
} catch (ArithmeticException e) {
[Link]("Handled exception!");
}

// Error Example
int[] arr = new int[999999999]; // May cause OutOfMemoryError
3. Types of Exceptions in Java
Java exceptions are mainly divided into two types:
(A) Checked Exceptions
 These are checked at compile time.
 The compiler forces the programmer to handle them using try-catch or throws.
 These usually occur due to external factors like file handling or database connections.
Examples:
 IOException
 SQLException
 FileNotFoundException
Example:
import [Link].*;

class Example {
public static void main(String[] args) {
try {
FileReader f = new FileReader("[Link]");
} catch (FileNotFoundException e) {
[Link]("File not found!");
}
}
}

(B) Unchecked Exceptions


 These are not checked at compile time.
 They occur at runtime due to logical or coding errors.
 They belong to the class RuntimeException.
Examples:
 ArithmeticException
 NullPointerException
 ArrayIndexOutOfBoundsException
Example:
class Example {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
[Link](arr[5]); // Unchecked exception
}
}

4. Control Flow of Exception Handling


Flow Diagram:
Try Block

Exception Occurs?
/ \
Yes No
↓ ↓
Catch Block Normal Flow

Finally Block (Always executes)

Program Continues
Example Program:
class FlowExample {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Exception caught!");
} finally {
[Link]("Finally block executed.");
}
[Link]("Program continues...");
}
}
Output:
Exception caught!
Finally block executed.
Program continues...

5. How JVM Reacts When Exception Occurs


When an exception occurs, JVM follows these steps:
1. Searches for a matching catch block in the current method.
2. If not found, it moves up the call stack to find one in the calling method.
3. If no matching handler is found, JVM terminates the program and displays an exception
message.
Example:
class Example {
static void divide() {
int x = 5 / 0; // Exception here
}
public static void main(String[] args) {
divide();
[Link]("End of program");
}
}
Output:
Exception in thread "main" [Link]: / by zero
at [Link]([Link])
at [Link]([Link])
👉 The JVM ends the program because no catch block was found.

6. Purpose and Usage of Exception Handling Keywords


Keyword Purpose Example / Syntax
Block that contains code which may
try try { int a = 10 / 0; }
cause an exception.
Handles the exception thrown by try catch(ArithmeticException e)
catch
block. { [Link]("Error!"); }
Executes whether an exception occurs finally { [Link]("Always
finally
or not (used to close resources). executed"); }
throw new ArithmeticException("Division by
throw Used to throw an exception manually.
zero");
Declares that a method may throw an
throws void readFile() throws IOException { ... }
exception to be handled elsewhere.
Full Example:
import [Link].*;

class Example {
static void checkAge(int age) throws IOException {
if (age < 18)
throw new IOException("Not eligible!");
else
[Link]("Eligible!");
}

public static void main(String[] args) {


try {
checkAge(15);
} catch (IOException e) {
[Link]("Exception: " + [Link]());
} finally {
[Link]("Check completed.");
}
}
}

7. Difference Between Checked and Unchecked Exceptions


Basis Checked Exceptions Unchecked Exceptions
Compile-time
Checked at compile-time. Checked at runtime.
check
Must be handled using try-catch or declared
Handling Handling is optional.
with throws.
External issues like file, network, or
Reason Logical or programming errors.
database.
Inherits from Exception (but not
Parent class Inherits from RuntimeException.
RuntimeException).
IOException, SQLException, NullPointerException,
Examples
FileNotFoundException. ArithmeticException.
When to use:
 Use checked exceptions when the program can recover from the problem (like retrying
file access).
 Use unchecked exceptions for programming mistakes (like invalid index, null pointer,
etc.).

✅ Summary:
 Exception handling makes Java programs safe and stable.
 It separates error-handling code from normal code.
 Main keywords: try, catch, finally, throw, throws.
 JVM terminates program if exception is not handled.
 Checked exceptions → compile-time; Unchecked → runtime.

8. Java Program to Demonstrate Multiple Catch Blocks


Concept:
In Java, we can have multiple catch blocks after one try block.
Each catch block is designed to handle a different type of exception.
When an exception occurs, Java checks each catch block from top to bottom to find the first
matching type and executes it.

Program Example:
class MultipleCatchExample {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int result = a / b; // ArithmeticException

int[] arr = new int[3];


arr[5] = 50; // ArrayIndexOutOfBoundsException

String str = null;


[Link]([Link]()); // NullPointerException
}
catch (ArithmeticException e) {
[Link]("Arithmetic Exception: Cannot divide by zero.");
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Index Out of Bounds Exception.");
}
catch (NullPointerException e) {
[Link]("Null Pointer Exception occurred.");
}
catch (Exception e) {
[Link]("General Exception: " + [Link]());
}
[Link]("Program continues normally...");
}
}

Output:
Arithmetic Exception: Cannot divide by zero.
Program continues normally...

Explanation:
1. Only one exception occurs at a time — in this case, ArithmeticException.
2. Java checks each catch block in order and executes the first match.
3. After handling the exception, control goes outside the try-catch and the program
continues.

Key Point:
 Always write more specific exceptions first (like ArithmeticException)
and general ones (like Exception) later, because Java checks them in order.
If you write the general one first, you’ll get a compiler error because it will “hide” the others.

9. Difference Between Inbuilt (Predefined) and User-Defined Exceptions


(A) Inbuilt (Predefined) Exceptions
These are the exceptions that are already defined in Java libraries.
They are part of the Java API and are ready to use.
Examples:
 ArithmeticException
 ArrayIndexOutOfBoundsException
 NullPointerException
 IOException
Example Code:
class InbuiltExample {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Inbuilt Exception: Division by zero!");
}
}
}

(B) User-Defined Exceptions


Sometimes, predefined exceptions are not enough.
We can create our own custom exception class to handle specific situations in our program.
To create one:
1. Define a class that extends the Exception class.
2. Use the throw keyword to throw the exception.

Example Program:
// Step 1: Create a custom exception
class AgeInvalidException extends Exception {
public AgeInvalidException(String message) {
super(message);
}
}

// Step 2: Use the custom exception


class CustomExceptionExample {
static void checkAge(int age) throws AgeInvalidException {
if (age < 18) {
throw new AgeInvalidException("You must be 18 or older to vote!");
} else {
[Link]("You are eligible to vote!");
}
}

public static void main(String[] args) {


try {
checkAge(15);
} catch (AgeInvalidException e) {
[Link]("Custom Exception Caught: " + [Link]());
}
}
}

Output:
Custom Exception Caught: You must be 18 or older to vote!

Difference Table:
Basis Inbuilt Exception User-Defined Exception
Definition Already defined by Java. Created by the programmer.
Handle common errors like division by zero, Handle specific conditions related to
Purpose
invalid index, etc. user logic.
From [Link] package (e.g. Exception, Extends Exception or
Class Used
RuntimeException). RuntimeException.
AgeInvalidException,
Example ArithmeticException, IOException.
LoginFailedException.

10. Best Practices for Handling Exceptions in Java


Proper exception handling makes applications safe, secure, and reliable.
Below are some best practices every Java programmer should follow:
1. Use Specific Exception Types
Instead of catching a general Exception, catch specific exceptions like IOException,
SQLException, etc.
✅ Good:
catch (IOException e) { ... }
❌ Bad:
catch (Exception e) { ... }

2. Don’t Ignore Exceptions


Avoid empty catch blocks.
Ignoring them hides potential problems.
✅ Good:
catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
}
❌ Bad:
catch (Exception e) {
// do nothing
}

3. Clean Up Resources Using finally or try-with-resources


Always close files, database connections, or sockets after use.
✅ Example:
try (FileReader fr = new FileReader("[Link]")) {
// use file
} catch (IOException e) {
[Link]([Link]());
}
(try-with-resources automatically closes the file.)

4. Don’t Overuse Exceptions


Use exceptions only for exceptional conditions, not for normal program flow.
For example, don’t throw an exception just to exit a loop.

5. Provide Meaningful Error Messages


When throwing or catching exceptions, give clear and useful messages to help debug easily.
✅ Example:
throw new IllegalArgumentException("Age cannot be negative!");

6. Log Exceptions
Use logging ([Link] or log4j) to record exceptions for analysis.
catch (IOException e) {
[Link]([Link]()).log([Link], null, e);
}

7. Convert Checked Exceptions When Needed


Sometimes, it’s better to wrap a checked exception into an unchecked one if you can’t handle it
properly.

Why Proper Exception Handling Is Important


1. ✅ Prevents Application Crash: Keeps the program running smoothly.
2. 🔐 Improves Security: Prevents leakage of sensitive error details to users.
3. ⚙️Improves Reliability: Ensures system stability under failure conditions.
4. 🧠 Easy Debugging: Helps identify the exact cause and location of errors.
5. 🌐 User-Friendly: Shows proper messages instead of confusing error codes.

Summary:
 Multiple catch blocks help handle different errors separately.
 User-defined exceptions make programs more meaningful and readable.
 Proper exception handling ensures that Java applications are robust, safe, and error-
resistant.

Short Answers:
1. What is an exception in Java?
An exception in Java is an unexpected event or error that happens during program execution
and interrupts the normal flow of the program.
For example, dividing a number by zero or trying to open a missing file can cause exceptions.

2. Differentiate between exceptions and errors.


Basis Exception Error
Problems that can be handled by the
Meaning Serious issues that cannot be handled.
program.
Recoverable? Yes, program can recover. No, usually not recoverable.
OutOfMemoryError,
Examples ArithmeticException, IOException
StackOverflowError

3. What are checked and unchecked exceptions? Give one example of each.
 Checked Exceptions:
These are checked at compile time. The program must handle them using try-catch or
throws.
👉 Example: IOException
 Unchecked Exceptions:
These occur at runtime and are not checked by the compiler.
👉 Example: ArithmeticException

4. What is the purpose of the finally block in Java exception handling?


The finally block is used to execute important code (like closing files or connections) whether
an exception occurs or not.
It always runs after the try and catch blocks.

5. What is the difference between the throw and throws keywords in Java?
Keyword Purpose Example
throw Used to throw an exception manually. throw new IOException();
Used in a method declaration to indicate that the void readFile() throws
throws
method may throw an exception. IOException { }

6. Give any two examples of inbuilt exceptions in Java.


1. ArithmeticException – occurs when dividing by zero.
2. NullPointerException – occurs when using an object that has no value.

7. Why is exception handling important in Java programs?


Exception handling is important because it:
 Prevents the program from crashing suddenly.
 Helps detect and fix errors easily.
 Keeps the program running smoothly and safely even when unexpected events occur.

8. What happens if an exception is not handled in Java?


If an exception is not handled, the Java Virtual Machine (JVM) stops the program and shows an
error message with the type of exception and the line number where it occurred.

9. Write the syntax of a try-catch-finally block in Java.


try {
// Code that may cause an exception
}
catch (ExceptionType e) {
// Code to handle the exception
}
finally {
// Code that always executes
}

10. What is a user-defined exception? Give one simple example scenario.


A user-defined exception is a custom exception created by the programmer to handle specific
errors in the program.
Example scenario:
If a student’s marks are negative, we can throw a custom exception called InvalidMarksException.
class InvalidMarksException extends Exception {
InvalidMarksException(String msg) {
super(msg);
}
}

SSCA2022 – Core Java Question Bank

Module-8
Short Questions
1. Define a thread in Java.
2. What is multithreading and why is it needed?
3. List any two bene its of multithreaded programming.
4. Name the different states in a thread life cycle.
5. What is the use of start() method in thread programming?
6. Differentiate between user thread and daemon thread.
7. What is thread priority?
8. Mention the purpose of thread synchronization.
9. What is inter-thread communication?
10. State the use of join() method in threads.
Long Questions
1. Explain the thread life cycle with a neat diagram and suitable methods.
2. Discuss the need for multithreaded programming with appropriate examples.
3. Describe various ways to create a thread in Java with examples.
4. Explain thread priorities and their effect on thread scheduling.
5. What is thread synchronization? Explain synchronized methods and blocks with examples.
6. Discuss inter-thread communication using wait(), notify(), and notifyAll() with an example.
7. Compare multithreading vs multiprocessing in terms of resource sharing and performance.
8. Describe different thread methods for controlling execution (sleep, yield, join, interrupt).
9. Explain with example how race conditions can occur and how synchronization solves it.
10. Write a program to demonstrate communication between two threads using wait() and notify().

Short Answers:
1. Define a thread in Java.

A thread in Java is a lightweight subprocess that runs a small part of a program.


It allows multiple tasks to run at the same time within a single program.
Each thread has its own execution path.

2. What is multithreading and why is it needed?

Multithreading means running two or more threads at the same time.


It is needed to make programs faster and more efficient, especially when performing multiple tasks
like downloading, playing music, or responding to user input at once.

3. List any two benefits of multithreaded programming.

1. Better performance – Tasks run simultaneously, using CPU efficiently.

2. Faster response – The program remains active and doesn’t freeze while doing heavy work.

4. Name the different states in a thread life cycle.

The main states of a thread are:

1. New – Thread is created but not started.

2. Runnable – Thread is ready to run.


3. Running – Thread is executing code.

4. Blocked/Waiting – Thread is waiting for some resource or signal.

5. Terminated – Thread has finished execution.

5. What is the use of start() method in thread programming?

The start() method is used to begin the execution of a thread.


It internally calls the run() method and tells the JVM to schedule the thread for running.

[Link]();

6. Differentiate between user thread and daemon thread.

User Thread Daemon Thread

Created by the user to perform


Used for background tasks like garbage collection.
main tasks.

JVM waits for them to finish before JVM does not wait for them; they stop automatically when user
ending. threads finish.

7. What is thread priority?

Thread priority decides which thread gets more CPU time.


Each thread has a priority value (from 1 to 10).
Higher priority threads are usually executed before lower ones.

[Link](8);

8. Mention the purpose of thread synchronization.

Thread synchronization ensures that only one thread accesses a shared resource at a time,
preventing data corruption or inconsistency.
It is mainly done using the synchronized keyword.

9. What is inter-thread communication?

Inter-thread communication allows threads to communicate and coordinate with each other using
methods like wait(), notify(), and notifyAll().
It helps one thread pause its work until another thread gives a signal to continue.

10. State the use of join() method in threads.


The join() method makes one thread wait for another thread to complete before it continues.
It ensures that one thread finishes its task before the next one starts.

[Link](); // main thread waits until t1 completes

Long Answers:
1. Explain the Thread Life Cycle with a Neat Diagram and Suitable Methods

Meaning:

The thread life cycle represents the different states a thread goes through from its creation to its end.
Each thread is controlled by the Java Virtual Machine (JVM) and moves between different states
depending on its actions.

Thread Life Cycle States:

1. New (Born State):

o A thread is created but not started yet.

o It enters this state when an object of the Thread class is created.

o Method used: Thread t = new Thread();

2. Runnable State:

o After calling the start() method, the thread is ready to run.

o It is waiting for CPU time to execute.

o Method: [Link]();

3. Running State:

o The thread is being executed by the CPU.

o JVM decides which thread will run first (based on scheduling and priority).

4. Blocked / Waiting State:

o The thread is temporarily inactive or waiting for another thread to complete its task
or resource.

o Methods that cause waiting: sleep(), wait(), or waiting for I/O.

5. Terminated (Dead State):

o The thread finishes its task or is stopped manually.

o It cannot be restarted again.

o Method: When run() completes or stop() is called.


Diagram of Thread Life Cycle:

New

↓ (start())

Runnable

↓ (JVM scheduler)

Running

↑ ↓

wait() sleep() blocked

↓ ↑

Waiting

↓ (notify()/resume())

Runnable

↓ (run() completed)

Terminated

Example Program:

class ThreadLifeCycle extends Thread {

public void run() {

[Link]("Thread is running...");

public static void main(String args[]) {

ThreadLifeCycle t1 = new ThreadLifeCycle(); // New

[Link](); // Runnable → Running

[Link]("Thread started...");

2. Discuss the Need for Multithreaded Programming with Appropriate Examples


Meaning:

Multithreading means executing multiple parts of a program (threads) simultaneously to perform


different tasks at the same time.

Need for Multithreading:

1. Better Performance:
Multiple threads make better use of CPU resources and speed up the program.

2. Faster Execution:
Tasks like downloading files, playing music, or responding to user input can occur
simultaneously.

3. Smooth User Interface:


The program doesn’t freeze or hang during long operations.

4. Efficient Resource Sharing:


Threads can share memory and data easily.

Example:

class Music extends Thread {

public void run() {

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

[Link]("Playing music...");

class Download extends Thread {

public void run() {

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

[Link]("Downloading file...");

class MultithreadExample {

public static void main(String args[]) {


Music m = new Music();

Download d = new Download();

[Link]();

[Link]();

Output:

Playing music...

Downloading file...

Playing music...

Downloading file...

(Threads run parallelly, showing multitasking.)

3. Describe Various Ways to Create a Thread in Java with Examples

There are two main ways to create threads in Java:

1. By Extending the Thread Class

 Create a class that extends Thread.

 Override the run() method with the code to execute.

 Create an object and call start() to run it.

Example:

class MyThread extends Thread {

public void run() {

[Link]("Thread is running...");

public static void main(String args[]) {

MyThread t1 = new MyThread();

[Link](); // starts the thread

}
}

2. By Implementing the Runnable Interface

 Create a class that implements Runnable.

 Pass the object to a Thread object and call start().

Example:

class MyRunnable implements Runnable {

public void run() {

[Link]("Thread is running using Runnable...");

public static void main(String args[]) {

MyRunnable obj = new MyRunnable();

Thread t = new Thread(obj);

[Link]();

Difference:

Thread Class Runnable Interface

Cannot extend any other class (because Java allows single


Can still extend another class.
inheritance).

Better for large applications and


Simpler for small programs.
flexibility.

4. Explain Thread Priorities and Their Effect on Thread Scheduling

Meaning:

Every thread in Java has a priority number between 1 and 10.


It helps the JVM decide which thread to execute first when multiple threads are ready to run.

Default Priorities:
 MIN_PRIORITY = 1

 NORM_PRIORITY = 5 (default)

 MAX_PRIORITY = 10

Effect on Scheduling:

 Higher-priority threads get more CPU time.

 However, thread scheduling depends on the JVM and operating system, so it’s not
guaranteed.

Example:

class PriorityExample extends Thread {

public void run() {

[Link]("Thread: " + [Link]().getName() +

" Priority: " + [Link]().getPriority());

public static void main(String args[]) {

PriorityExample t1 = new PriorityExample();

PriorityExample t2 = new PriorityExample();

PriorityExample t3 = new PriorityExample();

[Link](Thread.MIN_PRIORITY);

[Link](Thread.NORM_PRIORITY);

[Link](Thread.MAX_PRIORITY);

[Link]();

[Link]();

[Link]();

}
Output (May vary):

Thread: Thread-2 Priority: 10

Thread: Thread-1 Priority: 5

Thread: Thread-0 Priority: 1

5. What is Thread Synchronization? Explain Synchronized Methods and Blocks with Examples

Meaning:

When multiple threads try to access the same shared resource (like a variable or file) at the same
time, data inconsistency can occur.
To prevent this, Java provides synchronization to allow only one thread at a time to access the
resource.

1. Synchronized Method:

A method declared with the synchronized keyword ensures that only one thread executes it at a time.

Example:

class Bank {

synchronized void withdraw(int amount) {

[Link]("Withdrawing " + amount);

try {

[Link](1000);

} catch (Exception e) {}

[Link]("Withdraw successful!");

class Customer extends Thread {

Bank b;

Customer(Bank b) { this.b = b; }

public void run() { [Link](1000); }

}
class SyncExample {

public static void main(String args[]) {

Bank obj = new Bank();

Customer c1 = new Customer(obj);

Customer c2 = new Customer(obj);

[Link]();

[Link]();

✅ Only one customer can withdraw at a time due to synchronization.

2. Synchronized Block:

You can synchronize only a part of a method instead of the whole method.

synchronized(object) {

// code to be synchronized

Example:

class Table {

void printTable(int n) {

synchronized(this) {

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

[Link](n*i);

6. Discuss Inter-Thread Communication using wait(), notify(), and notifyAll() with an Example

Meaning:
Inter-thread communication allows threads to communicate and coordinate with each other.
It helps one thread pause execution and another thread to signal when it can continue.

Important Methods:

Method Description

wait() Makes the current thread wait until another thread calls notify().

notify() Wakes up one thread that is waiting.

notifyAll() Wakes up all waiting threads.

These methods are called on objects, not threads.

Example Program:

class Message {

boolean flag = false;

synchronized void produce() {

try {

[Link]("Producing message...");

flag = true;

wait(); // waits until notify() is called

[Link]("Resumed after consumption...");

} catch (Exception e) { }

synchronized void consume() {

try {

[Link]("Consuming message...");

if (flag) {

notify(); // wakes the waiting thread

} catch (Exception e) { }
}

class Communication {

public static void main(String args[]) {

Message msg = new Message();

Thread producer = new Thread(() -> [Link]());

Thread consumer = new Thread(() -> [Link]());

[Link]();

[Link]();

Output:

Producing message...

Consuming message...

Resumed after consumption...

Explanation:

1. The producer thread waits using wait().

2. The consumer thread uses notify() to wake it up.

3. Both threads communicate smoothly without conflict.

✅ Summary of All Concepts:

 Threads allow multitasking in a single program.

 Thread life cycle has five main states.

 We can create threads by extending Thread or implementing Runnable.

 Priorities affect which thread runs first.


 Synchronization prevents data corruption.

 Inter-thread communication allows coordination between threads.

7. Compare multithreading vs multiprocessing in terms of resource sharing and performance.

Multithreading

 Multithreading means running multiple threads (small tasks) within a single process.

 All threads share the same memory and resources of the process.

 It is lightweight and consumes less memory since threads are part of one process.

 Switching between threads is faster because they share the same memory space.

 However, threads can interfere with each other if not synchronized properly.

Example:
A web browser running multiple tabs — all share memory but work independently.

Multiprocessing

 Multiprocessing means running multiple processes, each with its own memory and
resources.

 Each process is independent, so one process crash does not affect another.

 It is heavyweight and requires more memory and CPU.

 Switching between processes is slower because each has its own memory space.

 There is no data sharing by default between processes.

Example:
Running a music player, a browser, and a text editor at the same time on your computer.

Comparison Table

Feature Multithreading Multiprocessing

Definition Multiple threads in one process Multiple independent processes

Memory Sharing Shared memory Separate memory

Speed Faster context switching Slower context switching

Communication Easier (shared variables) Harder (needs IPC)

Crash Impact One thread crash affects all threads One process crash does not affect others

Best For Lightweight, parallel tasks CPU-intensive, isolated tasks


Feature Multithreading Multiprocessing

8. Describe different thread methods for controlling execution (sleep, yield, join, interrupt).

Java provides several methods in the Thread class to control the execution flow of threads.

1. sleep()

 Used to pause the thread for a specific time (in milliseconds).

 The thread moves to Timed Waiting state.

[Link](2000); // pauses for 2 seconds

2. yield()

 Used to temporarily pause the current thread to give other threads a chance to execute.

 It helps achieve better CPU utilization.

 However, it does not guarantee that another thread will run immediately.

[Link]();

3. join()

 Makes one thread wait until another thread finishes execution.

 Useful when one thread’s result is needed before continuing.

[Link](); // current thread waits until t1 completes

4. interrupt()

 Used to interrupt a sleeping or waiting thread.

 It doesn’t stop the thread directly but sends a signal that it should stop.

[Link]();

If the thread is sleeping, it throws an InterruptedException.

9. Explain with example how race conditions can occur and how synchronization solves it.

Race Condition
A race condition happens when two or more threads access shared data at the same time, and the
final result depends on which thread runs first.
This can cause wrong or unpredictable output.

Example (without synchronization):

class Counter {

int count = 0;

void increment() {

count++;

public class RaceExample {

public static void main(String[] args) throws Exception {

Counter c = new Counter();

Thread t1 = new Thread(() -> {

for (int i = 0; i < 1000; i++) [Link]();

});

Thread t2 = new Thread(() -> {

for (int i = 0; i < 1000; i++) [Link]();

});

[Link]();

[Link]();

[Link]();

[Link]();

[Link]("Count = " + [Link]); // Expected 2000, but may be less

}
Here, both threads modify the same variable count at the same time → race condition occurs.

Solution – Synchronization

To fix this, we can use the synchronized keyword to lock the method, so only one thread can access it
at a time.

class Counter {

int count = 0;

synchronized void increment() {

count++;

Now, the program will always print the correct result (Count = 2000).
Synchronization ensures safe access to shared resources.

10. Write a program to demonstrate communication between two threads using wait() and notify().

Program Example

class Message {

private String msg;

private boolean empty = true;

public synchronized void write(String m) {

while (!empty) {

try { wait(); } catch (InterruptedException e) {}

empty = false;

msg = m;

[Link]("Written: " + msg);

notify();

}
public synchronized void read() {

while (empty) {

try { wait(); } catch (InterruptedException e) {}

[Link]("Read: " + msg);

empty = true;

notify();

public class ThreadCommunication {

public static void main(String[] args) {

Message msg = new Message();

Thread writer = new Thread(() -> {

String[] texts = {"Hello", "Java", "Threads"};

for (String t : texts) [Link](t);

});

Thread reader = new Thread(() -> {

for (int i = 0; i < 3; i++) [Link]();

});

[Link]();

[Link]();

Explanation

 The write() method writes data and calls notify() to signal the reader.

 The read() method waits until there’s data (wait()), then reads it.
 Both methods are synchronized so that only one runs at a time.

 The output will show proper alternation between writing and reading.
Module - 9

Java Packages
Part A: Short Answer Questions

• 1. What is a package in Java?

• 2. List any two advantages of using packages.

• 3. How do you define a package in a Java program?

• 4. What is the purpose of the import statement?

• 5. What is static import? Give an example.

• 6. What is the naming convention for userdefined packages?

• 7. Differentiate between built-in packages and user-defined packages.


Short Answers:

1. What is a package in Java?


A package in Java is a way to group related classes, interfaces, and sub-packages
together.
It helps organize code properly and avoid name conflicts.
Example: [Link], [Link], [Link].

2. List any two advantages of using packages.


1. Code organization: Packages make the program neat and manageable by
grouping similar classes.
2. Name conflict avoidance: Classes in different packages can have the same name
without confusion.
3. (Extra benefit – helps in access control and code reusability.)

3. How do you define a package in a Java program?


A package is defined using the package keyword at the top of the Java file (before
any class).
Example:
package mypackage;

public class Hello {


void display() {
[Link]("Hello from mypackage!");
}
}

4. What is the purpose of the import statement?


The import statement is used to access classes from other packages without
writing their full package name every time.
Example:
import [Link]; // imports Scanner class
Now you can directly write:
Scanner sc = new Scanner([Link]);
5. What is static import? Give an example.
A static import allows you to access static members (methods or variables) of a
class without class name.
It helps make the code shorter and cleaner.
Example:
import static [Link].*;
Now you can use:
[Link](sqrt(16)); // instead of [Link](16)

6. What is the naming convention for user-defined packages?


The naming convention is to use all lowercase letters and sometimes include the
reverse of your domain name to make it unique.
Example:
[Link]
or simple lowercase like:
[Link]
7. Differentiate between built-in packages and user-defined packages.
Built-in Packages User-defined Packages
Already provided by Java. Created by programmers.
Examples: [Link], [Link], [Link] Examples: mypackage, [Link]
Contain predefined classes and Contain user-created classes and
interfaces. methods.
Used by defining with the package
Used by importing from Java library.
keyword.

Part B: Medium Answer Questions


• 8. Explain how access protection works with packages. Which access modifiers are
package-specific?
• 9. Write the steps to create and use a user-defined package in Java with an
example.
• 10. What is the role of CLASSPATH in packages? How do you set it?
• 11. Differentiate between importing a single class and importing an entire package
with examples.
• 12. What is a JAR file? Explain the process of creating a JAR file for a package in
Java.
• 13. Write a program that defines a package named myPack containing a class
Message, and another class in a different package that imports and uses it.
• 14. Explain with example how static import can simplify code compared to normal
import.

8. Explain how access protection works with packages. Which access modifiers are
package-specific?
Java uses access modifiers to control how classes and members (methods, variables)
can be accessed from different packages.
The main access levels are:
Modifier Access Level Accessible From
All classes in all
public Everywhere
packages
Same package + subclasses in other Allows inheritance
protected
packages access
Modifier Access Level Accessible From
(no modifier)
Only within same package Package-specific access
(default)
private Within the same class only No package access
👉 Package-specific modifiers:
 default (no modifier) → accessible only inside the same package.

 protected → accessible inside the same package and in subclasses of other


packages.
This helps keep code secure and organized by limiting what can be used from outside
the package.

9. Write the steps to create and use a user-defined package in Java with an example.
Steps:
1. Create a package using the package keyword.
2. Store the file in a folder with the same package name.
3. Compile the file using javac -d . [Link] to create the package folder.
4. Import the package into another program using the import statement.
5. Use the class from that package.
Example:
File 1: [Link]
package mypackage;

public class Message {


public void show() {
[Link]("Hello from mypackage!");
}
}
File 2: [Link]
import [Link];

public class Main {


public static void main(String[] args) {
Message obj = new Message();
[Link]();
}
}
[Link] is the role of CLASSPATH in packages? How do you set it?
Q10. Role of CLASSPATH in Packages (Short & Easy)

Meaning:
CLASSPATH is an environment variable that tells Java where to find class files
and packages when compiling or running a program.
It prevents errors like “Class Not Found” by guiding Java to the correct folder or
JAR file.

Example:
If you have a package:
C:\JavaPrograms\myPack\[Link]
and a program in another folder uses it:
import [Link];
Java needs CLASSPATH to locate myPack.

Ways to Set CLASSPATH:


1. Temporarily (Command Line):
set CLASSPATH=C:\JavaPrograms
java Test
2. Using -classpath / -cp option:
java -cp C:\JavaPrograms Test
3. Permanently (System Environment Variable)
Set CLASSPATH in system settings to include package folder, e.g., C:\
JavaPrograms;.

Key Points:
 Default is current directory (.) if CLASSPATH not set.
 Multiple paths can be separated by ; (Windows) or : (Linux).
 Helps Java find user-defined packages and avoids errors.

Analogy:
CLASSPATH is like a map that tells Java where all your class files (houses) are
located.

11. Differentiate between importing a single class and importing an entire package
with examples.
Import Type Syntax Example Meaning
Import a single import import Only that specific
class [Link]; [Link]; class can be used.
Import an import packageName.*; import [Link].*; All classes in that
entire package package can be
Import Type Syntax Example Meaning
used.
👉 Using * is easier but may slightly slow down compilation if the package is large.

12. What is a JAR file? Explain the process of creating a JAR file for a package in Java.
JAR (Java ARchive) file is a compressed file (.jar) that bundles together multiple .class
files, metadata, and resources into one file.
It helps in distributing Java packages and libraries easily.
Steps to create a JAR file:
1. Compile your package classes:
2. javac -d . [Link]
3. Create the JAR file:
4. jar cf [Link] mypackage
Here:
o c = create a new JAR file

o f = specify filename ([Link])

o mypackage = folder containing your package classes

5. Run using the JAR:


6. java -cp [Link] Main
13. Write a program that defines a package named myPack containing a class
Message, and another class in a different package that imports and uses it.
File 1: [Link]
package myPack;

public class Message {


public void display() {
[Link]("Hello from myPack package!");
}
}
File 2: [Link]
import [Link];

public class TestPackage {


public static void main(String[] args) {
Message m = new Message();
[Link]();
}
}
Steps to run:
1. Compile [Link] → javac -d . [Link]
2. Compile [Link] → javac [Link]
3. Run → java TestPackage

14. Explain with example how static import can simplify code compared to normal
import.
Normal Import:
You must write the class name every time you use its static method.
import [Link];

public class Example {


public static void main(String[] args) {
[Link]([Link](25)); // need Math.
[Link]([Link](2,3));
}
}
Static Import:
You can use the methods directly without class name.
import static [Link].*;

public class Example {


public static void main(String[] args) {
[Link](sqrt(25)); // simpler
[Link](pow(2,3));
}
}
✅ Advantage: Code becomes cleaner and shorter, especially when many static
methods are used repeatedly.

Part C: Long Answer / Application-


Based Questions
• 15. (a) Define a package named bank that contains classes Account and
Transaction. (b) Show how to compile, set CLASSPATH, and access these
classes from another package named customer.
• 16. Discuss in detail access control in packages with respect to public,
protected, default, and private access modifiers. Use example code to
explain visibility across packages and subclasses.
• 17. Explain naming conventions and best practices for designing packages
in large projects. Include examples that show hierarchical package naming
(like [Link]).

15. (a) Define a package named bank that contains classes Account and
Transaction. (b) Show how to compile, set CLASSPATH, and access these
classes from another package named customer.
(a) Defining the bank package
We can group all banking-related classes into one package called bank.
File 1: [Link]
package bank;
public class Account {
public void showAccount() {
[Link]("Bank Account Created Successfully!");
}
}
File 2: [Link]
package bank;

public class Transaction {


public void processTransaction() {
[Link]("Transaction Completed Successfully!");
}
}
Here, both classes belong to the same package bank.
(b) Accessing from another package (customer)
File 3: [Link]
package customer;
import bank.*; // importing all classes from bank package

public class Customer {


public static void main(String[] args) {
Account acc = new Account();
Transaction tr = new Transaction();

[Link]();
[Link]();
}
}

Steps to Compile and Run


1. Create folder structure:
2. bank/[Link]
3. bank/[Link]
4. customer/[Link]
5. Compile bank package:
6. javac -d . bank/[Link] bank/[Link]
7. Compile customer package:
8. javac -d . customer/[Link]
9. Set CLASSPATH (if needed):
10. set CLASSPATH=C:\MyJavaPrograms;
11. Run the program:
12. java [Link]
Output:
Bank Account Created Successfully!
Transaction Completed Successfully!
✅ Real-life example:
Think of bank as a folder that stores all the backend code for bank operations
(like Account and Transaction classes).
The customer package is like a user interface where customers can access and
use those services.

16. Discuss in detail access control in packages with respect to public,


protected, default, and private access modifiers. Use example code to
explain visibility across packages and subclasses.
Access control in Java defines which parts of your program can access a
particular class, method, or variable.
This is achieved using access modifiers — public, protected, default, and
private.

1. public
 The class or method can be accessed from anywhere — same package or

different package.
 Used when you want to make something fully visible.

Example:
package bank;
public class Account {
public void display() {
[Link]("This is a public method.");
}
}
package customer;
import [Link];

public class Test {


public static void main(String[] args) {
Account a = new Account(); // accessible
[Link]();
}
}
✅ Works fine because display() is public.
2. protected
 Accessible within the same package and also in subclasses of other

packages (using inheritance).


Example:
package bank;
public class Account {
protected void showBalance() {
[Link]("Balance is visible to subclass.");
}
}
package customer;
import [Link];

public class Customer extends Account {


public static void main(String[] args) {
Customer c = new Customer();
[Link](); // works because subclass inherits it
}
}
✅ Accessible because Customer extends Account.

3. default (no modifier)


 Accessible only inside the same package.

 Not accessible outside, even if it’s a subclass.

Example:
package bank;
class Account {
void info() {
[Link]("Default access: only inside bank package");
}
}
package customer;
import [Link]; // ❌ Error: Account is not public
public class Test {
public static void main(String[] args) {
Account a = new Account(); // Not accessible
}
}
❌ Error: Cannot access Account from outside the package.

4. private
 Accessible only within the same class — not even in the same package.

Example:
package bank;
public class Account {
private void details() {
[Link]("Private: Only inside Account class.");
}
public void callDetails() {
details(); // allowed inside the same class
}
}
✅ Only accessible from inside the Account class itself.

Summary Table
Subclass (Other
Modifier Same Class Same Package Other Packages
Package)
private ✅ ❌ ❌ ❌
default ✅ ✅ ❌ ❌
protected ✅ ✅ ✅ ❌
public ✅ ✅ ✅ ✅

✅ Real-life Example:
Think of a bank system —
 private → PIN number (only inside bank database)

 default → internal functions (bank employees only)


 protected → shared with partner banks (via inheritance)
 public → services available to all customers.

17. Explain naming conventions and best practices for designing packages in
large projects. Include examples that show hierarchical package naming.
1. Meaning of Package Naming
In large projects, packages are named in a hierarchical way to keep code
organized and avoid name clashes.
The structure usually follows reverse domain name notation.

2. Naming Convention Rules


1. Use all lowercase letters.
2. Use reverse domain name of your organization.
3. Separate words with dots (.) to represent hierarchy.
4. Be specific and meaningful.
Example:
[Link]
[Link]
[Link]
Here:
 com → company

 bankingsystem → project name

 customer, transaction, loans → modules.

3. Best Practices for Designing Packages


✅ (a) Organize by functionality
Group related classes together.
Example:
 [Link] → all student classes

 [Link] → all teacher-related classes

✅ (b) Keep package names short but clear


Avoid long or confusing names.
Use meaningful keywords like billing, orders, admin.
✅ (c) Follow consistency
Use the same pattern throughout the project.
✅ (d) Avoid naming conflicts
If multiple teams work on one project, assign unique base package names.
✅ (e) Use sub-packages for modules
Large projects should divide code into small, manageable sub-packages.

4. Example of Hierarchical Naming (Real-life Example)


Imagine an online shopping system for a company named “ShopEasy”:
[Link]
├── [Link]
├── [Link]
├── [Link]
├── [Link]
└── [Link]
Each module has its own code — making the system clean, reusable, and easy
to maintain.

✅ In simple words:
Just like we organize files in folders (Documents → College → BCA → Notes),
Java organizes code in packages → sub-packages → classes to keep large
programs tidy and understandable.

You might also like