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

Java 1

The document discusses key concepts of Object-Oriented Programming (OOP) in Java, including encapsulation, inheritance, polymorphism, and abstraction. It explains the differences between Object-Oriented Programming (OOP) and Procedure-Oriented Programming (POP), as well as the roles of classes and objects. Additionally, it covers Java-specific features such as the Java Virtual Machine (JVM), garbage collection, and thread management.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views34 pages

Java 1

The document discusses key concepts of Object-Oriented Programming (OOP) in Java, including encapsulation, inheritance, polymorphism, and abstraction. It explains the differences between Object-Oriented Programming (OOP) and Procedure-Oriented Programming (POP), as well as the roles of classes and objects. Additionally, it covers Java-specific features such as the Java Virtual Machine (JVM), garbage collection, and thread management.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java 2022 OOP

Q3. (a) What do you mean by POP (Procedure (Object


encapsulation? Basis Oriented Oriented
Encapsulation is one of the four
Programming) Programm
fundamental OOP principles. It is the
mechanism of wrapping data (variables) ing)
and the methods (functions) that operate Approa Top-down Bottom-up
on data together as a single unit called a
class. It restricts direct access to some of
ch approach approach
an object's components, which is known Focus on Focus on
as data hiding.
Focus functions/proce objects
Key features of Encapsulation:
• Variables of a class are hidden from dures and data
other classes using private access More
modifier.
• These variables can only be secure
accessed through public getter and Data Less secure (data
setter methods. Securit (data is hiding
• It provides data security and prevents
y exposed) using
misuse of data.
Example: encapsulat
public class BankAccount { ion)
private double balance; // hidden
Data and
public void deposit(double amount) { Data Data and
balance += amount; } functions
Handlin functions are
public double getBalance() { return balance; are
g separate
} // controlled access combined
}
Reusabi Less code High code
(b) Write the basic difference between
class and object. lity reusability reusability
Basis Class Object Exampl C++, Java,
C
Blueprint es Python
Instance of a
Definition or (b) Why is Java a robust programming
class
template language?
Logical Physical/real- Java is called robust because it
Nature eliminates many error-prone situations:
entity world entity
• Strong Type Checking: Java checks
Does not Occupies
the data type at compile time and
Memory occupy memory
runtime.
memory when created • No Pointers: Java does not use
Defines Uses explicit pointers, eliminating pointer-
properties properties related errors.
Purpose • Garbage Collection: JVM
and and methods
methods of class automatically frees unused memory.
• Exception Handling: Java has a
Car comprehensive mechanism to handle
Specific car
Example (design of runtime errors.
(e.g., Red car)
a car) • Memory Management: Java
Q4. (a) Write the difference between prevents memory leaks through
Procedure Oriented Programming automatic management.
(POP) and Object Oriented Q5. Explain any two features of OOPs:
Programming (OOP). (a) Polymorphism (b) JVM (c)
Abstraction (d) Platform Independent
(a) Polymorphism Name of the method; it is the
Polymorphism means 'many forms'. main starting point of program
It allows one interface to be used for execution.
a general class of actions. In Java,
Data type; used to store a
polymorphism is of two types: String
• Compile-
sequence of characters (text).
time(Static)Polymorphism: Array of String; used to store
Achieved through method args[] command-line arguments passed
overloading — same method name to the program.
with different parameters.
• Runtime (Dynamic)
(b) What do you understand by
Polymorphism: Achieved through
wrapper class?
method overriding — subclass
A wrapper class is a class that wraps
provides specific implementation of
(encapsulates) a primitive data type into an
superclass method.
object. Java provides a wrapper class for each
(b) JVM (Java Virtual Machine)
JVM is an abstract machine that provides primitive type.
a runtime environment to execute Java Primitive Wrapper Class
bytecode. It is the foundation of Java's
int Integer
'Write Once, Run Anywhere' principle.
• JVM converts bytecode (.class file) float Float
into machine-specific code.
char Character
• It manages memory through garbage
collection. boolean Boolean
• JVM is platform dependent, but Java
double Double
programs are platform independent
because of JVM. long Long
(c) Abstraction Uses:
Abstraction is a concept of Object Oriented
• Required when working with
Programming (OOP) that means hiding the
internal implementation details and showing collections (e.g., ArrayList)
only the essential features of an [Link] helps • Used for type conversion (e.g.,
to reduce complexity and increases security by [Link]())
allowing the user to access only necessary • Allows primitives to be treated as
information. objects
Example: When we use a car, we only know
Example:
how to drive it (steering, brake, accelerator),
but we do not know the internal working of the int x = 10;
engine. Integer obj = [Link](x); // Boxing
Q6. (a) Explain the meaning of each int y = [Link](); // Unboxing
word of the line: public static void String s = [Link](x); // Conversion
main(String args[])
Q7. (a) What do you understand by
Access modifier; it means the Garbage Collection?
Garbage Collection (GC) is the process by
public method can be accessed from which Java automatically reclaims memory
anywhere. occupied by objects that are no longer in use
or referenced. The JVM runs a garbage
It belongs to the class, not to
collector that periodically frees unreferenced
static objects; can be called without objects from the heap memory.
creating an object. • Programmer does not need to explicitly
free memory (unlike C/C++).
Return type; it means the method • The finalize() method is called by GC just
void
does not return any value. before destroying an object.
• [Link]() can be called to request Example:
garbage collection, but it is not class Student {
guaranteed.
(b) Write the uses of final keyword in int rollNo;
Java. String name;

The final keyword in Java is used to restrict Student(int r, String n) { // Constructor


modification. It can be applied to variables, rollNo = r;
methods, and classes. name = n;
1. Final Variable:
}
• A variable declared as final cannot
be changed once initialized. }
• It becomes a constant. // Usage
• Example: Student s = new Student(1, "Ram"); //
Constructor called automatically
final int x = 10; // value cannot be changed
Q8. (b) Method Overloading and Method
2. Final Method:
Overriding
• A method declared as final cannot
be overridden by subclasses.
• Ensures the original Method Overloading:
implementation remains Method overloading occurs when two or
unchanged. more methods in the same class have the
• Example: same name but different parameters (type,
number, or order). It is resolved at compile
final void show() {
[Link]("Final
time (static polymorphism).
method"); Example:
} class Calculator {
int add(int a, int b) { return a + b; }
3. Final Class: double add(double a, double b) { return
• A class declared as final cannot be a + b; }
extended (inherited).
int add(int a, int b, int c) { return a + b +
• Prevents inheritance.
• Example:
c; }
final class Test { }
} Method overriding:
Q8. (a) What is constructor? Method overriding occurs when a subclass
A constructor is a special method that is provides a specific implementation of a
automatically called when an object is method that is already defined in its
created. It has the same name as the class superclass. The method signature must be
and does not have any return type (not the same. It is resolved at runtime
even void). Its main purpose is to initialize (dynamic polymorphism).
the object. Example:
Properties of Constructor: class Animal {
• Same name as the class void sound() {
• No return type [Link]("Animal makes
• Called automatically when an sound");
object is created using new }
• Can be overloaded (multiple }
constructors with different
parameters) class Dog extends Animal {
void sound() { // Overriding
[Link]("Dog barks"); Subclasses that extend an abstract class must
} provide implementations for all its abstract
} methods.
Example:
Q9. (a) What is Inheritance?
Inheritance is a mechanism in Java by
abstract class Shape {
which one class (subclass/child class) abstract double area(); // abstract method
acquires the properties and behaviors of
another class (superclass/parent class). It void display() { // concrete method
promotes code reusability and establishes [Link]("I am a shape");
}
an IS-A relationship.
}
Example:
class Dog extends Animal { } // Dog IS-A class Circle extends Shape {
Animal double r;
(b) Describe different forms of
inheritance with block diagram. Circle(double r) {
this.r = r;
Java supports the following types of
}
inheritance:
• Single Inheritance: One subclass double area() { // implementation of
inherits from one superclass. abstract method
A -> B (B extends A) return 3.14 * r * r;
• Multilevel Inheritance: A class }
inherits from a class which itself }
inherits from another class. (b) Write the difference between
A -> B -> C (B extends A, C interface and abstract class
extends B) Abstract
Basis Interface
• Hierarchical Inheritance: Multiple Class
subclasses inherit from one A class
superclass. that can
A blueprint
A have
that contains
/\ both
Definition only abstract
B C (Both B and C extend A) abstract
methods (by
and
• Multiple Inheritance: NOT directly default)
supported in Java with classes to concrete
avoid the Diamond Problem. methods
Achieved using interfaces. abstract
Keyword interface
A B class
\/ Both
Only abstract
C (NOT possible with classes; use methods (Java
abstract
interface) Methods and non-
8+ allows
• Hybrid Inheritance: Combination of abstract
default/static)
two or more types. Achieved in Java methods
using interfaces. Can have
Public, static,
any type
Variables and final by
Q10. (a) What is an Abstract Class? of
default
An abstract class is a class declared with the variables
abstract keyword. It cannot be instantiated, Construct
Not allowed Allowed
meaning objects cannot be created directly ors
from it. It may contain both abstract methods Does not
Supports
(methods without a body) and concrete Inheritan support
multiple
methods (methods with a body). ce multiple
inheritance
inheritan
Abstract Demo d = new Demo();
Basis Interface try {
Class
ce (with [Link]();
classes) } catch (IOException e) {
[Link]("Caught:"+
Implemented Extended
Impleme using using [Link]());
ntation implements extends }
keyword keyword }
Used for
}
Used for full partial Q12. (a) How can we create a thread?
Use
abstraction abstracti
on A thread in Java can be created in two
Q11. (a) Checked and Unchecked ways:
Exceptions 1. By extending the Thread class:
class MyThread extends Thread {
Checked Exception: public void run() {
[Link]("Thread running
Checked exceptions are those
via Thread class");
exceptions that are checked at compile-
}
time. The programmer must handle them
}
using try-catch or declare them using
throws.
Examples: IOException, // Start thread
FileNotFoundException, SQLException MyThread t = new MyThread();
[Link]();
Unchecked Exception: 2. By implementing the Runnable
Unchecked exceptions are those interface:
exceptions that occur at runtime and are class MyRunnable implements Runnable {
not checked at compile-time. They are public void run() {
subclasses of RuntimeException. [Link]("Thread running
Examples: ArithmeticException, via Runnable");
NullPointerException, }
ArrayIndexOutOfBoundsException }

Q11. (b) Use of throws Statement // Start thread


The throws keyword is used in a Thread t = new Thread(new
method declaration to specify that the MyRunnable());
method may throw one or more [Link]();
exceptions. It informs the caller of the
method to handle these exceptions. Q12. (b) Life Cycle of a Thread (with
It is mainly used for checked exceptions. Diagram)
Example:
import [Link].*; A thread passes through different states
during its lifecycle:
class Demo {
New → Runnable → Running → Blocked/Waiting →
void readFile() throws IOException {
Terminated
FileReader f = new ↑ ↓
FileReader("[Link]"); └──── back to Runnable ─┘
// Exception is passed to the caller
} States Explanation:
• New: Thread object is created but
public static void main(String[] args) { start() is not called.
• Runnable: After calling start(), • getPriority() → Returns the
thread is ready and waiting for priority of a thread
CPU. • setPriority(int p) → Sets the
• Running: Thread is executing the priority of a thread
run() method. Example:
• Blocked/Waiting: Thread is Thread t = new Thread();
paused due to sleep(), wait(), or [Link](Thread.MAX_PRIORITY);
I/O. It returns to Runnable after
completion. [Link]([Link]()); //
• Terminated (Dead): Thread Output: 10
execution is finished.
Q14. Write a Java program that
Q13. (a) What is Thread changes all characters to upper case
Synchronization? present in the file '[Link]' and puts
it into the '[Link]' file and displays
Thread Synchronization is the process of the content of '[Link]'.
controlling access of multiple threads to ANS:
shared resources. When multiple threads import [Link].*;
access the same resource simultaneously,
it may cause data inconsistency. class UpperCaseFile {
Synchronization ensures that only one public static void main(String[] args)
thread can access the shared resource at a throws Exception {
time. BufferedReader br = new
It is achieved using the synchronized BufferedReader(new
keyword. FileReader("[Link]"));
Example: BufferedWriter bw = new
class Counter { BufferedWriter(new
int count = 0; FileWriter("[Link]"));

synchronized void increment() { // Only String line;


one thread at a time while ((line = [Link]()) != null) {
count++; [Link]([Link]());
} [Link]();
} }
The synchronized keyword creates a lock
(monitor) on the object. When one thread [Link]();
acquires the lock, other threads must wait [Link]();
until the lock is released.
// Display content
Q13. (b) What is Thread Priority? br = new BufferedReader(new
FileReader("[Link]"));
Each thread in Java has a priority that while ((line = [Link]()) != null) {
determines the order of execution by the [Link](line);
CPU. Thread priority values range from 1 to }
10. [Link]();
• Thread.MIN_PRIORITY = 1 }
• Thread.NORM_PRIORITY = 5 }
(default)
• Thread.MAX_PRIORITY = 10 Java 2023
Methods:
Q2. (a) public static void main(String 2. Multilevel Inheritance:
args[]) — Write down the meaning of Inheritance in multiple levels (chain).
each word. [Animal]
Access modifier; it means the |
[Mammal]
public method can be accessed from
|
anywhere.
[Dog]
It belongs to the class, not to 3. Hierarchical Inheritance:
static objects; can be called without Multiple classes inherit from one parent.
creating an object. [Animal]
/ \
Return type; it means the method
void [Dog] [Cat]
does not return any value.
4. Multiple Inheritance (via Interface):
Name of the method; it is the A class implements multiple interfaces.
main starting point of program [Flyable] [Swimmable]
execution. \ /
[Duck]
Data type; used to store a
String 5. Hybrid Inheritance:
sequence of characters (text).
Combination of two or more types of
Array of String; used to store inheritance (achieved using interfaces in
args[] command-line arguments passed Java).
to the program. Q3. (a) What is constructor? What are
its special properties?
(b)What will happen if static modifier is A constructor is a special member
method that is automatically invoked
removed from the signature of main
when an object is created. It is used to
method? initialize the state (data members) of the
object.
If static is removed from main()
Special Properties of Constructor:
If the static keyword is removed, the
program will compile successfully but will • Has the same name as the class.
give a runtime error: • Does not have a return type (not even
void).
Error: Main method is not static in class • Is called automatically when an
Demo, object is created using 'new'.
please define the main method as: • Cannot be static, final, abstract, or
public static void main(String[] args) synchronized.
• Can be overloaded (constructor
Reason: overloading).
The JVM calls main() without creating an
• If no constructor is defined, Java
object. A non-static method requires an
provides a default constructor.
object, so the JVM cannot execute it.
(b) Discuss different types of
(c) Explain different forms of
constructors with examples.
inheritance with suitable diagrams.
1. Default Constructor:
1. Single Inheritance: • A constructor with no parameters
One class inherits from one parent class. • Provided automatically by the
[Animal] compiler if no constructor is
| defined
[Dog] Example:
class Demo {
int x; single interface/method name to
represent different behaviors.
Demo() { // Default constructor
Types: Compile-time
x = 0;
polymorphism (Method
}
Overloading) and Runtime
}
polymorphism (Method Overriding).
2. Parameterized Constructor:
• A constructor that accepts (b) Explain dynamic method
parameters
dispatch in method overriding
• Used to initialize objects with
specific values
with proper example.
Example: Dynamic Method Dispatch is the
class Student { mechanism by which a call to an
overridden method is resolved at
int roll;
runtime rather than compile time. It is
String name;
the basis of runtime polymorphism.
When a superclass reference variable
Student(int r, String n) { refers to a subclass object, the
roll = r; overridden method of the subclass is
name = n; called at runtime
}
} class Animal {
void sound() {
Student s = new Student(1, "Alice"); [Link]("Animal makes
3. Copy Constructor: sound");
• A constructor that creates a new }
object by copying another object }
• Not built-in in Java, but can be
defined by the programmer class Dog extends Animal {
Example: void sound() {
class Point { [Link]("Dog: Woof!");
int x, y; }
}
Point(int a, int b) {
x = a; class Cat extends Animal {
y = b; void sound() {
} [Link]("Cat: Meow!");
}
Point(Point p) { // Copy constructor }
x = p.x;
y = p.y; class Test {
} public static void main(String[] args) {
} Animal a; // Superclass reference

Point p1 = new Point(3, 4); a = new Dog();


Point p2 = new Point(p1); // Copy of p1 [Link](); // Output: Dog: Woof!

Q4. (a) What is polymorphism? a = new Cat();


Polymorphism (Greek: 'many forms') [Link](); // Output: Cat: Meow!
is the ability of an object to take on }
many forms. In Java, it allows a }
(c) How does method • finally: Always executes
overloading differ from method (whether exception occurs or not).
overriding? Used for cleanup.
Method • throw: Used to explicitly throw
Method
Basis Overridi an exception.
Overloading
ng • throws: Declares exceptions
Same that a method might throw.
Same method
Example:
method name
Definitio
name with with
n try {
different same
int result = 10 / 0; // May throw
parameters paramet
exception
ers
} catch (ArithmeticException e) {
Between [Link]("Error: " +
Within the supercla [Link]());
Location
same class ss and } finally {
subclass [Link]("This always
Must be Must be executes");
Paramet different exactly }
ers (type/numbe the
r/order) same (b)What are Checked and
Must be UnChecked Exceptions?
Return Can be same (or Checked Exceptions: Checked at
Type different covarian compile-time. Must be handled using
t) try-catch or throws. Subclass of
Runtime Exception but NOT
Compile- RuntimeException.
Polymor (dynami
time (static Examples: IOException,
phism c
polymorphis
Type polymor SQLException,
m)
phism) FileNotFoundException.
Inherita Unchecked Exceptions: Checked
Not required Required
nce at runtime. Need not be handled
Late mandatorily. Subclass of
Binding Early binding
binding RuntimeException.
sound() Examples:
add(int, int)
in parent ArithmeticException,
Example and add(int,
and child NullPointerException,
int, int)
classes ArrayIndexOutOfBoundsException.
Q5. (a) Explain how Exception
Handling is achieved in JAVA. (c)What are the advantages of using
Exception Handling in Java uses five exception handling in Java?
keywords: try, catch, finally, throw, • Separates error-handling code
throws. from normal code, making
programs cleaner.
• try: Encloses code that might
throw an exception. • Propagates exceptions up the
call stack automatically.
• catch: Catches and handles
the exception thrown in try block.
• Allows grouping and class Duck implements Flyable,
differentiation of different error Swimmable {
types. public void fly() {
• Prevents abnormal termination [Link]("Duck can
of programs. fly");
}
• Provides meaningful error
messages to the user. public void swim() {
Q6. (a) What is File Handling in [Link]("Duck can
Java? swim");
File Handling in Java refers to }
reading data from and writing data to }
files. Java provides the [Link]
package with classes for file class Test {
operations. public static void main(String[]
Key classes for File Handling: args) {
Duck d = new Duck();
• FileInputStream / [Link]();
FileOutputStream: Byte-based [Link]();
reading and writing. }
• FileReader / FileWriter: }
Character-based reading and (c) Describe the use of the throw
writing. keyword
• BufferedReader /
BufferedWriter: Efficient reading The throw keyword is used to explicitly
and writing with buffer. throw an exception in a Java program. It
is used when the programmer wants to
• File class: Represents
create and throw an exception manually.
file/directory path, allows
creating/deleting files.
Uses of throw:
• To throw a user-defined or
(b) With a suitable code explain
predefined exception
how we can achieve multiple
• To handle specific conditions in a
inheritance in Java. program
Java does not support multiple • Transfers control to the nearest
inheritance using classes to avoid catch block
ambiguity (diamond problem).
However, it can be achieved using Syntax:
interfaces. throw new ExceptionType("Error
A class can implement multiple message");
interfaces, thereby achieving Example:
multiple inheritance.
class Demo {
interface Flyable { public static void main(String[] args) {
void fly(); int age = 15;
}
if (age < 18) {
interface Swimmable { throw new
void swim(); ArithmeticException("Not eligible to
} vote");
}
}
[Link]("Eligible to vote"); }
} }
} (c) Which method of Thread class is
used to find out the priority given to
Q7. (a) Explain the life cycle of a a thread?
Thread. The method used to get the priority of a
A thread passes through different thread is:
states during its lifecycle: getPriority()
New → Runnable → Running → Blocked/Waiting → Example:
Terminated
↑ ↓ Thread t = new Thread();
└──────────── back to Runnable ─┘ int priority = [Link]();
States:
• New: Thread is created using [Link]("Priority: " +
new Thread() but not started
• Runnable: start() is called; priority);
thread is ready and waiting for // Default is 5
CPU
• Running: Thread is executing
the run() method Q8. (a) What do you mean by
• Blocked/Waiting: Thread is package?
paused due to sleep(), wait(), A package in Java is a namespace used to
or I/O
• Terminated: Thread completes organize related classes and interfaces. It
execution is similar to a folder in a directory.
(b) Describe synchronization in Packages help to avoid naming conflicts
respect to multithreading. and provide access control.
Example:
When multiple threads access a
shared resource simultaneously, it package mypackage; // Declaring a
may cause data inconsistency. package
Synchronization ensures that only
one thread can access the resource at (b) Explain Types of Packages in
a time.
Java.
It is achieved using the synchronized
keyword. 1. Built-in (Predefined) Packages:
Already provided by Java.
Example: • [Link] — Basic classes (String,
Math, Object) — imported
class BankAccount {
automatically.
int balance = 1000;
• [Link] — Utility classes
synchronized void withdraw(int (ArrayList, Scanner, Date).
amount) { • [Link] — Input/Output classes
if (balance >= amount) { (FileReader, BufferedReader).
balance -= amount;
[Link]("Withdrawn: • [Link] — Abstract Window
" + amount); Toolkit for GUI.
} else { • [Link] — Networking classes.
[Link]("Insufficient
balance");
2. User-defined Packages: Created by JVM converts bytecode to machine-
the programmer to organize their own
classes specific instructions. It also handles
memory management via garbage
(d) Write a code to create a package
collection. ii) JRE (Java Runtime
and then use it in a program.
Environment): JRE = JVM + Java
Step 1: Create Package Class class libraries. It is used to run Java
applications. It does NOT include
package mypack;
development tools like compiler.
public class Greet {
public void hello() {
End-users who just need to run Java
[Link]("Hello from apps install JRE.
mypack package!");
} iii) Polymorphism: Ability of an
} object to take many forms. In Java:
Step 2: Compile method overloading (compile-time)
javac -d . mypack/[Link]
and method overriding (runtime).
Example: same method name
Step 3: Use Package in Another
Class behaves differently based on
parameters or object type.
import [Link];
iv) Abstraction: Hiding internal
public class Main { implementation and showing only
public static void main(String[] args)
{ the functionality. Achieved via
Greet g = new Greet();
[Link]();
abstract classes and interfaces.
} Example: We know a car accelerates
}
when we press the accelerator —
Compile and Run: internal mechanism is hidden.
javac [Link]
java Main
Output: (b) What are the differences
Hello from mypack package! between POP and OOP?
POP OOP
Java 2024 (Procedure- (Object-
Q2. (a) Explain any three: i) JVM ii) Feature Oriented Oriented
JRE iii) Polymorphism iv) Programmin Program
Abstraction g) ming)
ANS:- Focuses
Focuses on
Basic on objects
i) JVM (Java Virtual Machine): JVM functions/proc
Concept and
edures
classes
is an abstract computing machine
Top-down Bottom-up
that executes Java bytecode. It Approach
approach approach
provides a runtime environment.
POP OOP Q3. (a) State the purpose of
(Procedure- (Object- using wrapper classes with
Feature Oriented Oriented
Programmin Program example.
g) ming) Purpose of Wrapper Classes
Data is not Data is 1. Object Representation of
secure (global secure Primitives
Data
data can be using Java is an object-oriented
Handling
accessed encapsulat language, but primitive types
easily) ion are not objects. Wrapper
Program classes allow primitives to
Program
Structure divided into
divided be treated as objects.
into 2. Use in Collections
functions
objects Collections like ArrayList
High and HashMap store objects
Reusabilit (through only, not primitive types.
Limited
y inheritance Wrapper classes make it
) possible to store primitive
Examples C, Pascal
Java, C++, values.
Python 3. Utility Methods
Combined Wrapper classes provide
Data & into a useful methods (e.g.,
Separate
Functions single unit parsing strings, converting
(object) types, comparing values).
More 4. Autoboxing and Unboxing
Security Less secure
secure Java automatically converts
(data between primitives and
hiding) wrapper objects:
Easy to o Autoboxing: primitive
Real-
model → object
world Difficult
real-world o Unboxing: object →
Modeling
problems primitive

c) Why is Java a robust Primitive Wrapper


programming language? Type Class
Ans:-
• Java performs strong type int Integer
checking at compile time and char Character
runtime. double Double
• No explicit pointer usage —
eliminates pointer errors. boolean Boolean
• Automatic garbage collection Example:-
handles memory management.
• Comprehensive exception public class WrapperExample {
handling mechanism prevents public static void main(String[]
crashes. args) {
• Java's strong memory model // Primitive type
prevents common memory int num = 10;
corruption issues.
// Converting primitive to
object (Autoboxing)
Integer obj = num; public class SumArray {
// Using wrapper class method public static void
String str = [Link](); main(String[] args) {
[Link]("String
value: " + str); // Array of 5 numbers
// Converting object back to int[] numbers = {10, 20, 30,
primitive (Unboxing) 40, 50};
int value = obj;
[Link]("Primitive
value: " + value); int sum = 0;
}
}

Output:- // Loop to calculate sum


String value: 10 for (int i = 0; i <
Primitive value: 10
(b) Define String. Explain any two [Link]; i++) {
String class methods with example sum += numbers[i];
In Java, a String is an object that }
represents a sequence of characters.
It is immutable, meaning once a String
object is created, its value cannot be // Display result
changed. The String class belongs to [Link]("Sum of
the [Link] package.
array elements: " + sum);
🔹 Any Two String Class Methods with
Examples }
1. length() Method }
• It returns the total number of
characters in a string. Output:-
String s = "Hello"; Sum of array elements: 150
[Link]([Link]()); Q4. (a) Define – Class, Object,
Output: 5
Instance variable and Class
variable
2. charAt(int index) Method
• It returns the character at the
specified index (index starts 1. Class
from 0).
String s = "Java"; A class is a blueprint or
[Link]([Link](0)); template used to create
Output: J
objects. It defines properties
(c)Write a Java code to find the sum (variables) and behaviors
of 5 numbers stored in an array. (methods).
Example: String name; // instance
class Student { variable
int id; }
String name; Class Variable (Static Variable)
A class variable is declared
void display() { using the static keyword.
[Link](id + " " • It is shared among all

+ name); objects of the class


} • Only one copy exists

} Example:
2. Object class Student {
An object is an instance of a static String college = "ABC
class. It represents a real-world College"; // class variable
entity and can access the }
properties and methods of the (b) Explain the each word of the
line: public static void main(String
class. args[])
Example: Access modifier; it means the
Student s1 = new Student(); public method can be accessed from
anywhere.
[Link] = 1; It belongs to the class, not to
[Link] = "Rahul"; static objects; can be called without
creating an object.
[Link]();
Return type; it means the method
void
3. Instance Variable does not return any value.
An instance variable is a Name of the method; it is the
main starting point of program
variable declared inside a class execution.
but outside methods. Data type; used to store a
String
sequence of characters (text).
• It belongs to an object
Array of String; used to store
• Each object has its own args[] command-line arguments passed
copy to the program.

Example: Q5. (a) Explain different types


of constructors with example.
class Student {
Types of Constructors
int id; // instance variable
1. Default Constructor (No-
argument Constructor) 2. Parameterized
• A constructor with no Constructor
parameters • A constructor that accepts

• If you don’t define any parameters


constructor, Java provides • Used to initialize objects
a default one with specific values
automatically Example:
Example: class Student {
class Student { int id;
int id; String name;
String name;
// Parameterized constructor
// Default constructor Student(int i, String n) {
Student() { id = i;
id = 0; name = n;
name = "Unknown"; }
}
void display() {
void display() { [Link](id + " "
[Link](id + " " + name);
+ name); }
}
public static void
public static void main(String[] args) {
main(String[] args) { Student s1 = new
Student s1 = new Student(1, "Rahul");
Student(); Student s2 = new
[Link](); // Output: 0 Student(2, "Amit");
Unknown
} [Link]();
} [Link]();
}
} public static void
main(String[] args) {
3. Copy Constructor (User- Student s1 = new
defined) Student(1, "Rahul");
• Used to create a new
Student s2 = new
object by copying values Student(s1); // copying
from another object
• Java does not provide it
[Link]();
by default; it must be [Link]();
created manually }
}
Example:
(b)What are the differences in
class Student { constructor and method?
int id; Construct
String name; Feature Method
or
Used to
// Parameterized constructor Used to
perform
Student(int i, String n) { Purpose initialize
operations
id = i; objects
/functions
name = n;
} Same as
Can be any
Name the class
valid name
// Copy constructor name
Student(Student s) { No return Must have
id = [Link]; Return type (not a return
name = [Link]; Type even type (or
} void) void)
Called
void display() { Called
automatic
[Link](id + " " Invocatio explicitly
ally when
+ name); n using
object is
} object
created
Construct Output:-
Feature Method
or Biggest number: 25
Q6. (a) Describe different
Inherited
Inheritan Not types of Inheritance with
by diagram.
ce inherited
subclasses Java supports the following types of
inheritance:
Can be • Single Inheritance: One subclass
Overloadi Can be inherits from one superclass.
overloade A -> B (B extends A)
ng overloaded • Multilevel Inheritance: A class
d
inherits from a class which itself
Yes (if no inherits from another class.
No default A -> B -> C (B extends A, C
Default construct extends B)
method is
Provided or is • Hierarchical Inheritance: Multiple
provided subclasses inherit from one
defined) superclass.
A
(c)Write a Java code to find the
/\
biggest among three numbers using
B C (Both B and C extend A)
conditional operators. • Multiple Inheritance: NOT directly
supported in Java with classes to
avoid the Diamond Problem.
public class BiggestNumber { Achieved using interfaces.
A B
public static void
\/
main(String[] args) { C (NOT possible with classes; use
int a = 10, b = 25, c = 15; interface)
• Hybrid Inheritance: Combination of
two or more types. Achieved in Java
using interfaces.
// Using conditional (b) Write a Java code to achieve
multilevel inheritance.
(ternary) operator
class Animal {
int max = (a > b) ?
void eat() {
((a > c) ? a : c)
:
[Link]("Eating...");
((b > c) ? b : c);
}
}
[Link]("Biggest
number: " + max);
class Dog extends Animal {
}
void bark() {
}
This forms multilevel
[Link]("Barking..."); inheritance (Animal → Dog →
} Puppy).
}
Q7. (a) What are the
differences in between
class Puppy extends Dog {
Interface and Abstract Class?
void weep() { Abstract
Feature Interface
Class
[Link]("Weeping..." A blueprint A class that
with only can have
); Definition abstract both abstract
} methods and concrete
(by default) methods
} Methods
are abstract Can have
by default both abstract
public class Main { (no body) and non-
Methods
public static void (Java 8+ can abstract
have (implemente
main(String[] args) { default/stat d) methods
Puppy p = new Puppy(); ic methods)
Can have
Only public instance
[Link](); // from Animal Variables static final variables
[Link](); // from Dog (constants) (normal
variables)
[Link](); // from Puppy Does not
Supports
} Inheritanc
multiple
support
e multiple
} inheritance
inheritance
Output:- Keyword
interface abstract class
Eating... Used
Construct No Can have
Barking... or constructor constructor
Weeping... Methods can
Methods
Explanation (Simple) Access have any
are public
Modifiers access
by default
• Animal → Parent class modifier
• Dog → Child of Animal Used for
Used for full
Usage partial
• Puppy → Child of Dog abstraction
abstraction
(b) Define package with example.? A thread passes through different
A package is a group of related states during its lifecycle:
classes and interfaces bundled New → Runnable → Running → Blocked/Waiting →
together in a namespace. It helps Terminated
organize code and prevents ↑ ↓
└──────────── back to Runnable ─┘
naming conflicts.
States:
(c)Write a Java code to create a • New: Thread is created using
package and then use that in a new Thread() but not started
• Runnable: start() is called;
program. thread is ready and waiting for
Example:- CPU
• Running: Thread is executing
// Creating a package the run() method
• Blocked/Waiting: Thread is
package animals; paused due to sleep(), wait(),
or I/O
public class Dog { • Terminated: Thread completes
public void bark() { execution

(b) Explain run() and start()


method in thread.
[Link]("Woof!");
} start() method:
• Creates a new thread of
} execution.
--------------------------------------- • Moves thread from New to
------------- Runnable state.
• Internally calls the run()
// use the package method in a new thread
import [Link]; context.
• Mustbe called to truly start a
new thread.
public class Main { run() method:
public static void • Contains the code to be
main(String[] args) { executed by the thread.
• If called directly (without
Dog d = new Dog(); start()), it runs in the current
[Link](); (main) thread, not a new
thread.
}
• Definedin Runnable interface
} or Thread class.
Q8. (a) Explain the life cycle Example:-
of a thread.
class MyThread extends Thread Unchecke
{ Featur Checked
d
e Exception
public void run() { Exception
[Link]("Thread Must be Not
is running"); Handli handled using compulsor
} ng try-catch or y to
throws handle
public static void External Programm
main(String[] args) { conditions ing errors
MyThread t1 = new Cause
(file, network, (logic
MyThread(); etc.) mistakes)
MyThread t2 = new
Subclasses of
MyThread(); Subclasses
Exception
of
Class (except
[Link](); // creates new RuntimeEx
RuntimeExce
thread ception
ption)
[Link](); // normal
Compil
method call (no new thread)
er Yes No
}
Check
}
Output:-
(b) Describe try and finally
Thread is running keywords.
Thread is running
Q9. (a) State the difference
between checked and try Keyword
unchecked exception. • The try block contains code that
may cause an exception
Unchecke • It must be followed by either
Featur Checked
d catch or finally
e Exception Example:
Exception
try {
Definiti Checked at Checked int a = 10 / 0; // may cause
exception
on compile-time at runtime
}
finally Keyword
• The finally block always
executes, whether an [Link]("Program
exception occurs or not continues...");
• Used for cleanup tasks (closing
}
files, releasing resources)
Example: }
try { Output:-
int a = 10 / 0;
} finally { Error: Cannot divide by zero
[Link]("This will always Program continues...
execute");
}
Q10. (a) Define stream class.
(C)Write a Java code to handle A Stream in Java is a sequence of
Arithmetic Exception. data flowing from a source (input)
to a destination (output). The
public class ArithmeticExample [Link] package provides stream
{ classes for I/O operations.
Streams can be byte-based or
public static void character-based.
main(String[] args) { Classification of Stream classes:
try { • Byte Streams: Handle raw
int a = 10, b = 0; binary data. Base classes:
InputStream and OutputStream.
int result = a / b; // Sub-classes:
causes ArithmeticException FileInputStream,
FileOutputStream,
BufferedInputStream.
[Link]("Result: " + • Character Streams: Handle
result); character/text data (Unicode).
Base classes: Reader and
} catch Writer.
(ArithmeticException e) { Sub-classes: FileReader,
FileWriter, BufferedReader,
BufferedWriter.
[Link]("Error:
(b) What do you mean by
Cannot divide by zero"); serialization in Java?
}
Serialization in Java
In Java, serialization is the
process of converting an object
into a byte stream so that it can ObjectOutputStream oos =
be: new ObjectOutputStream(fos);
• saved to a file [Link](s);
• sent over a network [Link]();
• stored in memory

Later, this byte stream can be [Link]("Object


converted back into an object serialized");
(called deserialization). }
Example:- }

import [Link].*; May 2025


class Student implements Q2. (a) Explain any three
features of Java
Serializable {
programming.
int id; 1. Platform Independent:
String name; Java follows 'Write Once, Run
Anywhere'. Java source code is
} compiled to bytecode (.class),
which can run on any platform
with JVM installed — not tied to
public class Test { any OS or hardware.
public static void 2. Object Oriented: Java is
main(String[] args) throws based on OOP principles —
encapsulation, inheritance,
Exception { polymorphism, and abstraction.
Student s = new Student(); Everything in Java is an object
(except primitives), making it
[Link] = 1; modular and reusable.
[Link] = "Rahul"; 3. Robust: Java is robust
because of: strict type checking,
no pointer usage, automatic
// Serialization garbage collection, strong
FileOutputStream fos = exception handling, and memory
management — making it reliable
new and crash-resistant.
FileOutputStream("[Link]" 4. Multithreaded: Java
); supports multithreading —
multiple parts of a program
running simultaneously, making
applications faster and more Type Casting in Java
efficient.
In Java, type casting means
(b)What do you mean by byte
code?
converting a variable from
Bytecode is the intermediate code one data type to another.
generated by the Java compiler
(javac) from the source code
Types of Type Casting
(.java file). It is stored in a .class 1. Implicit Casting
file. Bytecode is NOT machine
code — it is platform-independent
(Widening Casting)
instructions that the JVM can • Done automatically by
interpret and execute on any
machine.
Java
• Converts smaller type

Java Source Code (.java) → larger type


• No data loss
↓ (Compiler - javac)
Bytecode (.class) Order:
byte → short → int → long
↓ (JVM)
→ float → double
Machine Code
↓ Syntax:
Output largerType variable =
(c) Why is Java not considered a smallerTypeValue;
completely object-oriented
programming language?
Java is not 100% object-oriented Example:
because it uses primitive data Int a= 10;
types (int, float, char, boolean,
double, byte, short, long) which double b = a; // int to
are NOT objects. In a purely OOP double
language, everything must be an
object. Java supports primitives [Link](b);
for performance reasons. Output: 10.0
Languages like Smalltalk are
considered purely OOP because
they treat everything as objects. 2. Explicit Casting
(Narrowing Casting)
Q3. (a) What is type casting?
• Done manually by
Explain its types with proper
syntax and example. programmer
• Converts larger type → public static void
smaller type main(String[] args) {
• May cause data loss int num = 1234;
Syntax: int sum = 0;
smallerType variable =
(smallerType) while (num > 0) {
largerTypeValue; sum = sum + num % 10;
Example: // get last digit
double x = 10.75; num = num / 10; //
int y = (int) x; // double to remove last digit
int }
[Link](y); //
Output: 10 [Link]("Sum of
digits: " + sum);
(b) What do you understand by }
Garbage Collection?
}
Garbage Collection (GC) is an
automatic memory management Output:-
feature of Java. The JVM
Sum of digits: 10
automatically destroys unused
objects from the heap memory to Q4. (a) Define class and
free space. The programmer does object with example.
not need to manually release
memory (unlike C/C++).
Class
• The finalize() method is called A class is a blueprint or
by GC before destroying an template used to create
object.
objects. It defines properties
• [Link]() can request
garbage collection, but JVM (variables) and behaviors
may ignore it. (methods).
• GC prevents memory leaks in
Java programs.
Object
(c) Write a Java code to find the
sum of digits of a number. An object is an instance of a
class. It represents a real-world
public class SumOfDigits { entity and can use the
properties and methods Access modifier; it means the
public method can be accessed from
defined in the class. anywhere.
Example:- It belongs to the class, not to
class Student { static objects; can be called without
creating an object.
int id; Return type; it means the method
void
String name; does not return any value.
Name of the method; it is the
main starting point of program
void display() { execution.
[Link](id + " " String
Data type; used to store a
sequence of characters (text).
+ name);
Array of String; used to store
} args[] command-line arguments passed
to the program.
}
Q5. (a) Explain Constructor.
A constructor is a special method
public class Main { in a class that is automatically
called when an object of the class
public static void
is created using the 'new'
main(String[] args) { keyword. Its main purpose is to
Student s1 = new initialize the newly created object.
Characteristics:
Student(); // object creation
• Has the same name as the
class.
[Link] = 1; • Has no return type (not even
[Link] = "Rahul"; void).
• Automatically called during
object creation.
[Link](); • Can be overloaded with
} different parameters.
• Default constructor is provided
} if none is written.
Output:-
(b) Write a Java Code to implement
1 Rahul constructor overloading.

(b) Explain the meaning of each class Student {


word of: public static void
main(String args[]) int id;
String name;
Output:-
// Default constructor 0 Unknown
Student() { 1 Rahul
id = 0; (c) State the purpose of using final
keyword with example
name = "Unknown";
} Purpose of final Keyword
In Java, the final keyword is
// Parameterized constructor used to restrict modification.
Student(int i, String n) { Uses of final
id = i; 1. Final Variable
name = n; o Value cannot be
} changed once
assigned (constant)
void display() { Ex:-
[Link](id + " " final int x = 10;
+ name); // x = 20; // Error: cannot
} change value
2. Final Method
public static void • Cannot be overridden in a

main(String[] args) { subclass


Student s1 = new Ex:-
Student(); // calls default class A {
constructor final void show() {
Student s2 = new
Student(1, "Rahul"); // calls [Link]("Hello");
parameterized constructor }
}
[Link](); 3. Final Class
[Link](); • Cannot be inherited (no
} subclass can extend it)
} Ex:-
final class A { void showC() {
} [Link]("Class
// class B extends A {} // Error C");
Q6. (a) What is inheritance? }
Inheritance is a mechanism in Java by
}
which one class (subclass/child class)
acquires the properties and behaviors
of another class (superclass/parent public class Main {
class). It promotes code reusability and
establishes an IS-A relationship. public static void
Example: main(String[] args) {
class Dog extends Animal { } // Dog IS- C obj = new C();
A Animal

[Link](); // from A
[Link](); // from B
(b) Write a Java Code to implement
[Link](); // from C
multilevel inheritance. }
}
class A { Output:-
void showA() { Class A
[Link]("Class Class B
A"); Class C
} (c) Differentiate between method
overloading and method overriding.
}
Method Method
Feature Overload Overridin
class B extends A {
ing g
void showB() {
[Link]("Class Same
Same
B"); method
method
} name
Definitio name
} with
n with
different
same
paramete
class C extends B { paramete
rs
Method Method Q7. (a) What is meant by
interface?
Feature Overload Overridin An interface in Java is a blueprint
ing g of a class that contains only
abstract methods (before Java 8)
rs in and constants. It is used to
subclass achieve abstraction and multiple
inheritance. A class implements
Required an interface using the
(parent- 'implements' keyword.
Inheritan Not Ex:-
child
ce required
relationsh interface Animal {
ip) void sound(); // abstract
Must be method
Paramete different Must be }
rs (type/nu same
mber) class Dog implements Animal {
Can be Must be public void sound() {
Return [Link]("Bark");
same or same (or
Type }
different covariant)
Polymor Compile-
Runtime public static void
phism time
(dynamic) main(String[] args) {
Type (static)
Dog d = new Dog();
Resolved
Resolved [Link]();
Method at
at }
Call compile
runtime }
time
(b) Write a Java code to implement
@Overrid multiple inheritance using interface.
e interface A {
No
Keyword (optional void showA();
special
Used but }
keyword
recomme
nded) interface B {
void showB();
} Feature Interface Class
Can have
both
// Class implementing multiple Mostly
abstract
Methods abstract (no
interfaces and
body)
concrete
class C implements A, B { methods
public void showA() { Only public Can have
[Link]("From Variables static final instance
(constants) variables
Interface A");
Does not
} support
Supports
multiple
Inheritance multiple
inheritanc
public void showB() { inheritance
e (with
[Link]("From classes)

Interface B"); Keyword interface class


Cannot Can
} Object
create create
Creation
object object
public static void Implemente Inherited
Implementatio
d using using
main(String[] args) { n
implements extends
C obj = new C(); Has
No
Constructors construct
constructor
or
[Link]();
Q8. (a) Define package with
[Link](); example.
} A package is a group of related
classes and interfaces bundled
}
together in a namespace. It helps
Output:- organize code and prevents
naming conflicts.
From Interface A
Example:-
From Interface B
(c) Write the difference between // Creating a package
interface and class. package animals;
Feature Interface Class public class Dog {
Blueprint Blueprint
with with data
public void bark() {
Definition
abstract and
methods methods
[Link]("Woof!");
} public static void
} main(String[] args) {
--------------------------------------- try {
------------- int age = 15;
// use the package
import [Link]; if (age < 18) {
throw new
ArithmeticException("Not
public class Main {
eligible");
public static void
}
main(String[] args) {
Dog d = new Dog();
[Link](); [Link]("Eligible");
} } catch
} (ArithmeticException e) {
(c)Explain try, catch and throw
block used in Java Exception
Handling. [Link]([Link]
e());
try block: The code that may }
throw an exception is placed }
inside try. If an exception occurs,
execution stops and control }
passes to the matching catch output:-
block.
Not eligible
catch block: Catches the
Q9. (a) State different types of
exception thrown in the try block.
It specifies the type of exception it errors.
can handle. Multiple catch blocks 1. Compile-time Errors
are allowed for different exception (Syntax Errors): Errors detected
by the compiler before execution.
types.
Caused by incorrect syntax,
throw keyword: Used to explicitly missing semicolons, undeclared
throw an exception (either built-in variables.
or custom). It is followed by an int x = ; // Missing value —
instance of an exception.
compile error
Ex:- 2. Runtime Errors: Errors that
occur during program execution.
public class Test { The program compiles
successfully but crashes at problems like thread
runtime.
int a = 10 / 0; // interference or memory
ArithmeticException at errors.
runtime Key Mechanisms
3. Logical Errors: The • Locks/Monitors: Threads
program compiles and runs but
produces incorrect results due to acquire a lock before
flawed logic. entering a critical section;
others wait until it's
int area = length + width;
released (e.g.,
// Should be * not +
Java's synchronized keywo
(b) Describe thread rd).
synchronization in respect to • Wait/Notify: Threads
multithreading.
pause (wait) and signal
Thread synchronization in (notify/notifyAll) each
multithreading controls access other for coordination, as
to shared resources among in producer-consumer
multiple threads to prevent scenarios.
issues like race conditions and • Other Tools: Mutexes,

data corruption. It ensures semaphores, spinlocks, or


orderly execution, especially read-write locks for
in critical sections of code. advanced control.
Why It's Needed (c) Define thread priority.
Multiple threads running Thread priority is a numerical value
concurrently can interfere assigned to a thread that indicates its
when accessing shared data, relative importance or preference for
receiving CPU time compared with other
leading to unpredictable threads in the system.
outcomes. Synchronization What thread priority means
enforces mutual exclusion, • The scheduler uses thread
priorities to decide which runnable
allowing only one thread at a
thread should execute next;
time into a critical section. higher-priority threads are
This maintains data generally given preference over
lower-priority ones.
consistency and avoids
• In many systems (for example, Base Classes:
Java), priorities are integers in a
InputStream → reads bytes |
fixed range (such as 1–10), where 1
OutputStream → writes bytes
is the lowest and 10 is the highest,
Reader → reads characters | Writer
and 5 is the default or “normal”
→ writes characters
priority.
How it affects scheduling (b) State the classification of stream
• When multiple threads are ready classes.
to run, the scheduler normally
selects the highest-priority one
first; if priorities are equal, it may In Java-style I/O, stream classes
use round-robin or some other are usually classified into two
fairness policy.
• A newly created thread usually
main categories based on the
inherits the priority of the thread kind of data they handle: byte
that created it, and this can later streams and character streams.
be changed via methods such
as setPriority() in Java.
1. Byte streams
Q10. (a) Define stream class. • Used for handling raw

8-bit bytes (for example,


A Stream in Java is a sequence of images, audio, any binary
data flowing from a source (input)
to a destination (output). The data).
[Link] package provides stream • Built on two abstract base
classes for I/O operations.
Streams can be byte-based or classes: InputStream (for
character-based. reading bytes)
Classification of Stream classes: and OutputStream (for
• Byte Streams: Handle raw writing bytes).
binary data. Base classes:
InputStream and OutputStream. 2. Character streams
Sub-classes: • Used for handling 16-bit
FileInputStream,
FileOutputStream,
Unicode characters (text
BufferedInputStream. data).
• Character Streams: Handle • Built on two abstract base
character/text data (Unicode).
Base classes: Reader and
classes: Reader (for
Writer. reading characters)
Sub-classes: FileReader, and Writer (for writing
FileWriter, BufferedReader,
BufferedWriter. characters)
(c) Write a Java program to create }
and read a text file.
}
import [Link].*; Output:-
public class FileExample { Hello Java File
public static void
main(String[] args) {
try {
// Create and write to
file
FileWriter fw = new
FileWriter("[Link]");
[Link]("Hello Java
File");
[Link]();

// Read from file


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

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


1) {

[Link]((char) ch);
}
[Link]();

} catch (IOException e) {
[Link]("Error
occurred");
}

You might also like