C Programming Language Assignment
C Programming Language Assignment
47(iv)
Important Instructions
Assignment – 01
Q1. Java is often described as "Write Once, Run Anywhere." Explain this
concept in detail. Discuss the role of the Java Compiler and the Java
Virtual Machine (JVM) in achieving this feature.
Ans.
Java is widely recognized for its powerful slogan “Write Once, Run
Anywhere” (WORA). This phrase represents one of Java’s core strengths
—platform independence. It means that a Java program, once written
and compiled, can run on any device or operating system that has a Java
Virtual Machine (JVM), without requiring the programmer to rewrite or
recompile the code for each platform.
1. Java Compiler
This is the first key step towards achieving WORA. Bytecode acts like a
bridge between human-readable code and machine-specific instructions.
This architecture ensures that the same .class file can be run
unchanged on any machine that has a compatible JVM.
Thus, the JVM is the engine that translates universal Bytecode into
platform-specific execution, completing the WORA promise.
Benefits of WORA
Conclusion
Ans.
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction
Definition:
Encapsulation is the mechanism of binding data (variables) and
methods (functions) that operate on the data into a single unit
(class) and restricting direct access to some of the object’s components.
Real-world analogy:
Think of a capsule or medicine tablet. The medicine (data) is hidden
inside the capsule, and the patient just consumes the capsule without
knowing the complex formulation inside. Similarly, in a car, you press the
accelerator, but you don’t need to know the internal mechanism of the
engine to make the car move.
Purpose:
Definition:
Inheritance allows a new class (subclass/child) to acquire the
properties and behaviors (fields and methods) of an existing class
(superclass/parent). In Java, this is achieved using the extends keyword.
Real-world analogy:
Consider a family tree. A child inherits traits from their parents. For
example, a sports car is a type of car, so it inherits basic functionalities
like steering, brakes, etc., but can also have additional features like turbo
mode.
Purpose:
Definition:
Polymorphism allows objects to be treated as instances of their parent
class rather than their actual class. It enables a single action to
behave differently based on the object that performs it.
Real-world analogy:
A person can behave differently in different roles—a man can be a
father, a son, a teacher. Each role demands different behavior.
Similarly, the method draw() can behave differently in a class Circle,
Rectangle, or Triangle.
Purpose:
Enhances flexibility
Definition:
Abstraction means hiding the complex implementation details and
showing only the essential features of the object. In Java, abstraction
is achieved using abstract classes and interfaces.
Real-world analogy:
When you use a TV remote, you just press buttons to change channels or
volume—you don’t know (or need to know) how the remote communicates
with the TV internally. The interface (remote) is abstracted from its
complex inner workings.
Purpose:
Reduces complexity
Conclusion
Encapsulatio
Hides data inside a class Capsule or car engine
n
TV remote or car
Abstraction Shows only necessary details
dashboard
Q3. Compare and contrast the concepts of an abstract class and an
interface in Java. Highlight their similarities, differences, and typical use
cases in Java application design.
Ans.
Constructor
Can have constructors. Cannot have constructors.
s
✅ Similarities
✅ Use Cases
Choose Abstract
Use Case Choose Interface
Class
Representing common
behavior across unrelated No Yes
classes
Choose Abstract
Use Case Choose Interface
Class
No (only single
Yes (multiple interfaces
Need multiple inheritance inheritance
can be implemented)
allowed)
✅ Example Analogy
✅ Conclusion
Both abstract classes and interfaces are essential tools in Java's OOP
toolkit. Use abstract classes when you're working with closely related
classes with shared logic, and use interfaces when you're defining a
common contract across unrelated classes or need to support
multiple inheritance.
Assignment – 02
Ans.
Heap Memory
Stack Memory
Method Area
But, for most programming concerns, the Heap and Stack are the main
areas.
2. Heap Memory
Definition:
The Heap is the runtime memory area where Java objects are stored. It is
a shared memory area and is used for dynamic memory allocation. Every
time you create a new object, it is stored in the heap.
Characteristics:
Managed by the JVM: The JVM allocates memory from the heap
when you create objects and deallocates memory when objects are
no longer in use, through Garbage Collection.
Large and slower: The heap is generally much larger than the
stack, but accessing it is slower because it involves searching for
free memory spaces.
Memory fragmentation: The heap can get fragmented if memory
is frequently allocated and deallocated, which may affect
performance over time.
3. Stack Memory
Definition:
The Stack is the memory area where method calls and local variables are
stored. The stack follows the Last In, First Out (LIFO) principle,
meaning that the most recently used data is popped off first.
Characteristics:
Small and fast: The stack is smaller than the heap but faster to
access. This is because the stack works with a predefined memory
structure and doesn’t require searching for free spaces.
Stores primitive data types: Local variables (like int, float, etc.)
and references to objects are stored in the stack.
o Method arguments
4. Garbage Collection
Definition:
Garbage Collection (GC) is a process by which the JVM automatically
identifies and reclaims memory that is no longer in use. It frees up heap
space by clearing objects that are no longer referenced by any part of
the program.
How it works:
Types of GC:
Major GC: Occurs in the Old generation and can be slower because
it collects a larger set of objects.
Full GC: Involves cleaning the entire heap, including both the Young
and Old generations.
Example:
1. Object Usage:
After creation, the object’s methods and fields can be accessed. A
reference to the object is stored in the stack (as a local variable or
instance variable), but the actual data is stored in the heap.
3. Garbage Collection:
The JVM periodically checks for unreachable objects. When an object
is no longer referenced, the garbage collector deallocates
memory used by the object, freeing up space in the heap.
4. Finalization (Optional):
Before the object is completely removed, Java provides a finalize()
method (deprecated in recent versions) that allows developers to
clean up resources. However, reliance on finalization is discouraged
due to its unpredictability.
Ans.
Try-Catch-Finally Mechanism
1. try Block:
The try block is used to wrap the code that might throw an
exception. It tells the JVM, "Try to execute this block of code, and if
an exception occurs, jump to the catch block."
2. catch Block:
The catch block is used to catch and handle the exception that is
thrown in the try block. It specifies the type of exception to catch
and provides a place to handle the error, such as logging the error
or providing a meaningful message to the user.
3. finally Block:
The finally block contains code that is always executed after the try
block, whether an exception occurred or not. This block is used to
release resources (like file handles, database connections, or
network resources) and perform cleanup tasks.
Syntax:
try {
} finally {
Example:
try {
} catch (ArithmeticException e) {
} finally {
Key Points:
1. Checked Exceptions
Common Examples:
o IOException
o SQLException
o FileNotFoundException
When to Use:
Example:
// Further code
2. Unchecked Exceptions
Common Examples:
o NullPointerException
o ArrayIndexOutOfBoundsException
o ArithmeticException
When to Use:
Example:
Handling
Must be handled using
Requireme Optional to handle.
try-catch or throws.
nt
IOException, NullPointerException,
Examples SQLException, ArithmeticException,
FileNotFoundException. ArrayIndexOutOfBoundsException.
Conclusion
Ans.
1. Improved Performance:
4. Responsive UI:
5. Concurrency:
o Multithreading is essential in building applications that require
concurrency, such as web servers, game engines,
database management systems, and real-time
applications.
A thread in Java goes through various stages during its lifetime. The
thread lifecycle consists of several states, and the thread transitions
from one state to another depending on the execution flow.
States of a Thread:
A thread can exist in one of the following states during its lifecycle:
1. New (Born):
Blocked:
The thread will remain blocked until the resource becomes available.
Waiting:
A thread enters the Waiting state when it is waiting indefinitely for
another thread to perform a particular action (like completing a
task).
synchronized (obj) {
obj.wait();
Timed Waiting:
This state allows the thread to resume after the time elapses.
Terminated (Dead):
| |
Terminated (Dead)
Consider a scenario where two threads try to update the same bank
account balance simultaneously. Without synchronization, one thread
might read the balance, and before it writes the new balance, the second
thread may also read the balance and overwrite it, causing data
corruption.
1. Synchronized Methods:
this.balance += amount;
Synchronized Blocks:
synchronized (this) {
this.balance += amount;
java
Copy
Edit
lock.lock();
try {
// Critical section
} finally {
lock.unlock();
Volatile Keyword:
java
Copy
Edit
This guarantees that changes to the variable are visible to all threads, but
it does not provide full synchronization for method execution.
Conclusion