0% found this document useful (0 votes)
15 views44 pages

Summer 2027 Solution - Java

The document covers key concepts of Object Oriented Programming (OOP) in Java, including definitions of class, object, inheritance, polymorphism, encapsulation, and abstraction. It also discusses the differences between StringBuffer and StringBuilder, the role of constructors and constructor overloading, and provides insights on arrays and their methods. Additionally, it explains design hints for class and inheritance, the use of the static modifier, and details on inheritance and polymorphism with examples.

Uploaded by

dicepo5475
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)
15 views44 pages

Summer 2027 Solution - Java

The document covers key concepts of Object Oriented Programming (OOP) in Java, including definitions of class, object, inheritance, polymorphism, encapsulation, and abstraction. It also discusses the differences between StringBuffer and StringBuilder, the role of constructors and constructor overloading, and provides insights on arrays and their methods. Additionally, it explains design hints for class and inheritance, the use of the static modifier, and details on inheritance and polymorphism with examples.

Uploaded by

dicepo5475
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
You are on page 1/ 44

Object Oriented Programming - I

BE - SEMESTER–IV (NEW) EXAMINATION – SUMMER 2021

Q-1 (a) Define Object Oriented Concepts.

Answer:

1. Class: In Java, a class is a blueprint or template that defines the


properties (variables) and behaviours (methods) of objects. It
serves as a building block for creating instances of objects.
2. Object: An object is an instance of a class in Java. It represents a

z
specific entity and encapsulates both data (state) and behaviours
aa
(methods). Objects are created based on the defined class and
can interact with each other.
Aw
3. Inheritance: In Java, inheritance is a mechanism that allows a
class to inherit properties and behaviours from another class. The
subclass (derived class) inherits the attributes and methods of the
ut

superclass (base class), promoting code reuse and facilitating


hierarchical relationships between classes.
gr

4. Polymorphism: Polymorphism in Java refers to the ability of


Ja

objects of different classes to respond differently to the same


method call. It allows for the implementation of the same method in
different ways in various classes, enhancing flexibility and
extensibility.
5. Encapsulation: Encapsulation in Java involves bundling data
(attributes) and methods within a class and controlling access to
them. It helps in data hiding, maintaining data integrity, and
providing a clear interface for interacting with objects.
6. Abstraction: Abstraction in Java is the process of simplifying
complex systems by focusing on essential features and hiding
unnecessary details. It involves creating abstract classes and
interfaces to define common behaviours and contracts that
concrete classes must implement.

Click :Youtube Channel | Free Material | Download App


7. Method Overloading: Method overloading in Java allows the
definition of multiple methods with the same name but different
parameters within a class. It enables the use of the same method
name for different purposes based on the type or number of
arguments.
8. Method Overriding: Method overriding in Java allows a subclass
to provide a different implementation of a method that is already
defined in its superclass. It allows for customization of behaviour in
derived classes.
9. Interface: In Java, an interface is a collection of method signatures
(without implementation) that defines a contract for classes to
follow. It provides a way to achieve abstraction and supports
multiple inheritance through interface implementation.
10. Constructor: In Java, a constructor is a special method that is

z
automatically called when an object of a class is created. It
aa
initialises the object's state and performs necessary setup
operations.
Aw

(NOTE: Only write 3 or 4 concepts in exam as the question is of 3


marks only)
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-1(b) What is the difference between the StringBuffer
and StringBuilder classes?

Answer:

StringBuffer StringBuilder

Thread-Safe Not Thread-Safe


All methods are synchronised No synchronisation
Slightly slower due to Faster due to lack of
synchronisation overhead synchronisation

z
Suitable for multithreaded
environment
aa
Requires external synchronisation
in threads
Aw
More memory overhead due to
Less memory overhead
internal synchronisation
Used when thread safety is Used when thread safety is not
ut

required required
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-1(c) Define constructor. How objects are
constructed? Explain constructor overloading with an
example.

Answer:

● Constructor: A constructor in Java is a special method that is


invoked automatically when an object of a class is created. It is
responsible for initialising the state (data members) of the object.
The constructor has the same name as the class and does not
have a return type, not even void. Constructors can be used to set
default values, initialise variables, and perform any necessary
setup operations for the object.

z
aa
● How Objects are Constructed: To construct an object, you use
the new keyword followed by a call to the constructor of the class.
Aw
The constructor allocates memory for the object and initialises its
data members. The general syntax for creating an object and
invoking a constructor is as follows:
ut
gr

ClassName objectName = new ClassName();


Ja

● Constructor Overloading: Constructor overloading refers to the


ability to define multiple constructors with different parameters in a
class. Each constructor can have a unique parameter list, allowing
objects to be constructed in different ways. The choice of
constructor to use depends on the arguments provided during
object creation. By overloading constructors, you can provide
flexibility and convenience in object initialization.

Click :Youtube Channel | Free Material | Download App


Example:

class Car {
String brand;
String color;
int year;

// Default constructor
Car() {
brand = "Unknown";
color = "Unknown";
year = 0;
}
// Constructor with brand and year parameters
Car(String carBrand, int carYear) {

z
brand = carBrand;
color = "Unknown";
year = carYear;
aa
}
w
// Constructor with brand, color, and year parameters
A

Car(String carBrand, String carColor, int carYear) {


brand = carBrand;
ut

color = carColor;
year = carYear;
gr

}
}
Ja

public class Main {


public static void main(String[] args) {
// Creating objects using different constructors
Car car1 = new Car();
Car car2 = new Car("Toyota", 2019);
Car car3 = new Car("Honda", "Red", 2022);
// Displaying the details of each car
System.out.println("Car 1: Brand - " + car1.brand + ",
Color - " + car1.color + ", Year - " + car1.year);
System.out.println("Car 2: Brand - " + car2.brand + ",
Color - " + car2.color + ", Year - " + car2.year);
System.out.println("Car 3: Brand - " + car3.brand + ",
Color - " + car3.color + ", Year - " + car3.year);
}
}

Click :Youtube Channel | Free Material | Download App


Q-2(a) Explain about arrays, Type of arrays and arrays
methods.

Answer:

● Arrays: In Java, an array is a container object that holds a fixed


number of elements of the same type. It provides a way to store
and access multiple values of the same data type in a single
variable. Arrays have a fixed length determined at the time of
creation and can be accessed using an index starting from 0 to the
length minus 1.

● Types of Arrays:

z
aa
1. Single-Dimensional Array: A single-dimensional array is
the most common type of array. It stores elements in a linear
Aw
fashion, allowing access to elements using a single index.
2. Multi-Dimensional Array: A multi-dimensional array is an
array of arrays. It represents a tabular or matrix-like structure
ut

with multiple rows and columns.


gr

● Array Methods:
Ja

1. length(): The length property returns the number of


elements in an array.
2. clone(): The clone() method creates a shallow copy of an
array, producing a new array object with the same elements.
3. toString(): The toString() method returns a string
representation of the array, listing the elements enclosed in
square brackets.
4. sort(): The sort() method sorts the elements of an array in
ascending order. It uses a modified version of the quicksort
algorithm.

Click :Youtube Channel | Free Material | Download App


Q-2(b) Explain about Encapsulation, Abstraction.

Answer:

1. Encapsulation:
● Encapsulation is a mechanism that combines data and the
methods (or functions) that operate on that data into a single
unit called a class.
● It allows for the bundling of related data and functionality,
hiding the internal details of how the class works from the
outside world.
● The key idea is to provide a public interface (public methods)
through which external code can interact with the class, while

z
keeping the internal implementation details hidden and
aa
protected (private or protected data members and methods).
● Encapsulation provides benefits such as data protection,
Aw
code maintainability, and flexibility in modifying the internal
implementation without affecting the external code that uses
the class.
ut

2. Abstraction
gr

● Abstraction is the process of representing complex real-world


entities as simplified models within a program.
Ja

● It focuses on capturing the essential characteristics and


behaviour of an object, while hiding unnecessary details that
are not relevant to the current context.
● Abstraction is achieved through the use of abstract classes
and interfaces in object-oriented programming.
● Abstract classes define a common structure and behaviour
for a group of related classes, while interfaces define a
contract that specifies a set of methods that implementing
classes must adhere to.
● By using abstraction, programmers can create higher-level
and more generalised classes and interfaces, promoting
code reusability, modularity, and flexibility.

Click :Youtube Channel | Free Material | Download App


Q-2(c) State the design hints for class and inheritance.
Also discuss the working and meaning of the “static”
modifier with suitable examples.

Answer:

1. Class Design Hints:


● Keep classes focused: Each class should have a single
responsibility and be focused on a specific task or concept.
● Follow the Single Responsibility Principle (SRP): A class
should have only one reason to change.
● Encapsulate data and behaviour: Hide internal details and
provide a well-defined interface for interacting with the class.

z
● Favour composition over inheritance: Use composition to
aa
build complex classes by combining simpler, reusable
components.
Aw
● Keep class dependencies minimal: Minimise
dependencies between classes to reduce coupling and
improve flexibility.
ut

● Apply proper naming conventions: Choose meaningful


and descriptive names for classes to enhance code
gr

readability and understanding.


Ja

2. Inheritance Design Hints:


● Use inheritance for "is-a" relationships: Inheritance
should be used when one class "is a" specialised version of
another class.
● Favour composition over deep inheritance hierarchies:
Prefer creating reusable components that can be composed
rather than creating complex inheritance chains.
● Avoid excessive deep hierarchies: Limit the depth of
inheritance hierarchies to avoid overly complex and tightly
coupled code.
● Avoid inheritance when the "is-a" relationship is weak: If
the relationship between classes is not a strong "is-a"
relationship, consider using interfaces or other mechanisms
instead.

Click :Youtube Channel | Free Material | Download App


Static Modifier:

● In Java, the "static" modifier is used to define class members


(variables or methods) that belong to the class itself rather than
individual instances of the class. When a member is declared as
static, it means that it is shared by all objects of that class and can
be accessed without creating an instance of the class.

1. Static Variables: A static variable, also known as a class variable,


is shared by all instances of a class. It is initialised only once, at
the start of the program, and retains its value throughout the
program's execution. Any changes made to the static variable are
reflected across all objects of the class.

z
Example: aa
w
class Counter {
A

static int count = 0; // Static variable


ut

Counter() {
count++;
gr

}
}
Ja

public class Main {


public static void main(String[] args) {
Counter c1 = new Counter();
System.out.println(Counter.count); // Output: 1

Counter c2 = new Counter();


System.out.println(Counter.count); // Output: 2
}
}

Click :Youtube Channel | Free Material | Download App


2. Static Methods: A static method belongs to the class itself rather
than an instance of the class. It can be called directly using the
class name, without creating an object. Static methods cannot
access non-static (instance) variables or methods directly because
they do not belong to any specific instance.

Example:

class MathUtils {
static int multiply(int a, int b) {
return a * b;
}
}

z
public class Main {
public static void main(String[] args) {
aa
int result = MathUtils.multiply(5, 3);
System.out.println(result); // Output: 15
Aw
}
}
ut
gr
Ja

OR

Click :Youtube Channel | Free Material | Download App


Q-2(c) Explain in detail how inheritance and
polymorphism are supported in java with necessary
examples.

Answer:

In Java, inheritance and polymorphism are fundamental concepts that


support code reusability, modularity, and flexibility.

1. Inheritance:

● Inheritance is the mechanism in Java that allows one class to


inherit the properties (methods and fields) of another class.

z
● The class that is being inherited from is called the superclass
aa
or parent class, and the class that inherits is called the
subclass or child class.
w
● Inheritance is denoted by the "extends" keyword.
A

Example:
ut
gr

class Animal {
void eat() {
Ja

System.out.println("Animal is eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking...");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Output: Animal is eating...
dog.bark(); // Output: Dog is barking...
}
}

Click :Youtube Channel | Free Material | Download App


2. Polymorphism:

● Polymorphism refers to the ability of objects of different


classes to be treated as objects of a common superclass.
● It allows methods to be overridden in the subclass, providing
different implementations while maintaining a consistent
interface.
● Polymorphism is achieved through method overriding and
method overloading.

Example:

class Animal {
void makeSound() {

z
System.out.println("Animal is making a
sound...");
}
aa
w
}
A

class Dog extends Animal {


@Override
ut

void makeSound() {
System.out.println("Dog is barking...");
gr

}
}
Ja

public class Main {


public static void main(String[] args) {
Animal animal = new Animal();
animal.makeSound(); // Output: Animal is making
a sound...

Animal dog = new Dog();


dog.makeSound(); // Output: Dog is barking...
}
}

Click :Youtube Channel | Free Material | Download App


Q-3(a) Explain about different types of string methods.

Answer:

1. Manipulation Methods:
● These methods modify or manipulate the content of the
string.
● Examples: substring(), concat(), replace(), toLowerCase(),
toUpperCase().
● They enable operations like extracting substrings,
concatenating strings, replacing characters, and changing
the case of characters.
2. Comparison Methods:

z
● These methods are used to compare strings for equality or to
determine their ordering. aa
● Examples: equals(), equalsIgnoreCase(), compareTo(),
Aw
compareToIgnoreCase().
● They allow comparing strings based on their content,
ignoring case differences, or based on lexicographic
ut

ordering.
3. Searching and Matching Methods:
gr

● These methods help in finding substrings or patterns within a


string.
Ja

● Examples: contains(), startsWith(), endsWith(), indexOf(),


lastIndexOf(), matches().
● They enable searching for specific characters, substrings, or
regular expressions within a string.

Click :Youtube Channel | Free Material | Download App


Q-3(b) Write short notes on access specifiers and
modifiers in java.

Answer:

Access Specifiers:

1. Public: Allows unrestricted access to classes, methods, and


variables from anywhere in the program.
2. Private: Restricts access to only within the defining class, ensuring
encapsulation and data hiding.
3. Protected: Provides access to subclasses and classes within the
same package, allowing for inheritance and package-level

z
encapsulation.
aa
4. Default (Package-private): Limits access to only within the same
package, maintaining package-level encapsulation.
Aw

Modifiers:
ut

1. Final: Prevents further modification to classes, methods, or


variables, ensuring immutability or prohibiting method overriding or
gr

class extension.
Ja

2. Static: Indicates that a variable or method belongs to the class


itself, not individual instances, allowing direct access without object
instantiation.
3. Abstract: Used in abstract classes or methods, it provides a
blueprint for subclasses to implement and cannot be instantiated
on its own.
4. Synchronized: Ensures thread-safe access to methods or blocks,
allowing only one thread at a time to execute them to prevent data
race conditions.
5. Volatile: Guarantees visibility and ordering of shared variables
among threads, ensuring that reads and writes occur directly from
and to the main memory.

Click :Youtube Channel | Free Material | Download App


Q-3(c) What is an Exception? Explain the exception
hierarchy. Explain how to throw, catch and handle
Exceptions.

Answer:

Exception:

● An Exception in Java is an event or condition that occurs during


the execution of a program and disrupts the normal flow of
instructions.
● It represents an error or unexpected situation that needs to be
handled by the program.

z
● Exceptions allow programmers to handle errors gracefully and take
appropriate actions.
aa
Aw
Exception Hierarchy:

● In Java, exceptions are organised in a hierarchy based on their


ut

relationship with the Throwable class.


● The hierarchy consists of two main types of exceptions:
gr
Ja

1. Checked Exceptions:

● These are exceptions that the compiler requires to be


handled explicitly.
● They extend the Exception class.
● Examples: IOException, SQLException. Checked exceptions
typically represent recoverable conditions or external events
that the program needs to handle gracefully.

2. Unchecked Exceptions (Runtime Exceptions):

● These are exceptions that are not required to be handled


explicitly.
● They extend the RuntimeException class.

Click :Youtube Channel | Free Material | Download App


● Examples: NullPointerException,
ArrayIndexOutOfBoundsException. Unchecked exceptions
generally represent programming errors or exceptional
conditions that the program should avoid or fix.

How to Throw, Catch, and Handle Exceptions:

1. Throwing Exceptions: To throw an exception explicitly, use the


throw keyword followed by an instance of an exception class.

Example:

throw new IOException("File not found");

z
aa
2. Catching Exceptions: To catch exceptions, use the try-catch
block. The try block encloses the code that may throw an
Aw
exception. The catch block catches and handles the thrown
exception.

Example:
ut
gr

try {
// Code that may throw an exception
Ja

} catch (IOException e) {
// Handling the IOException
}

Click :Youtube Channel | Free Material | Download App


3. Handling Exceptions: Exception handling involves writing code to
handle exceptions gracefully. Multiple catch blocks can be used to
handle different types of exceptions. The finally block, if present, is
executed regardless of whether an exception occurs or not.

Example:

try {
// Code that may throw an exception
} catch (IOException e) {
// Handling the IOException
} catch (NullPointerException e) {
// Handling the NullPointerException
} finally {
// Code that always executes

z
}
aa
Aw
ut
gr
Ja

OR

Click :Youtube Channel | Free Material | Download App


Q-3(a) Explain about Final class, Fields, Methods.

Answer:

1. Final Class: A final class in Java is a class that cannot be


subclassed or inherited. It is marked with the final keyword. Once a
class is declared as final, it cannot be extended further. This is
often done to prevent modifications or to ensure that the class
serves as the ultimate implementation of a concept. Final classes
are commonly used for utility classes, immutable classes, or
classes with sensitive behaviour that should not be altered.

2. Final Fields (Variables): A final field, also known as a constant or

z
immutable variable, is a field that cannot be modified once it is
aa
initialised. It is marked with the final keyword. Once a final field is
assigned a value, it cannot be changed. Final fields are typically
Aw
used to define constants or values that should remain unchanged
throughout the program's execution.
ut

3. Final Methods: A final method in Java is a method that cannot be


overridden by a subclass. It is marked with the final keyword. Once
gr

a method is declared as final in a superclass, it cannot be modified


or overridden in any of its subclasses. This ensures that the
Ja

behaviour of the method remains consistent across all classes and


prevents subclasses from altering the method implementation.
Final methods are often used when a method in a superclass is
considered critical and should not be changed by subclasses.

Click :Youtube Channel | Free Material | Download App


Q-3(b) What is a Package? What are the benefits of
using packages? Write down the steps in creating a
package and using it in a java program with an
example.

Answer:

Package: A Package in Java is a way of organising related classes,


interfaces, and resources. It provides a hierarchical structure to group
related components together.

Benefits of Using Packages:

z
aa
1. Modularity and Organization: Packages allow for logical
grouping of classes, making it easier to manage and maintain
code. It promotes code reusability and enhances the overall
Aw

structure of the program.


2. Encapsulation and Access Control: Packages provide
encapsulation by controlling the visibility and accessibility of
ut

classes and their members. Classes within the same package can
gr

have default (package-private) access, allowing them to be


accessed by other classes within the same package.
Ja

3. Namespace Management: Packages provide a unique


namespace for classes. They help avoid naming clashes,
especially when multiple libraries or modules are used within a
project.
4. Reusability and Collaboration: Packages facilitate code reuse
and collaboration. They allow developers to distribute and share
code as reusable components or libraries, making it easier to work
on large-scale projects.

Click :Youtube Channel | Free Material | Download App


Steps to Create and Use a Package in Java:

1. Package Declaration: Add a package declaration at the top of the


Java file to indicate the package to which the class belongs. For
example, package com.example.mypackage;.
2. Directory Structure: Create a directory structure that matches the
package name. Each level of the package hierarchy corresponds
to a directory in the file system. For example, create the directory
com/example/mypackage to match the package
com.example.mypackage.
3. Class Definition: Define the class within the package. For
example:
package com.example.mypackage;

z
public class MyClass {

}
// Class implementation aa
Aw
4. Compilation and Execution: Compile the Java file using the
javac command, ensuring that the directory structure matches the
package hierarchy. To execute the compiled class, use the fully
ut

qualified name of the class, including the package name. For


example, java com.example.mypackage.MyClass.
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-3(c) Explain the concept of inner classes and explain
the types of inner classes with an example program.

Answer:

Inner Class:

● In Java, an Inner Class is a class defined within another class.


● It allows you to logically group classes together and establish a
close relationship between them.
● Inner classes have access to the members of the enclosing class,
including private members, and can be used to encapsulate
related functionality.

z
Types of Inner Classes:
aa
Aw
1. Member Inner Class:

● A member inner class is a non-static class defined at the


ut

member level of another class.


● It has access to all members of the enclosing class, including
gr

private members.
Ja

2. Static Nested Class:

● A static nested class is a static class defined at the member


level of another class.
● It is similar to a regular class but is nested for packaging
convenience. It does not have access to the instance
members of the enclosing class.

Click :Youtube Channel | Free Material | Download App


3. Local Inner Class:

● A local inner class is a class defined within a method or


scope block.
● It has access to the variables and parameters of the
enclosing block and can only be instantiated within that
block.

4. Anonymous Inner Class:

● An anonymous inner class is a class defined without a name.


● It is typically used for creating an instance of an interface or
extending a class on-the-fly. It is defined and instantiated
simultaneously.

z
Example: aa
w
public class OuterClass {
A

private int x = 10;


ut

// Member Inner Class


public class InnerClass {
gr

public void display() {


System.out.println("Inner class: " + x);
Ja

}
}

// Static Nested Class


public static class NestedClass {
public void display() {
System.out.println("Nested class");
}
}

public void outerMethod() {


int y = 5;

// Local Inner Class


class LocalClass {
public void display() {

Click :Youtube Channel | Free Material | Download App


System.out.println("Local class: " + y);
}
}

// Anonymous Inner Class


Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Anonymous inner class");
}
};

// Instantiating inner classes


InnerClass inner = new InnerClass();
inner.display();

z
NestedClass nested = new NestedClass();
nested.display(); aa
Aw
LocalClass local = new LocalClass();
local.display();

runnable.run();
ut

}
gr

public static void main(String[] args) {


Ja

OuterClass outer = new OuterClass();


outer.outerMethod();
}
}

Click :Youtube Channel | Free Material | Download App


Q-4(a) What is Dynamic binding? Show with an
example how dynamic binding works.

Answer:

Dynamic Binding:

● Dynamic binding, also known as late binding, is a mechanism in


object-oriented programming where the actual method or function
to be executed is determined at runtime based on the actual type
of the object.

Example:

z
class Animal {
aa
public void makeSound() {
w
System.out.println("Animal makes a sound");
A

}
}
ut

class Dog extends Animal {


@Override
gr

public void makeSound() {


System.out.println("Dog barks");
Ja

}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animal1.makeSound(); // Output: Dog barks
animal2.makeSound(); // Output: Cat meows
}
}

Click :Youtube Channel | Free Material | Download App


Q-4(b) Write short notes about I/O stream classes.

Answer:

I/O (Input/Output) stream classes in Java facilitate reading from and


writing to different data sources, like files or network connections. Here
are some key points about I/O stream classes:

1. Stream Hierarchy: I/O streams are organised in a hierarchy with


two main branches:

● InputStream and OutputStream: For reading and writing


binary data.

z
● Reader and Writer: For reading and writing character data.
aa
2. Byte Streams (InputStream/OutputStream): Byte-oriented
Aw
streams are used for reading and writing raw binary data, like files
or images. Examples: FileInputStream, FileOutputStream,
BufferedInputStream, BufferedOutputStream.
ut

3. Character Streams (Reader/Writer): Character-oriented streams


gr

handle character data and handle character encoding and


decoding. Examples: FileReader, FileWriter, BufferedReader,
Ja

BufferedWriter.

4. Buffered Streams: Buffered streams provide buffering capabilities


to improve I/O performance. They store data in memory before
reading from or writing to the underlying stream. Examples:
BufferedInputStream, BufferedOutputStream, BufferedReader,
BufferedWriter.

Click :Youtube Channel | Free Material | Download App


Q-4(c) Explain the thread state, thread properties and
thread synchronisation.

Answer:

Thread State: In Java, a thread can exist in different states throughout


its lifecycle:

1. New: The thread is in the new state when it is created but has not
yet started.
2. Runnable: The thread is in the runnable state when it is ready to
run and waiting for its turn on the CPU.
3. Blocked: The thread is in the blocked state when it is waiting for a

z
monitor lock to enter a synchronised block or waiting for I/O
operations to complete.
aa
4. Waiting: The thread is in the waiting state when it waits indefinitely
Aw
until another thread notifies it to resume execution.
5. Timed Waiting: The thread is in the timed waiting state when it
waits for a specific amount of time before resuming execution.
ut

6. Terminated: The thread is in the terminated state when it


completes its execution or is explicitly terminated.
gr
Ja

Thread Properties:

1. Priority: Each thread has a priority that determines its importance


relative to other threads. Thread priorities range from 1 (lowest) to
10 (highest).
2. Name: Threads can be assigned names for identification and
debugging purposes.
3. Daemon: A daemon thread is a background thread that runs
without preventing the program from exiting.
4. Thread Group: Threads can be organised into thread groups,
which helps manage and control a collection of threads.

Click :Youtube Channel | Free Material | Download App


Thread Synchronisation: Thread synchronisation is the coordination of
multiple threads to ensure their proper and safe execution in a
multi-threaded environment. It is crucial to prevent race conditions and
maintain data consistency. Key concepts include:

1. Locks: Locking mechanisms, such as the synchronised keyword


or explicit Lock objects, are used to ensure exclusive access to
shared resources.
2. Critical Sections: Critical sections are code blocks that need to
be executed atomically by only one thread at a time.
Synchronisation is used to protect critical sections.
3. Mutual Exclusion: Mutual exclusion ensures that only one thread
can access a shared resource at a given time.
4. Inter-Thread Communication: Thread synchronisation is often

z
coupled with inter-thread communication mechanisms, such as
aa
wait(), notify(), and notifyAll(), to enable threads to communicate
and coordinate their activities.
A w
ut
gr
Ja

OR

Click :Youtube Channel | Free Material | Download App


Q-4(a) Explain the concept of finalization.

Answer:

Finalization:

● Finalization in Java is a process where an object gets the


opportunity to perform any necessary cleanup actions before it is
garbage collected.
● The finalize() method is defined in the Object class and can be
overridden in a subclass to provide custom finalization logic.
● The method is called by the JVM when the object becomes eligible
for garbage collection.

z
● It allows for releasing resources, closing connections, or
performing other cleanup tasks. aa
● However, it's important to note that the use of finalize() is
Aw
discouraged due to its unpredictable execution timing and potential
performance impact.
● It is recommended to use alternative resource management
ut

techniques like try-with-resources or explicit cleanup methods.


gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-4(b) What is reflection and how does it help to
manipulate java code?

Answer:

Reflection in Java is a powerful feature that enables the examination and


manipulation of code at runtime. It allows programs to introspect and
modify the structure, behavior, and state of classes, interfaces, methods,
and fields dynamically. Reflection provides a way to inspect and
manipulate Java code beyond what is statically available during
compilation.

Here's how reflection helps manipulate Java code:

z
aa
1. Introspection: Reflection allows you to obtain information about
classes, interfaces, methods, and fields at runtime. You can
Aw
access class metadata, such as its name, superclass,
implemented interfaces, constructors, and methods.
2. Dynamic Class Instantiation: Reflection enables the creation of
ut

new instances of classes dynamically, even if the class name is not


known at compile time. By obtaining the Class object through
gr

reflection, you can invoke constructors and create objects at


Ja

runtime.
3. Method Invocation: Reflection allows you to invoke methods
dynamically based on their names, even if the methods are not
known at compile time. You can obtain method references, set
their accessibility, and invoke them using different arguments.
4. Field Manipulation: Reflection allows you to access and modify
field values dynamically, including private fields. You can read and
set field values using reflection, which is useful for scenarios
where direct field access is not possible or desirable.
5. Annotations and Annotations Processing: Reflection enables
the inspection of annotations at runtime. You can retrieve
annotation details, check for their presence, and use them to
perform custom processing or apply runtime behaviors.

Click :Youtube Channel | Free Material | Download App


Q-4(c) Write a java program to implement the multiple
inheritance concepts for calculating area of circle and
square.

Answer:

interface Circle {
double calculateArea();
}

interface Square {
double calculateArea();
}

z
aa
class AreaCalculator implements Circle, Square {
private double radius;
private double side;
Aw

public AreaCalculator(double radius, double side) {


this.radius = radius;
ut

this.side = side;
}
gr

@Override
Ja

public double calculateArea() {


// Implementing the calculateArea() method for Circle
double circleArea = Math.PI * radius * radius;
// Implementing the calculateArea() method for Square
double squareArea = side * side;
return circleArea + squareArea;
}
}

public class Main {


public static void main(String[] args) {
double radius = 3.5;
double side = 5.0;

AreaCalculator calculator = new AreaCalculator(radius,


side);

Click :Youtube Channel | Free Material | Download App


double totalArea = calculator.calculateArea();

System.out.println("Total area: " + totalArea);


}
}

z
aa
Aw
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-5(a) Explain about callback.

Answer:

Callback:

● A callback in programming refers to the practice of passing a


function as an argument to another function or method.
● The receiving function can then invoke the callback function at a
later point in time or when a specific condition is met.
● Callbacks are commonly used in event-driven programming and
asynchronous operations.

z
aa
Aw
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-5(b) Explain the interface with an example program.

Answer:

Interface:

● In Java, an interface is a blueprint of a class that defines a set of


methods that must be implemented by any class that implements
the interface.
● It establishes a contract between the interface and the
implementing classes, specifying what methods should be present
and how they should be implemented.

z
Example:

// Interface definition
aa
w
interface Animal {
void makeSound(); // Abstract method declaration
A

}
ut

// Implementing class
gr

class Dog implements Animal {


@Override
Ja

public void makeSound() {


System.out.println("Dog barks");
}
}

// Implementing class
class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("Cat meows");
}
}

public class Main {


public static void main(String[] args) {
Animal dog = new Dog(); // Interface reference holding

Click :Youtube Channel | Free Material | Download App


Dog object
Animal cat = new Cat(); // Interface reference holding
Cat object

dog.makeSound(); // Output: Dog barks


cat.makeSound(); // Output: Cat meows
}
}

z
aa
Aw
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-5(c) What is Generic programming and why is it
needed? Explain with examples. List the limitations and
restrictions of generic programming.

Answer:

● Generic programming is a programming approach that enables the


creation of reusable algorithms and data structures that can work
with different types of data.
● It allows developers to write code that is independent of specific
data types and provides flexibility, type safety, and code reusability.

Why is generic programming needed?

z
aa
1. Code Reusability: Generics allow the creation of generic
algorithms and data structures that can be used with different
Aw
types of data, eliminating the need to write duplicate code for each
specific type.
2. Type Safety: Generics provide compile-time type checking,
ut

preventing type-related errors at runtime. This helps catch errors


early in the development process and improves code reliability.
gr

3. Abstraction: Generics enable the creation of more abstract and


Ja

general-purpose code by decoupling it from specific types. This


promotes cleaner and more modular code design.

Click :Youtube Channel | Free Material | Download App


Example:

class Box<T> {
private T item;

public void setItem(T item) {


this.item = item;
}

public T getItem() {
return item;
}
}

public class Main {

z
public static void main(String[] args) {
aa
Box<Integer> integerBox = new Box<>();
integerBox.setItem(10);
int value = integerBox.getItem(); // No casting needed
A w
Box<String> stringBox = new Box<>();
stringBox.setItem("Hello");
ut

String text = stringBox.getItem(); // No casting needed


}
gr

}
Ja

Click :Youtube Channel | Free Material | Download App


Limitations and Restrictions of Generic Programming:

1. Primitive Types: Generics in Java cannot be used with primitive


types directly. However, wrapper classes like Integer, Double, etc.,
can be used instead.
2. Type Erasure: Java implements generics using type erasure,
which means the type information is removed at runtime. This
imposes certain limitations, such as the inability to check the type
of a generic parameter at runtime.
3. Array Creation: It is not possible to create arrays of a generic type
directly. Workarounds include creating arrays of wildcard types or
using collections instead of arrays.
4. Static Context: Generics cannot be used in a static context with
type parameters specific to the instance of the class. However,

z
they can be used with generic methods in a static context.
aa
A w
ut
gr
Ja

OR

Click :Youtube Channel | Free Material | Download App


Q-5(a) Explain about Proxy class, Interface and
Methods.

Answer:

1. Proxy Class: In Java, a Proxy class is a class generated at


runtime that acts as an intermediary between a client object and its
corresponding real object. It allows for the implementation of
cross-cutting concerns, such as logging, security, or performance
monitoring, without modifying the original object's code.

2. Interface: An interface in Java defines a contract that a class must


adhere to. It specifies a set of methods that implementing classes

z
must provide. Interfaces allow for abstraction, multiple inheritance
aa
of type, and promote loose coupling between components.
Aw
3. Methods: Methods in Java are blocks of code that define the
behaviour of a class. They represent actions or operations that an
object can perform. Methods encapsulate logic and allow for code
ut

reuse and modular design. They can have parameters and return
values, and their visibility can be controlled with access modifiers.
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-5(b) Explain about adapter classes and mouse
events with an example.

Answer:

1. Adapter Classes: In Java, an Adapter class is a class that


provides default empty implementations of methods in an
interface. It allows a class to implement only the methods it needs,
instead of implementing all methods of the interface. This pattern
helps in reducing code duplication and improves code readability.

2. Mouse Events: In Java, Mouse Events refer to actions or


interactions performed by a user with a mouse device. Mouse

z
events can include clicking, dragging, moving, and releasing the
aa
mouse. These events can be captured and handled in a Java
program to perform specific actions or trigger specific behavior.
A w
Example:
ut

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
gr

class MouseClickListener extends MouseAdapter {


Ja

@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at (" + e.getX() + ", "
+ e.getY() + ")");
}
}

public class Main {


public static void main(String[] args) {
MouseClickListener mouseClickListener = new
MouseClickListener();

// Simulating mouse click event


MouseEvent mouseEvent = new MouseEvent(
new Object(), MouseEvent.MOUSE_CLICKED,

Click :Youtube Channel | Free Material | Download App


System.currentTimeMillis(),
0, 50, 100, 1, false
);

mouseClickListener.mouseClicked(mouseEvent);
}
}

z
aa
Aw
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-5(c) With a neat diagram explain the Model view
controller design pattern and list out the advantages
and disadvantages of using it in designing an
application.

Answer:

Model-View-Controller (MVC) Design Pattern:

z
aa
Aw
ut
gr
Ja

● The MVC design pattern is a widely used architectural pattern that


separates an application into three interconnected components:
the Model, View, and Controller.

Click :Youtube Channel | Free Material | Download App


1. Model: Represents the application's data and business logic.
Manages data storage, retrieval, and manipulation. Notifies
observers (usually views) about changes in data.
2. View: Presents the user interface to display the data from the
model. Renders the data and handles user interactions. Sends
user actions to the controller for processing.
3. Controller: Handles user input and events from the view.
Orchestrates interactions between the model and view. Updates
the model based on user actions and updates the view
accordingly.

The flow of the MVC pattern typically follows this sequence:

● The user interacts with the view, such as clicking a button or

z
entering data.
aa
● The view notifies the controller of the user action.
● The controller updates the model based on the user action.
Aw
● The model updates its data and notifies the view(s) of the
changes.
● The view retrieves the updated data from the model and refreshes
ut

the UI.
gr

Advantages of using the MVC pattern:


Ja

1. Separation of Concerns: MVC separates the application logic


(model), user interface (view), and user input handling (controller),
making the codebase more organized and maintainable.
2. Code Reusability: The modular nature of MVC allows for reusing
models, views, and controllers in different parts of the application.
3. Parallel Development: MVC enables parallel development by
allowing separate teams to work on different components
independently.
4. Testability: Each component can be tested independently, leading
to improved testability and easier bug detection.
5. User Experience: The separation of concerns and clear
responsibilities of each component result in a more responsive and
interactive user experience.

Click :Youtube Channel | Free Material | Download App


Disadvantages of using the MVC pattern:

1. Complexity: Implementing MVC requires careful planning and


understanding of the pattern, which can be complex for smaller
applications.
2. Overhead: The pattern may introduce additional layers and
communication overhead between components, potentially
affecting performance in some cases.
3. Learning Curve: Developers new to MVC may require time to
understand and adapt to the pattern's concepts and practices.
4. Increased File Count: Implementing MVC often leads to a larger
number of files and classes, which may make the project structure
more complex.

z
aa
Aw
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App

You might also like