Core Java Finale
Core Java Finale
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.
JDK Java Development Kit Used for developing Java programs (includes JRE + tools).
JRE Java Runtime Environment Used for running Java programs (includes JVM + libraries).
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.
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.
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.
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).
Example:
[Link]("Hello Java");
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
Interpreted
Python Executes line by line, slower Platform independent but slower
Language
7. Discuss the role of Just-In-Time (JIT) compiler in JVM. How does it improve Java’s performance
compared to purely interpreted languages?
It improves performance by converting bytecode into machine code at runtime (when the
program is running).
How it Works
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.
Comparison:
Type Example Performance
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++.
Garbage Collection (GC) in Java automatically removes unused objects from memory.
How it Works
Example:
class Example {
Benefits
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 is known as a secure language because it provides a safe environment to run programs without
harming the system.
1. No Pointers
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
Example:
Comparison:
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:
2. Object-Oriented:
4. Secure:
5. Rich Libraries:
6. Multithreading:
Weaknesses of Java
3. Verbose Syntax:
Comparison Table:
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.
Syntax Error Occurs when rules of the language are broken. Missing semicolon (;)
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.
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 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.
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.
Next, the programmer reads the error message or uses debugging tools to find the exact line
or section where the problem occurs.
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.
After fixing, the program is tested again with different inputs to confirm that the problem is
solved and no new bugs were created.
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:
🔹 1. ArithmeticException
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
🔹 2. NullPointerException
try {
String s = null;
[Link]([Link]());
} catch (NullPointerException e) {
[Link]("Object is null!");
🔹 3. ArrayIndexOutOfBoundsException
try {
[Link](arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
🔹 4. NumberFormatException
try {
} catch (NumberFormatException e) {
🔹 5. FileNotFoundException
Occurs when the program tries to open a file that doesn’t exist.
try {
} catch (FileNotFoundException e) {
}
✅ 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:
Example:
int total = 0;
total += i;
🔹 How It Helps
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:
🔹 How It Helps
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:
🔹 1. Syntax Error
These errors are detected by the compiler before running the program.
Example:
🔹 2. Runtime Error
Example:
int a = 10 / 0; // ArithmeticException
🔹 3. Logic Error
Example:
int a = 5, b = 10;
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.
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.
o Displays the current values of variables while the program runs — helpful to find
wrong data changes.
6. Error Console
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:
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.
Add simple print lines to check variable values and the flow of the program.
👉 Example:
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.
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.
You can check in the docs when errors like NullPointerException or FileNotFoundException may occur.
Java Docs and tutorials give sample programs showing how to use classes and methods correctly.
👉 Example: How to use Scanner or FileReader safely.
Docs also tell which methods are old or unsafe so you can use the latest ones.
👉 Example: Use [Link]() instead of FileReader.
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:
🔹 Step-by-Step Debugging:
2. Go to that Line
Check what variable is null.
Here, name is null.
6. Run Again
Now it prints the length successfully.
if (name != null) {
[Link]([Link]());
} else {
✅ 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:
1. What is wrong?
→ The total price is showing less than expected.
4. Why is it happening?
→ Maybe the discount is subtracted twice.
5. How to check?
→ Add print statements:
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.
Long: Explain the purpose of instance initializer blocks. Illustrate with a program using multiple constructors and a common initialization block.
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?
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.
Long: Create a class with multiple overloaded methods. Explain how Java resolves which method to call during runtime.
Long: Explain all types of static members in Java with suitable examples showing their behavior and usage.
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.
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.
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:
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);
// Creating objects
// Assigning values
[Link] = "Uzma";
[Link] = 22;
[Link] = "Fatima";
[Link] = 20;
// Display info
[Link]();
[Link]();
Explanation:
Student is a class.
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.
Short:
Medium:
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;
// Default constructor
Student() {
name = "Unknown";
age = 0;
// Parameterized constructor
Student(String n, int a) {
name = n;
age = a;
void display() {
Output:
Explanation:
Medium:
Meaning Used in same package & subclasses of other packages. Used 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.
1. public
2. protected
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 {
🧩 2. protected
Accessible within the same package and also in subclasses (even if they are in different packages).
✅ Example:
public class A {
}
}
Accessible only within the same package — not outside the package or in subclasses of another package.
✅ Example:
class A {
void msg() {
🧩 4. private
public class A {
📦 Package 1: pack1
// File: pack1/[Link]
package pack1;
public class A {
[Link]("Public Method");
[Link]("Protected Method");
void defaultMethod() {
[Link]("Default Method");
[Link]("Private Method");
}
public void showAll() {
[Link](publicVar);
[Link](protectedVar);
[Link](defaultVar);
[Link](privateVar);
📦 Package 2: pack2
// File: pack2/[Link]
package pack2;
import pack1.A;
[Link](publicVar); // ✅ Accessible
publicMethod(); // ✅ Accessible
package pack2;
import pack1.A;
public class C {
[Link]([Link]); // ✅ Accessible
[Link](); // ✅ Accessible
🧠 Summary Table:
Modifier Same Class Same Package Subclass (diff package) Other Package
private ✅ Yes ❌ No ❌ No ❌ No
💬 In Simple Words:
Example:
// File: pack1/[Link]
package pack1;
[Link](name + " " + marks + " " + age + " " + id);
}
// File: pack2/[Link]
package pack2;
import [Link];
Explanation:
Short:
👉 Example:
class Outer {
void show() {
}
}
class Test {
[Link]();
Medium:
class Outer {
void display() {
class Inner {
void msg() {
[Link]();
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:
o Used when inner class does not depend on outer class object.
2. Non-static Inner Class:
o Has no name.
Example:
class Outer {
class NonStaticInner {
void method() {
class MethodInner {
[Link]();
}
public class Main {
[Link]();
[Link]();
[Link]();
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:
Can have both abstract and normal methods. All methods are abstract (until Java 8).
Used for sharing common behavior. Used for enforcing common rules.
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:
Example:
void sleep() {
[Link]("Sleeping...");
void sound() {
[Link]("Bark!");
}
public class Main {
[Link]();
[Link]();
🔹 Interface:
Used when different classes share common behavior but are not related.
Example:
interface Vehicle {
void start();
}
class Car implements Vehicle {
[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.
Short:
Code Example:
class Calculator {
[Link](a + b);
[Link](a + b);
[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) {
void show(String s) {
void show(double d) {
[Link](10);
[Link]("Hello");
[Link](3.14);
Short:
Code Example:
class Demo {
[Link]("Hello!");
[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 {
Long:
Code Example:
class Example {
static int count;
int id;
static {
count = 0;
Example(int id) {
[Link] = id;
count++;
[Link]();
}
Short:
Medium:
Code Example:
class Student {
String name;
int age;
Student() {
this("Unknown", 18);
[Link] = age;
Long:
Code Example:
class Demo {
int a;
Demo(int a) {
this.a = a;
Demo() {
this(100);
}
void display() {
void test() {
show(this);
[Link]();
[Link]();
Medium:
Code Example:
Long:
Code Example:
class Test {
[Link]("Object destroyed!");
t1 = null;
[Link]();
9. Generics in Java
Short:
Medium:
Code Example:
class Box<T> {
T value;
[Link] = value;
T get() {
return value;
[Link]("Hello");
[Link]([Link]());
[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:
K key;
V value;
[Link] = key;
[Link] = value;
void show() {
[Link]();
[Link]();
Short:
Medium:
Long:
Comparison Table:
Feature Abstract Class Interface
Code Example:
interface Flyable {
void fly();
}
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).
5. Name any two Java primitive data types and mention their size.
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:
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:
2. Compilation:
The Java compiler (javac) converts the human-readable source code into bytecode, stored in
a .class file.
👉 Example: javac [Link] → creates [Link]
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
Program Output
Real-Life Example:
The chef (JVM) reads your recipe and cooks (executes) it into a ready meal (output).
Code Example:
class Hello {
[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):
4. Main Method:
The entry point of the program.
public static void main(String[] args) { ... }
Code Example:
Output Example:
Welcome, Uzma!
Real-Life Example:
Explanation:
Java Runtime
JRE Used to run Java programs JVM + Libraries
Environment
Diagram:
JDK
├── JRE
│ ├── JVM
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:
4. Discuss the rules and naming conventions for Identifiers in Java. Provide examples of valid and
invalid identifiers.
Explanation:
Naming Conventions:
Examples:
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:
1. Integer Literal
2. Floating-Point Literal
3. Character Literal
4. String Literal
5. Boolean Literal
6. Null Literal
Represents no value.
Example:
🧠 Real-life example: If you don’t have a middle name, its value can be null.
Summary Table:
Explanation:
Comparison Table:
Definition Used to store whole numbers Used to store numbers with decimals
Size Range From 1 byte (byte) to 8 bytes (long) float = 4 bytes, double = 8 bytes
Use Case Counting people, items, or things Measuring weight, height, or distance
Real-Life Example:
Code Example:
int students = 25; // Integer
Output:
Students: 25
7. Describe the Types of Comments Supported by Java and Explain Their Significance with
Examples
Explanation:
1. Single-line Comment
[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 */.
*/
3. Documentation Comment
* @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.
Default
Type Size Example Description
Value
byte 1 byte 0 byte age = 20; Small integers (range: -128 to 127)
long phone =
long 8 bytes 0L Large integers
9876543210L;
(logical)
Code Example:
class DataTypes {
Output:
Age: 22
Weight: 45.6
Grade: A
Passed: true
Real-Life Example:
double → temperature
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
+ 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
== Equal to 5 == 5 true
Code Example:
` ` Logical OR
Code Example:
[Link](!a); // false
Real-Life Example:
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.
4 +, - Addition, Subtraction
Precedence Level Operator Description
6 ==, != Equality
8 `
Code Example 1:
int result = 10 + 5 * 2;
[Link](result);
Explanation:
* has higher precedence than +.
→ 5 * 2 = 10, then 10 + 10 = 20
Output: 20
[Link](result);
Explanation:
Parentheses change order → 10 + 5 = 15, then 15 * 2 = 30
Output: 30
Real-Life Example:
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.
1. Code Reusability: You can use existing class features in a new class.
Example:
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.
When a subclass automatically gets the variables (data members) of its parent class.
Example:
class Animal {
int legs = 4;
void show() {
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).
Benefits of Inheritance:
1. Code Reusability – You don’t need to write the same code again and again.
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...");
void display() {
Output:
Vehicle starts...
Car is ready to drive!
Explanation:
Explanation:
Java supports different forms of inheritance based on how classes are connected.
1. Single Inheritance
Parent
Child
Example:
class 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 {}
3. Hierarchical Inheritance
Parent
/ \
Child1 Child2
Example:
class Animal {}
Interface1 Interface2
\ /
\ /
\ /
Class
Example:
interface Animal {}
interface 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...");
void study() {
[Link]("Student is studying...");
Output:
Person is eating...
Student is studying...
Explanation:
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:
Private members are not inherited directly, but can be accessed through public methods of the
superclass.
Example:
class Employee {
void work() {
void showDetails() {
[Link]();
Output:
Company: TechCorp
Language: Java
Explanation:
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() {
Child() {
Output:
Explanation:
When Child object is created, first Parent() runs automatically (because of super()), then the
Child() constructor.
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() {
void sound() {
[Link]("Dog barks");
[Link]();
}
Output:
Dog barks
Explanation:
The [Link]() statement allows the child to still access the original parent behavior.
Real-Life Example:
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() {
void sound() {
[Link]("Dog barks");
}
}
void sound() {
[Link]("Cat meows");
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.
execution.
Overloading multiple methods with same name but Overriding a parent method in
Example
different parameters. subclass.
class MathOperation {
return a + b;
return a + b;
class Vehicle {
void run() {
[Link]("Vehicle is running");
void run() {
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.
Program:
class Parent {
void show() {
void show() {
void childMethod() {
// Downcasting
Child c = (Child) p;
Output:
Explanation:
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;
[Link] = name;
[Link] = age;
void showDetails() {
String course;
super(name, age);
[Link] = course;
}
void showDetails() {
[Link]("Student Name: " + name + ", Age: " + age + ", Course: " + course);
double salary;
super(name, age);
[Link] = salary;
void showDetails() {
[Link]("Employee Name: " + name + ", Age: " + age + ", Salary: " + salary);
[Link]();
[Link]();
}
}
Output:
Explanation:
Based on the object type (Student/Employee), the correct version runs at runtime.
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:
Example:
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:
// Storing values
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
}
}
Output:
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).
Dynamic You declare an array first and assign values int marks[] = new int[5];
Initialization later using indexes. marks[0] = 60;
Example:
Static Initialization
Dynamic Initialization
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.
int sum = 0;
Output:
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.
Definition:
A String in Java is a sequence of characters enclosed in double quotes " ".
Example:
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";
[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()).
int count = 0;
count++;
Output:
Explanation:
The loop goes through each character and increases the counter.
We didn’t use [Link]() — instead, we counted manually.
Memory Creates new object when changed. Uses same object for changes.
Example:
[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.
largest = arr[i];
smallest = arr[i];
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:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
[Link]("3x3 Matrix:");
[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.
Output:
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:
Example:
Output:
Substring: Java
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:
int count = 0;
str = [Link]();
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:
[Link]("Programming Languages:");
[Link](t);
Output:
Programming Languages:
Java
Python
C++
JavaScript
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:
rev += [Link](i);
if ([Link](rev))
else
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:
second = first;
first = num;
second = num;
Output:
Theory:
Matrix addition means adding the elements of two matrices at the same position.
Example:
int[][] A = {{1,2,3},{4,5,6},{7,8,9}};
int[][] B = {{9,8,7},{6,5,4},{3,2,1}};
}
[Link]("Matrix Addition:");
[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:
char ch = [Link](i);
if ([Link](ch) == -1)
result += ch;
Output:
18. Explain the difference between String, StringBuffer, and StringBuilder with examples.
Theory:
String Immutable (cannot be changed) Yes Slow When data won’t change
Example:
String s = "Hello";
[Link](s); // Hello
[Link](" Java");
[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:
int count = 1;
if (words[i].equals(words[j])) {
count++;
if (words[i] != "0")
Output:
Java = 2
is = 2
fun = 1
and = 1
powerful = 1
Example:
import [Link];
[Link](names);
[Link]("Sorted Strings:");
[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.
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.
8. Write a Java program to demonstrate the use of multiple catch blocks and explain
how Java handles multiple exceptions.
10. Discuss best practices for handling exceptions in Java. Explain why proper
exception handling is important for secure and reliable applications.
Short Questions
3. What are checked and unchecked exceptions? Give one example of each.
5. What is the difference between the throw and throws keywords in Java?
// 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!");
}
}
}
class Example {
static void checkAge(int age) throws IOException {
if (age < 18)
throw new IOException("Not eligible!");
else
[Link]("Eligible!");
}
✅ 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.
Program Example:
class MultipleCatchExample {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int result = a / b; // ArithmeticException
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.
Example Program:
// Step 1: Create a custom exception
class AgeInvalidException extends Exception {
public AgeInvalidException(String message) {
super(message);
}
}
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.
6. Log Exceptions
Use logging ([Link] or log4j) to record exceptions for analysis.
catch (IOException e) {
[Link]([Link]()).log([Link], null, e);
}
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.
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
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 { }
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.
2. Faster response – The program remains active and doesn’t freeze while doing heavy work.
[Link]();
JVM waits for them to finish before JVM does not wait for them; they stop automatically when user
ending. threads finish.
[Link](8);
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.
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.
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.
2. Runnable State:
o Method: [Link]();
3. Running State:
o JVM decides which thread will run first (based on scheduling and priority).
o The thread is temporarily inactive or waiting for another thread to complete its task
or resource.
New
↓ (start())
Runnable
↓ (JVM scheduler)
Running
↑ ↓
↓ ↑
Waiting
↓ (notify()/resume())
Runnable
↓ (run() completed)
Terminated
Example Program:
[Link]("Thread is running...");
[Link]("Thread started...");
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.
Example:
[Link]("Playing music...");
[Link]("Downloading file...");
class MultithreadExample {
[Link]();
[Link]();
Output:
Playing music...
Downloading file...
Playing music...
Downloading file...
Example:
[Link]("Thread is running...");
}
}
Example:
[Link]();
Difference:
Meaning:
Default Priorities:
MIN_PRIORITY = 1
NORM_PRIORITY = 5 (default)
MAX_PRIORITY = 10
Effect on Scheduling:
However, thread scheduling depends on the JVM and operating system, so it’s not
guaranteed.
Example:
[Link](Thread.MIN_PRIORITY);
[Link](Thread.NORM_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
[Link]();
}
Output (May vary):
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 {
try {
[Link](1000);
} catch (Exception e) {}
[Link]("Withdraw successful!");
Bank b;
Customer(Bank b) { this.b = b; }
}
class SyncExample {
[Link]();
[Link]();
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().
Example Program:
class Message {
try {
[Link]("Producing message...");
flag = true;
} catch (Exception e) { }
try {
[Link]("Consuming message...");
if (flag) {
} catch (Exception e) { }
}
class Communication {
[Link]();
[Link]();
Output:
Producing message...
Consuming message...
Explanation:
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.
Switching between processes is slower because each has its own memory space.
Example:
Running a music player, a browser, and a text editor at the same time on your computer.
Comparison Table
Crash Impact One thread crash affects all threads One process crash does not affect others
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()
2. yield()
Used to temporarily pause the current thread to give other threads a chance to execute.
However, it does not guarantee that another thread will run immediately.
[Link]();
3. join()
4. interrupt()
It doesn’t stop the thread directly but sends a signal that it should stop.
[Link]();
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.
class Counter {
int count = 0;
void increment() {
count++;
});
});
[Link]();
[Link]();
[Link]();
[Link]();
}
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;
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 {
while (!empty) {
empty = false;
msg = m;
notify();
}
public synchronized void read() {
while (empty) {
empty = true;
notify();
});
});
[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
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.
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;
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.
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
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];
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;
[Link]();
[Link]();
}
}
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];
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)
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.
✅ 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.