JAVA QB SOL(MODULE 2-3)
JAVA QB SOL(MODULE 2-3)
Ans:
Inheritance is a mechanism in which one class acquires the property of another class
I. Single Inheritance
II. Mul ple Inheritance
III. Mul level Inheritance
IV. Hierarchial Inheritance
V. Hybrid Inheritance
Single Inheritance: A subclass inherits from a single superclass. Java supports single inheritance
for classes.
Ex:
class Animal {
void eat() {
System.out.println("Animal is ea ng.");
}
}
interface Walker {
void walk();
}
Mul level Inheritance: In mul level inheritance, a derived class inherits from another
derived class, forming a chain of inheritance.
Ex:
class Vehicle {
void move() {
System.out.println("Vehicle is moving.");
}
}
class B extends A {
void methodB() {
System.out.println("Method B");
}
}
class C extends A {
void methodC() {
System.out.println("Method C");
}
}
class D extends B {
void methodD() {
System.out.println("Method D");
}
}
2. Explain Overloading and Overriding within the scope of Inheritance using a suitable example.
3. How overriding is different from overloading? Explain with an example. Or why overridden methods are
used in Java? Explain with an example.
Ans:
Overloading:
Overloading is a feature in Java that allows a class to have mul ple methods with the same
name but different parameter lists. Overloaded methods are differen ated by the number or type
of parameters they accept.
Ex:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Overriding:
Overriding is a feature that allows a subclass to provide a specific implementa on for a
method that is already defined in its superclass. The method in the subclass should have the same
method signature (method name and parameter types) as the method in the superclass.
Ex:
class Shape {
void draw() {
System.out.println("Drawing a shape.");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle.");
}
}
Why Overridden Methods are Used:
Overridden methods are used to achieve polymorphism and dynamic method invoca on.
They allow a subclass to provide its own specialized implementa on of a method defined in its
superclass. This is par cularly useful in scenarios where you want to work with objects of different
subclasses in a uniform way.
Ex:
public class Main {
public sta c void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
The super keyword in Java is used to refer to the immediate parent class of a subclass. It can be
used in two primary ways:
The super() constructor call is used to invoke the constructor of the superclass. This is
useful when a subclass constructor needs to perform addi onal tasks or ini alize variables that
are specific to the subclass, while also making sure that the ini aliza on code from the superclass
constructor is executed.
Parent() {
System.out.println("Parent constructor");
Child() {
System.out.println("Child constructor");
OUTPUT
Parent constructor
Child constructor
II. To Call Superclass Method:
The super keyword can also be used to call a method of the superclass when a
subclass wants to provide its own implementa on but s ll needs to access the method of
the parent class.
Ex:
class Parent {
void display() {
System.out.println("Parent's display method");
}
}
class Child extends Parent {
@Override
void display() {
super.display(); // Calling the parent class method
System.out.println("Child's display method");
}
}
public class Main {
public sta c void main(String[] args) {
Child child = new Child();
child.display();
}
}
OUTPUT
Parent's display method
Child's display method
5. Write a short note on i) Super keyword ii) Final keyword iii) Dynamic method dispatch
Ans:
I. Super Keyword
Ans:
The super keyword in Java is used to refer to the immediate parent class of a subclass. It has two
primary uses:
To call the constructor of the superclass using super() in the subclass constructor. This ensures that
the ini aliza on code of the superclass is executed before the subclass's own ini aliza on.
To call methods or access fields from the parent class even when they are overridden in the
subclass. This is useful when you want to u lize or extend the func onality of the parent class
while adding specific behavior in the subclass.
Ex:
class Parent {
void display() {
@Override
void display() {
}
II. Final Keyword:
The final keyword in Java is used to denote that a class, method, or variable cannot be
further subclassed, overridden, or modified, respec vely.
A final class cannot be extended, ensuring that its design remains unchanged.
A final method cannot be overridden in its subclasses, preserving the behavior defined in
the parent class.
A final variable cannot be reassigned a er its ini al value is set, providing immutability.
Ex:
class Parent {
class Main {
Example:
class Animal {
void makeSound() {
void makeSound() {
System.out.println("Dog barks.");
Ans:
Ex:
Ans:
An excep on in Java is an event that occurs during the execu on of a program, disrup ng the
normal flow of instruc ons. Excep ons are used to handle run me errors or excep onal situa ons that
can't be resolved at compile me. Java provides a robust excep on handling mechanism to deal with such
situa ons, helping to write more reliable and resilient programs. Excep on handling involves iden fying,
capturing, and dealing with excep ons to prevent program crashes and to provide meaningful error
messages to users.
Checked Excep on
Unchecked Excep on(Run me Excep on)
Error
I. Checked Expression
Checked excep ons are the excep ons that are checked at compile- me. Code that might raise
checked excep ons must be placed within a try-catch block or declared in the method signature
using the throws keyword.
Ex:
import java.io.BufferedReader;
import java.io.FileReader;
try {
System.out.println(line);
reader.close();
} catch (IOExcep on e) {
}
II. Unchecked Excep ons (Run meExcep ons):
Unchecked excep ons, also known as run me excep ons, do not need to be explicitly
caught or declared in the method signature. They occur at run me and typically indicate
programming errors, like dividing by zero or accessing an array index out of bounds.
Ex:
int a = 10, b = 0;
System.out.println(result);
III. Error
Errors are excep onal condi ons that usually can't be handled by a Java program. They
indicate serious problems that are beyond the control of the applica on, like running out of
memory or hardware failures. Errors are not meant to be caught or handled; they are o en used
to indicate unrecoverable situa ons.
Ex:
}
8. What is an exception? Give the keywords and the general structure of an exception-handling
block.
OR
try {
int result = 10 / 0; // This will cause an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
ii) Multiple Catch Clauses:
When dealing with multiple types of exceptions that might occur within a try block, you can
use multiple catch clauses to handle each type of exception differently. Here's a Java example:
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // This will cause an ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e.getMessage());
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
}
iii) Throw:
The throw keyword is used to manually raise an exception in your code. You can use it when
you encounter a situation that warrants an exceptional condition. Here's a Java example:
public void validateAge(int age) throws IllegalArgumentException {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative.");
}
System.out.println("Age is valid: " + age);
}
iv) Throws:
The throws keyword is used in method declarations to indicate that the method might throw
a speci ic type of exception. It's used to notify callers of the method that they need to handle the
potential exceptions. Here's a Java example:
public void readFile(String ilename) throws IOException {
// Code to read a ile
}
v) Finally:
The finally block is used to define a sec on of code that is guaranteed to be executed, regardless
of whether an excep on was thrown or not. It's o en used for resource cleanup.
9. Demonstrate the working of nested try blocks, with suitable examples and syntax.
Ans:
Nested try blocks are used when you have a try block within another try block. This structure
allows you to handle different levels of excep ons at various scopes
Syntax
try {
try {
} finally {
} finally {
}
class Main {
// main method
public static void main(String args[]) {
try {
int a[] = {30, 45, 60, 75, 90, 105, 120, 140, 160, 200};
// displaying element at index 8
System.out.println("Element at index 8 = "+a[8]);
// another try block
try {
System.out.println("Division");
int res = 100/ 0;
}
catch (ArithmeticException ex2) {
System.out.println("Sorry! Division by zero isn't feasible!");
}
}
catch (ArrayIndexOutOfBoundsException ex1) {
System.out.println("ArrayIndexOutOfBoundsException");
}
}
}
Output
Element at index 8 = 160
Division
Sorry! Division by zero isn't feasible!
10. Demonstrate the use of a user-de ined exception class with a suitable example.
Ans:
User-de ined exception classes allow you to create custom exceptions that suit your
application's speci ic needs. To create a user-de ined exception, you need to create a new class
that extends an existing exception class (usually Exception or one of its subclasses). Here's an
example in Java:
Output
Caught
GeeksGeeks
MODULE-03
1. What is a Package? What are the steps involved in creating user-defined Packages?
Ans:
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
Steps Involved in creating User defined Packages are
o Create Directory Structures
o Create Java Files
o Compile
o Use the Package
o Compile & Run
Create Directory Structure: Packages are organized as directories within the source code
directory. The package name corresponds to the directory structure. For example, if you
want to create a package named com.mycompany.myapp, create the directory structure
as src/com/mycompany/myapp.
Create Java Files: Inside the package directory, create Java source files with the desired
classes or functions. Each Java file should begin with a package declaration to indicate
which package it belongs to. For example:
package com.mycompany.myapp;
public class MyClass {
// class code here
}
Compile: Compile the Java files using the command-line compiler or an integrated
development environment (IDE). You need to navigate to the root directory of your source
files and compile using the package structure. For example:
javac src/com/mycompany/myapp/MyClass.java
Use the Package: In other parts of your code or in other projects, you can import and use
the classes from your created package. Import the package at the beginning of your Java
file using an import statement. For example:
import com.mycompany.myapp.MyClass;
Ans:
I. Public: Members marked as public are accessible from anywhere, both within the same
class and from outside the class. There are no restrictions on accessing public members.
} }
II. Protected: Members marked as protected are accessible within the same class,
subclasses (even if they are in different packages), and within the same package. They
are not accessible from outside the package if they are not part of a subclass.
package com.mycompany.myapp;
package com.mycompany.myapp;
class MyPackageClass {
int defaultField; // package-private
void defaultMethod() {
// method code here
}
}
IV. Private: Members marked as private are accessible only within the same class. They
are not accessible from subclasses, other classes within the same package, or from
outside the package.
3. Define an Interface? List the differences between an Interface and an Abstract Class with
syntax.
Ans:
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
4. What is the alternative approach to implementing multiple inheritances in Java? Explain
with an example.
Ans:
In Java, the alternative approach to achieving multiple inheritance is by using
interfaces. Interfaces allow a class to inherit multiple sets of method contracts without
introducing the complexities and ambiguities associated with multiple inheritance
through classes.
In this approach, a class can implement multiple interfaces, each defining a set of
methods that the implementing class must provide. This allows a class to inherit
behavior from multiple sources while avoiding the complexities and ambiguities
associated with traditional multiple class inheritance.
Ex:
// Interface for flying behavior
interface Flying {
void fly();
}
void chirp() {
System.out.println("Bird is chirping.");
}
}
void engineSound() {
System.out.println("Airplane engine sound.");
}
}
// Class representing a flying object that inherits from both Bird and Airplane through
interfaces
class FlyingObject implements Flying {
private Bird bird = new Bird();
private Airplane airplane = new Airplane();
@Override
public void fly() {
bird.fly(); // Delegating the fly behavior to Bird
airplane.fly(); // Delegating the fly behavior to Airplane
}
// You can also access methods specific to Bird and Airplane through the FlyingObject
object
// flyingObject.chirp(); // Error: chirp() is not a method of FlyingObject
// flyingObject.engineSound(); // Error: engineSound() is not a method of FlyingObject
}
}
Multithreading is a function of the CPU that permits multiple threads to run independently
while sharing the same process resources. A thread is a conscience sequence of instructions
that may run in the same parent process as other threads.
Multithreading allows many parts of a program to run simultaneously. These parts are
referred to as threads, and they are lightweight processes that are available within the
process. As a result, multithreading increases CPU utilization through multitasking. In
multithreading, a computer may execute and process multiple tasks simultaneously.
Responsiveness
Resource Sharing
Economy
Utilization of Multiprocessor Architecture
Resource Sharing
All the threads of a process share its resources such as memory, data, files etc. A
single application can have different threads within the same address space using
resource sharing.
Responsiveness
Program responsiveness allows a program to run even if part of it is blocked using
multithreading. This can also be done if the process is performing a lengthy
operation. For example - A web browser with multithreading can use one thread for
user contact and another for image loading at the same time.
Utilization of Multiprocessor Architecture
In a multiprocessor architecture, each thread can run on a different processor in
parallel using multithreading. This increases concurrency of the system. This is in
direct contrast to a single processor system, where only one process or thread can
run on a processor at a time.
Economy
It is more economical to use threads as they share the process resources.
Comparatively, it is more expensive and time-consuming to create processes as they
require more memory and resources. The overhead for process creation and
management is much higher than thread creation and management.
6. What are threads? Explain the different ways of creating threads in Java.
Ans:
The direction or path that is taken while a program is being executed is called Thread
The Different ways of creating Threads are
o By extending Thread class
o By implementing Runnable interface.
EX:
class MyThread extends Thread {
MyThread(){
Super(“one”);
}
public void run (){
system.out.println(“New Thread Created “);
Thread t=Thread. current Thread();
System.out.println(t);
}
}
Public class main
{
Public static void main(string[]args){
My Thread ob=new My Thread();
Ob.start();
}
}
Output
New Thread Created
Thread[one,5,Main]
EX:
class MyRunnable implements Runnable {
public void run() {
// Code to be executed by the thread
}
}
New: The thread is in this state when it is first created but has not yet been started by calling
its start() method.
Runnable: Once the thread's start() method is called, it enters the runnable state. In this
state, the thread is eligible to be executed by the CPU, but it might not necessarily be
executing at any given moment due to the CPU scheduler's decisions.
Running: A thread enters the running state when the CPU scheduler selects it for
execution. In this state, the thread's code in the run() method is actively being executed.
Blocked/Waiting: Threads in this state are temporarily inactive. They are waiting for some
event to occur before they can proceed. This could be waiting for I/O, acquiring a lock, or
other synchronization events.
Timed Waiting: Threads in this state are waiting for a specified amount of time. They will
automatically transition to the runnable state once the timer expires or the event they are
waiting for occurs.
Terminated/Dead: A thread enters this state when it has completed its execution or if an
unhandled exception occurs in its code. Once a thread is terminated, it cannot be started
again.
┌──────────
│ NEW │
└───────────┘
│
▼
┌───────────┐
│RUNNABLE │
└───────────┘
│
▼
┌───────────┐
│ RUNNING │
└───────────┘
│
▼
┌───────────┐
│ BLOCKED │
└───────────┘
│
▼
┌───────────┐
│TIMED WAIT │
└───────────┘
│
▼
┌───────────┐
│TERMINATED │
└───────────┘
8. Why main thread is important? Write a Java program that creates multiple child threads
and also ensures that the main thread stops last.
Ans:
The main thread in a Java program is important for several reasons:
Program Entry Point: The main thread is where the execution of a Java program begins.
It's the first thread to be executed when you run a Java application, and it serves as the
entry point for your program.
Control and Coordination: The main thread is responsible for coordinating the execution
of other threads in the program. It can create, start, and manage other threads, and it can
wait for their completion.
Cleanup: The main thread is typically used to perform cleanup tasks and release resources
when the program is about to exit. This ensures that resources are properly disposed of
before the program terminates.
@Override
public void run() {
System.out.println("Child Thread " + id + " is running.");
try {
Thread.sleep(2000); // Simulate some work
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Child Thread " + id + " has completed.");
}
}
I. Isalive[]
The isAlive() method is used to determine whether a thread is still active and
running. It returns true if the thread on which it's called is currently executing or has
not yet started execution, and false if the thread has finished executing.
Ex:
Thread thread = new Thread(() -> {
// Thread's task
});
thread.start();
II. Join[]
The join() method is used to make the calling thread wait for the thread on which
it's called to complete its execution. This is often used to ensure that specific threads
complete before the main thread continues or before another thread's execution.
try {
thread1.join(); // Wait for thread1 to complete
thread2.join(); // Wait for thread2 to complete
} catch (InterruptedException e) {
e.printStackTrace();
}
Syntax: Thread.yield();
Ex:
Thread thread1 = new Thread(() -> {
// Thread 1's task
Thread.yield();
// Rest of Thread 1's task
});
Thread thread2 = new Thread(() -> {
// Thread 2's task
});
thread1.start();
thread2.start();
10. Describe the thread priority. How to assign and get the thread priority?
Ans:
Thread priority in Java is a concept that allows you to assign a priority level to each thread,
indicating its relative importance in terms of CPU time allocation. Threads with higher priority
values are more likely to be scheduled by the thread scheduler to run before threads with lower
priority values.
Java defines thread priorities using integer values ranging from Thread.MIN_PRIORITY
(1) to Thread.MAX_PRIORITY (10), with Thread.NORM_PRIORITY (5) as the default.
Higher values represent higher priority.
I. Assigning Thread Priority:
To set the priority of a thread, you can use the setPriority(int priority) method
provided by the Thread class.
Ex:
Thread thread = new Thread(() -> {
// Thread's task
});
thread.start();
II. Getting Thread Priority:
To retrieve the current priority of a thread, you can use the getPriority() method
provided by the Thread class.
Ex:
int priority = thread.getPriority();
System.out.println("Thread priority: " + priority);
11. What do you mean by synchronization? How it is achieved for threads in Java? Explain
with syntax.
Ans:
Thread Synchronization is a process of allowing only one thread to use the object
when multiple threads are trying to use the particular object at the same time.
To achieve this Thread Synchronization we have to use a java keyword or modifier
called “synchronized”.
Synchronization in java is the capability to control the access of multiple threads to
any shared resource.
General Syntax:
synchronized(objectidentifier)
{
// Access shared variables and other shared resources;
}
Using the synchronized Keyword:
You can use the synchronized keyword to define critical sections of code
that should be accessed by only one thread at a time. This can be applied to methods
or blocks of code.
class SharedResource {
private int count = 0;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class SharedResource {
private Lock lock = new ReentrantLock();
private int count = 0;
wait(): It tells the calling thread to give up the lock and go to sleep until some other thread
enters the same monitor and calls notify().
notify(): It wakes up one single thread called wait() on the same object. It should be noted
that calling notify() does not give up a lock on a resource.
Syntax:public final void notify()
notifyAll(): It wakes up all the threads called wait() on the same object.
Syntax:public final void notifyAll()
13. Write a short note on the Bounded buffer problem.
Or
14. With suitable examples explain the Producer-Consumer problem.
Ans:
The Bounded buffer Problem can also be called a Producer consumer problem. The
problem covers two processes—the producer and the consumer—that share a single, fixed-
size buffer that serves as a queue.
o Data generation, buffering, and restarting are all tasks performed by the producer.
o The consumer simultaneously consumes the data (i.e., removed from the buffer),
one piece at a time.
The producer must either sleep or destroy data when the buffer is full. When a consumer
later takes an item out of the buffer, the producer is notified, and the buffer is once more
filled. In the same way, if the consumer detects that the buffer is empty, it can nod off. The
consumer is awakened when the producer inserts data into the buffer to find significance.
Buffer Data Structure: The buffer is a shared data structure that can hold a fixed number
of items. Both producer and consumer threads interact with this buffer.
Producer Threads: These threads are responsible for adding items to the buffer. They
need to ensure that they don't add items when the buffer is full.
Consumer Threads: These threads are responsible for removing items from the buffer.
They should wait when the buffer is empty.
Synchronization Mechanisms: To avoid race conditions and coordinate the behavior of
producer and consumer threads, synchronization mechanisms like locks, semaphores, or
condition variables are commonly used.
Deadlocks and Starvation: Incorrect synchronization can lead to deadlocks, where
threads are blocked indefinitely. Starvation might occur if certain threads are consistently
unable to access resources.