0% found this document useful (0 votes)
6 views50 pages

Java Notes 2 Final

Object-Oriented Programming (OOP) is a programming paradigm that uses classes and objects to model real-world entities, focusing on principles like encapsulation, abstraction, inheritance, and polymorphism. Inheritance allows classes to inherit properties and methods from other classes, while encapsulation restricts access to an object's internal state. Java supports single inheritance and uses the Java Virtual Machine (JVM) for platform independence, enabling code portability across different systems.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views50 pages

Java Notes 2 Final

Object-Oriented Programming (OOP) is a programming paradigm that uses classes and objects to model real-world entities, focusing on principles like encapsulation, abstraction, inheritance, and polymorphism. Inheritance allows classes to inherit properties and methods from other classes, while encapsulation restricts access to an object's internal state. Java supports single inheritance and uses the Java Virtual Machine (JVM) for platform independence, enabling code portability across different systems.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

1) What is OOP? Difference between Procedural and OOP.

[wbsu 2023]
Ans:- Object-Oriented Programming is a way of programming where we use classes and
objects to create programs based on the real world. These objects have data (called
attributes) and functions (called methods) inside them. In OOP, computer programs are
made using objects that act like real-life things and can interact with each other.

1.a) Define object in Java. [2021] [DSE B2]


Ans:- An object in Java is a real-world entity that is created from a class. It is an instance of a
class that contains state (fields/variables) and behavior (methods/functions).

Example:-
Car myCar = new Car();

Here, myCar is an object of the Car class.


8.a) Discuss the basic principle of object oriented programming.(DSE B2) [2021] 6
Ans:- Object-Oriented Programming (OOP) is a programming style based on the concept of
objects. An object stores data (called attributes) and functions (called methods) that work on
that data. The main aim of OOP is to make programs modular, reusable, and easy to maintain.

The four main principles of OOP are:


1. Encapsulation:
Encapsulation means binding data and methods inside a class. It hides the internal
details of an object and only shows what is necessary using access modifiers like private
and public.
Example: In a BankAccount class, the account balance is hidden and can only be
changed using methods like deposit() or withdraw().
2. Abstraction:
Abstraction means showing only the important features and hiding the complex parts.
It reduces code complexity and increases readability.
Example: When using a print() method, the user does not need to know how printing
happens inside.
3. Inheritance:
Inheritance means a class (child class) can use the properties and methods of another
class (parent class). It helps in code reuse.
Example: A class Dog can inherit from a class Animal and use its methods like eat() or
sleep().
4. Polymorphism:
Polymorphism means the same function or method can work in different ways
depending on the object. It increases flexibility in programming.
Types of Polymorphism:
 Compile-time Polymorphism (Method Overloading)
 Run-time Polymorphism (Method Overriding)
Example: A method draw() behaves differently for a Circle and a Rectangle.

Inheritance
3.a) What are the different forms of Inheritance? 5 [DSE B2]
Ans:- There are five common types of inheritance in object-oriented
programming: single, multiple, multilevel, hierarchical, and hybrid. Each type defines a
different way classes can inherit properties and behaviors from other classes.
Here's a breakdown of each type:
 Single Inheritance:A class inherits from only one parent class. This is the simplest
form and provides a direct parent-child relationship.
 Multiple Inheritance:
A class inherits from multiple parent classes. This allows a class to combine features from
different sources, but can lead to complexities.
 Multilevel Inheritance:
A class inherits from a class that itself inherits from another class, creating a chain of
inheritance. This forms a hierarchy of parent and child classes.
 Hierarchical Inheritance:
Multiple classes inherit from a single parent class. This creates a tree-like structure
where several classes share common properties from the parent.
 Hybrid Inheritance:
This type of inheritance combines two or more of the other inheritance types. For
example, it could involve multilevel and multiple inheritance.

6.a) Describe the uses of super keyword with respect to inheritance. Give an example.
[2021-22] dse 1 (5)
Ans:- bhebe dekhbo
5. (a) How is inheritance incorporated(babohar) in Java?
(b) Is it possible in Java to have multiple inheritance? If not, then how can it be
implemented in Java? [wb 2023] 2+(2+4)
Ans:- In Java, the extends keyword is used to do inheritance. It allows a subclass to get
the fields and methods of the superclass. When one class extends another class, it
means it gets all the non-primitive members (like fields and methods) from the parent
class. The subclass can also change (override) or add new features to them.
Example: In the following example, Animal is the base class and Dog, Cat and Cow are
derived classes that extend the Animal class.

3.b) The main reason why Java does not support multiple inheritance is because Java is
designed to be simple and clear, not complex. If multiple inheritance is allowed, it can
create confusion and problems when a class has more than one parent. So, Java avoids
that.
In Java, a class can inherit from only one superclass using the extends keyword. This is
called single inheritance. It makes a clear class structure, where every class has only one
parent. This helps in writing clean code, makes it easier to maintain, and avoids any
conflicts.
Next part in khata
3. (a) What do you mean by inheritance? What purpose does it serve? Explain. 4
(b) How single inheritance is implemented in Java? Explain with an example. 4 [2021-
2022] DSE-1
3.a) Ans:- Java Inheritance is a fundamental concept in OOP(Object-Oriented
Programming). It is the mechanism in Java by which one class is allowed to inherit the
features(fields and methods) of another class. In Java, Inheritance means creating new
classes based on existing ones. A class that inherits from another class can reuse the
methods and fields of that class.
Syntax
class ChildClass extends ParentClass {

// Additional fields and methods


}


 Code Reusability: The code written in the Superclass is common to all subclasses.
Child classes can directly use the parent class code.
 Method Overriding: Method Overriding is achievable only through Inheritance. It is
one of the ways by which Java achieves Run Time Polymorphism.
 Abstraction: The concept of abstraction where we do not have to provide all details,
is achieved through inheritance. Abstraction only shows the functionality to the user.
3.b) Single Inheritance in Java means that a class (called a subclass or child class) inherits
properties and methods from only one superclass (parent class).
This allows code reuse and method overriding.
Next part in khata
Polymorphism
1. Describe method overloading and method overriding. 5
Ans:- When a class has two or more methods with the same name but different
parameters, the respective method is called based on the arguments passed. The
respective method body is dynamically bound to the calling line. This mechanism is
known as method overloading.
Example:-
In method overriding, the super class and subclass have methods with the same name,
including parameters. JVM calls the respective method based on the object used to call
the method. In overriding, the return types should also be the same.
EXAMPLE
2. What restrictions are placed in method overloading and method overriding?
[wbsu 2023 hons] (3+3)
Ans:- ✅ Restrictions in Method Overloading:
1. Method name must be the same.
2. Parameter list must be different (type, number, or order).
3. Return type alone is not enough to distinguish overloaded methods.
4. Can’t overload by just changing access modifier.
✅ Restrictions in Method Overriding:
1. Method name and parameter list must be exactly same as superclass method.
2. The overriding method cannot reduce visibility (e.g., from public to private).
3. The overriding method cannot throw broader exceptions than the overridden
method.
4. Final, static, or private methods cannot be overridden.
5. The subclass method should use the @Override annotation for clarity
5.b) Explain the differences between method overriding and method overloading. Give
example. [2020, held 21] 5
1.f ) Differentiate between abstract class and interface. (2023) 2
Ans:-

1.h) Differentiate class, abstract class.[2021-22] 2


5. (a) What do you mean by encapsulation? (b) How encapsulation is achieved in
Java? Explain with an example. (c) Briefly explain the use of final keyword. [2021-
2022] 2+3+3
Ans:- Encapsulation is the process of grouping data (variables) and methods (functions) that
work on that data into a single unit called a class.

It helps to hide the internal details of an object from the outside world. Only selected
parts are made accessible using access modifiers like private, public, or protected. This
ensures that the data is protected from direct changes and can only be modified through
methods.
c) The final keyword in Java is used to restrict modification of variables, methods,
and classes. It helps to ensure security, consistency, and immutability in the program.

1. Final Variable

When a variable is declared as final, its value cannot be changed once it is assigned.
It acts as a constant.
Example:

final int x = 10;

// x = 20; // This will cause a compile-time error

2. Final Method

A method declared as final cannot be overridden by any subclass. This is useful


when the method's implementation should not be changed.
Example:

class A {

final void display() {

System.out.println("Hello");

3. Final Class

A class declared as final cannot be extended (inherited). It is used when the class
functionality should not be modified by inheritance.

Example:

final class Test {

// class content

// class Demo extends Test { } // Error


 Conclusion:

The final keyword is used to make variables constant, prevent method overriding,
and stop class inheritance. It is mainly used for safety and to avoid unintended
changes in the code.

DSE-b2 [2021]

Ans:- see above answer

4.b) What do you mean by abstraction?[2021-22] [DSE B1]

Ans:- Abstraction is one of the key principles of object-oriented programming. It means


hiding the internal implementation details of a class and showing only the necessary
functionalities to the user.

In simple words, abstraction allows us to focus on what an object does instead of how
it does it.

EXAMPLE:-

abstract class Animal {

abstract void makeSound(); // abstract method

class Dog extends Animal {

void makeSound() {

System.out.println("Bark");

}
How does a class accomplish data hiding? 2[bu 2022]

Ans:- In Java, data hiding is achieved by declaring class variables as private and providing
public getter and setter methods to access and update the values.

This means the internal state of an object is hidden from outside classes and can only
be accessed through controlled methods. It helps in protecting data, preventing
unauthorized access, and ensuring encapsulation.

Steps to Achieve Data Hiding:

1. Declare variables as private so they are not directly accessible from outside the class.
2. Provide public methods (getters and setters) to access and modify those variables.

Example

JVM and Platform Independence

1.a) Why Java is called platform independent language?[wbsu 2023]

Ans:- Java is platform-independent because its source code is compiled into


bytecode, which can run on any system that has a Java Virtual Machine (JVM).
This allows the same Java program to run on different platforms without
modification.

8.a) Why Java is called a system independent programming language?[dse 1] 21-22

Ans:- Java is called system-independent because it uses the Java Virtual Machine
(JVM) to run programs.
Java code is compiled into platform-neutral bytecode, which can be executed on any system
with a JVM, regardless of the operating system or hardware.
Thus, the same Java program runs on any system, making it system-
independent.

1.f) Why is Java called a compiler-interpreter language? [BU 2022]

Ans:- Java is called a compiler-interpreter language because it uses both a compiler and an
interpreter to run programs.
Java code is first compiled by the Java compiler (javac) into bytecode, and then the Java
Virtual Machine (JVM) interprets this bytecode and executes it line by line on any system.

What is a Java virtual machine (JVM)? (extra)

Ans:- JVM is a virtual machine that enables the execution of Java bytecode. The JVM acts as
an interpreter between the Java programming language and the underlying hardware. It
provides a runtime environment for Java applications to run on different platforms and
operating systems.

1.f) What is the role of JVM? [DSE b2] 2021

Ans:- The Java Virtual Machine (JVM) plays a key role in executing Java programs.
1) It reads the compiled bytecode and converts it into machine code specific to the
operating system.
2) This allows Java programs to run on any platform, making Java platform-independent.

3) It also handles memory management, security, and exception handling during program
execution.

1.b) What is the role of Garbage Collection?( 2023) 2

Ans:-

1) Java garbage collection is an automatic process that manages memory in the heap.
2) It identifies which objects are still in use (referenced) and which are not in use
(unreferenced).
3) It removes the objects that are unreachable (no longer referenced).
4) The programmer does not need to mark objects to be deleted explicitly. Garbage
collection is implemented within the JVM.

1.a) What do you mean by portability of a program? Is Java language portable? [DSE
1] [2021-2022][WBSU]

Ans:- Portability of a Program:

Portability means that a program written on one system (platform) can run on another system
without needing any changes in the code.
In simple words, a portable program can work on different operating systems (like Windows,
Linux, or Mac) without rewriting it.
Is Java Portable?

✅ Yes, Java is a portable language.

Java is portable because Java programs are compiled into bytecode, which can run on any
system that has the Java Virtual Machine (JVM).
Since JVM is available for all major operating systems, the same Java program can run
anywhere — this makes Java write once, run anywhere.

Garbage collection

3.b.i) BU 2022

Ans:- In Java, Garbage Collection (GC) is a process by which the Java Virtual Machine
(JVM) automatically removes unused or unreferenced objects from the memory. This helps
to free up memory space and improve the performance and efficiency of the Java program.

1.f) How does garbage collection take place in Java? Bu 2019

Ans:- In Java, garbage collection is the process by which the Java Virtual Machine (JVM)
automatically removes objects from memory that are no longer needed or referenced. This helps
free up memory and keeps the program efficient.

1.b) What is the role of Garbage Collection? WBSU [2023] 2

Ans:- Garbage Collection in Java is used to automatically manage memory by deleting objects that
are no longer in use. It helps in:

1. Freeing up memory by removing unreferenced objects from the heap.


2. Preventing memory leaks, which can slow down or crash a program.
3. Improving performance by keeping the memory clean and ready for new objects.

2.a) What is a constructor? Discuss about different types of constructors. [DSE B2]
[2021] 5

Ans:- A constructor in Java is a special method that is automatically called when an object of
a class is created.
It is used to initialize the object.
It has the same name as the class and does not have any return type, not even void.

1. Default Constructor

If you don’t write any constructor in your class, Java automatically provides a default
constructor.
It doesn’t take any arguments and doesn’t do any special task—just helps in creating an
object.

Example
2. No-Argument Constructor (User-Defined)

This is a constructor you write yourself, and it doesn’t take any parameters.
It can be used to print a message or set default values when the object is created.

Example:
3. Parameterized Constructor

This constructor takes one or more values (parameters) when the object is created.
It is used to give initial values to variables inside the object.

Example:
4. Copy Constructor (Conceptual in Java)

Java doesn’t have a built-in copy constructor like C++, but we can make one.
It takes an object of the same class and copies its data to the new object.

Example:
5. Private Constructor

If a constructor is marked as private, objects cannot be created directly from outside


the class.
This is useful in cases like the Singleton design pattern, where you want only one object
of the class.

Example:

Conclusion:
Constructors are used to create and initialize objects. Java supports different types of
constructors for different use cases, like giving default values, setting custom data,
copying existing data, or restricting object creation.
2.c) Differentiate between default constructor and parameterized constructor. [WBSU]
[2021-2011][DSE 1]

3.b) What is constructor? How do you define parameterized constructor? Explain with
a program. 2+4[BU CC3 2019]

Ans:- A constructor in Java is a special method that is automatically called when an object of
a class is created.
It is used to initialize the object.
It has the same name as the class and does not have any return type, not even void.

SYNTAX:

Next part

A parameterized constructor in Java is a constructor that accepts arguments (parameters)


to initialize the data members of an object during its creation.
It allows different objects of the same class to be initialized with different values.

The main purpose of a parameterized constructor is to assign user-defined values to instance


variables at the time of object creation, instead of assigning default values.
A class can have multiple parameterized constructors with different sets of parameters
(this is called constructor overloading).

NEXT PART :- FOR SYNTAX AND EXAMPLE FOLLOW ABOVE PAGE

(MY SUGGESTION)

2.d) What is constructor overloading?[dse 1][2021-2022]

Ans:- Constructor overloading means creating many constructors in one class with different
parameters.
It helps to create objects in different ways and give different values when the object is made.
Java decides which constructor to run based on the number or type of values you pass.
All constructors have the same name as the class, but their parameter lists are different.
It is a part of compile-time polymorphism.

SYNTAX:-
4.b) Explain multilevel inheritance with example. [2020 held 21] 5

Ans:- Multilevel Inheritance in java involves a class extending to another class that is already
extended from another class. In simple words it includes inheriting a class, which already
inherited some other class. We can create hierarchies in Java with as many layers of
Inheritance as we want. This means we can utilize a subclass as a superclass. In this case,
each subclass inherits all of the traits shared by all of its superclasses.

Example
Keywords

2.b) Explain the use of 'this' keyword with an example. [cu 2021] 2

Ans:- The this keyword in Java is a reference variable that refers to the current object of the
class. It is mainly used to distinguish between instance variables and parameters when they
have the same name. (DEFINITION)

Example

1.d) What is the function of this() in Java? (WBSU 2020-2021) (DSE 1) 2

Ans:- It is mainly used to,

 Call current class methods and fields

 To pass an instance of the current class as a parameter

 To differentiate between the local and instance variables.

Using "this" reference can improve code readability and reduce naming conflicts.

1.D) What are the two uses of keyword super in Java? [DSE 1][WBSU 2021-2022] 2

Ans:- It is used to call superclass methods, and to access the superclass constructor.

The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.

DEFINITION:-

The super keyword refers to superclass (parent) objects. It is used to call superclass methods,
and to access the superclass constructor. The most common use of the super keyword is to
eliminate the confusion between superclasses and subclasses that have methods with the same
name.

EXAMPLE:-

2.a) Explain the use of final keyword in variable, method and class. 3 (wbsu 2023)

Ans:- Use of final with Variables

 Makes the variable constant (value cannot be changed).


 Helps in defining fixed values like PI, MAX_SPEED, etc.

Example:

final int age = 18;

2. Use of final with Methods

 Prevents method overriding in subclasses.


 Useful when you want to protect important methods from being modified.

Example:

final void display() {

System.out.println("Cannot be overridden");

3. Use of final with Classes

 Prevents the class from being inherited.


 Used to create secure and complete classes.
Example:

final class Animal { }

1.e) Differentiate between final and finally.[2020-21] [WBSU]

Feature final finally


Type Keyword Block
Used to declare constants, prevent method Used to execute important code (like
Purpose
overriding, and inheritance of classes. cleanup) after a try-catch block.
Used with try-catch for exception
Usage Applied to variables, methods, and classes.
handling.
<br>try { // code } <br>finally { //
Example final int x = 10; final void display() {}
cleanup code }
Always executes, whether an
Behavior Prevents changes or modifications.
exception occurs or not.

Access Specifiers/Modifiers

2.b) Can we declare a class as 'private'? Explain briefly. (2021-2022) (DSE 1)

Ans:- No, we cannot declare a top-level class as private or protected. It can be


either public or default (no modifier). If it does not have a modifier, it is supposed to have a default
access.

Syntax

// A top level class

public class TopLevelClassTest {

// Class body

1.d) What are the different access specifier in Java? [2021][DSE b2] 2

Or, 3.b) Discuss the different access modifiers in java. [BU 2019] 4

Ans:- Java has four access modifiers: public, private, protected, and default. These modifiers
control the visibility and accessibility of classes, methods, and variables.

Here's a breakdown:

 public:
The most accessible, allowing access from anywhere (within the class, outside the class, and
across different packages).

 private:

The most restrictive, limiting access to only within the declaring class.

 protected:

Allows access within the same package and also by subclasses in different packages.

 default (package-private):

When no access modifier is specified, it defaults to this level, granting access within the same
package only.

These access modifiers play a crucial role in encapsulation, a fundamental principle of object-
oriented programming, by controlling which parts of the code can interact with each other.

Packages and Interfaces

3.c) Define package. Write steps for creating a user defined package. How we can add a
new class into a user defined package? [BU 2019] 2+4+4

Ans:- A package in Java is used to group related classes. Think of it as a folder in a file directory. We
use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided
into two categories:

Built-in Packages (packages from the Java API)

User-defined Packages (create your own packages)

Next answer

1. Create a Java file and declare a package at the top:


Write the package statement as the first line in your Java file.

package packagename;

2. Define your class or interface in the same file:


Create a public class (or interface) after the package declaration.

public class ClassName {

// class body

3. Save the file with the class name:


Save the file with the same name as the public class (e.g., ClassName.java).
4. Compile the Java file with -d option to specify package directory:
Use the following command in terminal or command prompt:

javac -d . ClassName.java

5. A directory with the package name will be created automatically:


This directory will contain the compiled .class file.

6. Create another Java file to use the package:


Use the import statement to access the class from the package.

import packagename.ClassName;

7.Use the class in your program and run it:


Create an object and use its methods as needed, then compile and run.

3.b) How does package differ from Interface? Explain it with suitable example. 5+5 [cu
2021 gen]

Characteristics Package Interface

Organize related classes and Define a contract for classes to


Purpose interfaces into a single unit. implement.

Declared using interface


Declared using package keyword.
Syntax keyword.

Define method signatures that


Group classes and interfaces based classes implementing the
on functionality. interface must provide
Usage implementations.

Packages can have access modifiers Interface methods are implicitly


Accessibility to control visibility. public and abstract.

Supports multiple inheritance as


Does not support multiple
Multiple a class can implement multiple
inheritance.
Inheritance interfaces.

public interface Printable {


package
void print();
com.geeksforgeeks.mypackage;
Example }
2.c) What are the differences between interface and class? 5 [BU 2022]

1.h) What are the similarities between interface and class? [2020-2021] wbsu (2)

 Both Define a Type:

 Interfaces and classes can both be used to define a data type that can be used to
declare objects or references.

 Can Have Variables and Methods:

 Both can contain variables and methods.


 (In interfaces, variables are public static final by default.)

 Can Be Used in Inheritance:

 Classes can inherit from other classes, and interfaces can also be extended or
implemented, supporting inheritance.

 Can Be Public or Default Access:

 Both can have public or default (package-private) access modifiers.


 Can Be Compiled and Stored as .class Files:

 After compilation, both are converted into bytecode (.class) files used by the JVM.

1.h) Differentiate between Class and Abstract Class in Java. 2 marks (WBSU 2021-
2022)

✅ Difference Between Class and Abstract Class:

Point Class Abstract Class


A class is a blueprint to An abstract class is a class with one or
Definition
create objects. more abstract methods.
Objects can be created
Object Creation Cannot create objects directly from it.
directly.
Method All methods must have a Can have both abstract (no body) and
Implementation body. concrete methods.
Keyword Used class abstract
Used for full Used for partial implementation or
Use Case
implementation. common base.
Constructors and Can have constructors and Also supports constructors and
Variables variables. variables.

Exception Handling

1.d) What are exceptions? 2 [wbsu 2023]

Ans:- An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.

1.b) What is the difference between error and exception? 2 (WBSU 2020, held 21)

Ans:-

Errors Exceptions

We can recover from exceptions by either


Recovering from Error is not possible. using try-catch block or throwing
exceptions back to the caller.
Errors Exceptions

Exceptions include both checked as well as


All errors in java are unchecked type.
unchecked type.

Errors are mostly caused by the


Program itself is responsible for causing
environment in which program is
exceptions.
running.

Unchecked exceptions occur at runtime


Errors can occur at compile time. whereas checked exceptions occur at
compile time

They are defined in java.lang.Error They are defined in java.lang.Exception


package. package

Examples : Checked Exceptions :


SQLException, IOException Unchecked
Examples : java.lang.StackOverflowError, Exceptions :
java.lang.OutOfMemoryError ArrayIndexOutOfBoundException,
NullPointerException,
ArithmeticException.

1.a) Is it possible to have a 'try' block without a 'catch' block? [2020 held 2021] wbsu

Ans:- yes, It is possible to have a try block without a catch block by using a final block.

As we know, a final block will always execute even there is an exception occurred in a try
block, except System.exit() it will execute always.

Q) What happens if there is no 'catch' block with a 'try' block in exception handling?

Ans:- If there is no catch block with a try block in exception handling, then a finally block
must be used. The finally block always executes whether an exception occurs or not. If
neither catch nor finally is present, it results in a compile-time error.

1.g) Differentiate between throw and throws.[2021-2022] [DSE 1] WBSU


Ans:-

Q) Illustrate the use of 'throw' and 'throws' in Java.

Ans:- In Java, throw and throws are used for exception handling.

 throw is used to explicitly throw an exception from a method or block of code. It is


followed by an instance of Throwable class or its subclasses.
 throws is used in the method declaration to indicate that the method may throw one
or more exceptions. It notifies the caller of the method to handle those exceptions.

Syntax:

 throw new ExceptionType("Error Message");


 returnType methodName() throws ExceptionType { ... }

6)Briefly describe the behaviour of an user define exception with an example. 5


[2020 held 21] wbsu Ans:- korle khata tei korbo

3.a) How do you create your own exceptions in Java? 4 [BU 2019]

Ans:- Q: How do you create your own exceptions in Java? (5 Marks)

In Java, user-defined exceptions are custom exceptions created by the programmer to


handle specific situations that are not covered by Java's built-in exception classes. This
allows for more meaningful and controlled error handling in a program.

Definition:A user-defined exception is a class that inherits from the Exception class (for
checked exceptions) or the RuntimeException class (for unchecked exceptions). It behaves
like any other exception and can be thrown and caught using the throw and try-catch
mechanism.
Steps to Create a User-Defined Exception:

1. Create a custom exception class by extending Exception or RuntimeException.


2. Define a constructor that calls the superclass constructor with a custom error message.
3. Throw the exception using the throw keyword when a specific condition occurs.
4. Handle the exception using a try-catch block.

Syntax:

class MyException extends Exception {

public MyException(String message) {

super(message);

Advantages of User-Defined Exceptions:

 Helps handle application-specific errors.


 Makes code easier to understand and maintain.
 Provides custom error messages for better debugging.
 Improves the overall robustness and clarity of the program.

Threads

Q) What is a thread?

Ans:- A thread in Java is a lightweight sub-process or a small unit of a process. It is the smallest part
of a program that can run independently and concurrently with other threads.

In simple words, a thread is a separate path of execution in a program. Using threads, we


can perform multiple tasks at the same time, which is called multithreading.

Example:

When you open a webpage, downloading images, loading text, and playing audio can all
happen at the same time using different threads.

1.c) What is a daemon thread in Java? [2021] [DSE B2] [WBSU]

Ans:- In Java, daemon threads are low-priority threads that run in the background to
perform tasks such as garbage collection or provide services to user threads. The life of a
daemon thread depends on the mercy of user threads, meaning that when all user threads
finish their execution, the Java Virtual Machine (JVM) automatically terminates the daemon
thread.
4.b) Explain thread prioritization in Java. (Cu 2021) 5

Ans:- dekhchi khatai

1.d) What is the method used for creating thread in Java? [ bu 2022] 2

Ans:- 1. Thread Class

The Thread class provides constructors and methods for creating and operating on threads.
The thread extends the Object and implements the Runnable interface.

2. Runnable Interface

Any class with instances that are intended to be executed by a thread should implement the
Runnable interface. The Runnable interface has only one method, which is called run().

1.c) What is multithreading? [BU 2019] 2

Ans:- Multithreading is a Java feature that enables the concurrent execution of two or more parts
of a program, maximizing CPU utilization. Each part of such a program is called a thread. So, threads
are lightweight processes within a process.

Example: Imagine a restaurant kitchen where multiple chefs are working simultaneously on
different dishes. This setup ensures faster service and better CPU (chef) utilization, just like
threads in Java.

1.h) What is the need of synchronization of methods? [BU 2019]

Ans:- To stop wrong or mixed-up data:


If many threads change the same data at once, the result can be wrong. Synchronization helps to
avoid that.

To keep threads safe:


Synchronization makes sure that only one thread uses a method or object at a time. This
keeps the program safe and correct.

To stop race conditions:


A race condition happens when two threads are working at the same time and the result
depends on who finishes first. Synchronization controls this.

To do one task at a time without interruption:


Sometimes we want a group of steps to run one after another without any other thread
interrupting. Synchronization helps with that too.

2.a) Describe the thread life cycle. [2020 held 21][wbsu]

Ans:- The life cycle of a thread in Java refers to the various states of a thread goes through. For
example, a thread is born, started, runs, and then dies. Thread class defines the life cycle and
various states of a thread.
Flow Chart of Java Thread Life Cycle

The following diagram shows the complete life cycle of a thread.

States of a Thread Life Cycle in Java

Following are the stages of the life cycle −

 New − A new thread begins its life cycle in the new state. It remains in this state until
the program starts the thread. It is also referred to as a born thread.
 Runnable − After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while the thread waits
for another thread to perform a task. A thread transitions back to the runnable state
only when another thread signals the waiting thread to continue executing.
 Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.

7) Explain wait() method related to thread (5 marks) [WBSU DSE 1][2020 held 21]

Ans:- The wait() method in Java is used to pause the execution of a thread until another
thread notifies it to continue. It is a part of Java’s synchronization system, which helps
threads to communicate and coordinate with each other.

When a thread calls the wait() method on an object, it must first hold the lock (monitor) of
that object. This means the wait() method must be called inside a synchronized block or
method.

Once the thread calls wait(), it releases the lock and goes into the waiting state.
The thread stays in the waiting state until one of the following happens:

1. Another thread calls the notify() or notifyAll() method on the same object.
2. A specified time runs out (if a timeout is used).
3. The thread is interrupted by another thread.

After being notified, the thread tries to get the lock again, and when it gets it, it resumes
execution from where it had paused.

Use of wait():

The wait() method is useful when a thread needs to wait for a certain condition before it can
move forward.
For example, a thread may wait for some data to be ready, for a resource to be free, or for
another thread to complete a task.

1.b) What is the purpose of wrapper class in Java? [2021 DSE B2] WBSU 2

Ans:- To use primitives as objects:


Some Java libraries (like collections) work with objects only, not with primitive types.
Wrapper classes allow us to use primitives in such cases.

Autoboxing and Unboxing:


Java automatically converts between primitives and wrapper objects:

 Autoboxing: int → Integer


 Unboxing: Integer → int

Use in Collections (e.g., ArrayList):


Collections like ArrayList can’t store primitive types directly, but they can store wrapper
objects.

Utility Methods:
Wrapper classes provide useful methods to convert values, parse strings, etc.
Example: Integer.parseInt("123");

Strings

1.e) Describe charAt() method related to String.[DSE 1][2021-2022]

Ans:- The charAt() method is a function of the java.lang.String class. Its purpose is to return
the character at a specified index within a string.

Example

String str = "Hello";

char result = str.charAt(1); // 'e' is at index 1


System.out.println(result); // Output: e

2.b) Describe the substring() and indexOf() methods of String class with suitable
examples. [wbsu 2023]

1. substring() Method:

The substring() method is used to take out a part of a string. It returns a new string starting
from the given position and continues till the end, or up to the specified ending position
(excluding the last position).

SYNTAX

String substring(int beginIndex)

String substring(int beginIndex, int endIndex)

EXAMPLE

String str = "HelloWorld";

System.out.println(str.substring(5)); // Output: World

System.out.println(str.substring(0, 5)); // Output: Hello

2.indexOf() Method:

The indexOf() method is used to find the position of the first time a letter or word appears in
a string. If the letter or word is not found, it gives -1.

Syntax:

int indexOf(char ch)

int indexOf(String str)

Example:

String str = "HelloWorld";

System.out.println(str.indexOf('o')); // Output: 4

System.out.println(str.indexOf("World")); // Output: 5

System.out.println(str.indexOf('z')); // Output: -1

4.b) What is the difference between String equals() and == operator? [WBSU 2023] 2

Ans:-
S.No. == Operator Equals() Method

1. == is considered an operator in Java. Equals() is considered as a method in


Java.

2. It is majorly used to compare the reference It is used to compare the actual content
values and objects. of the object.

3. We can use the == operator with objects We cannot use the equals method with
and primitives. primitives.

4. The == operator can’t compare conflicting The equals() method can compare
objects, so at that time the compiler conflicting objects utilizing the equals()
surrenders the compile-time error. method and returns “false”.

5. == operator cannot be overridden. Equals() method and can be overridden.

8.a) Write down the difference between String class and String Buffer class. 3 [WBSU
2020, held 2021]

Ans:-

S. String StringBuffer
No.

1 String is immutable. It is mutable.

2 It is slow in terms of executing the It is fast in terms of executing the


concatenation task. concatenation task.

3 Here the length of the string class is Here the length can be modified whenever
static. required, as it is dynamic in behaviour.

4 It is less efficient. It is more efficient in nature as compared to


the string class.

5 String consumes more as compared to StringBuffer uses less memory as compared to


the stringbuffer. the string.

5 It utilises a string constant pool to It prefers heap memory to store the objects.
store the values.

6 It overrides both equal() and It cannot override equal() and hashcode()


hashcode() techniques of object class. methods.

9.b) Write short notes on Strings in Java. [2020 held 2021 wbsu] 4

In Java, a String is used to store and work with words and sentences. It is an object that holds
a sequence of characters, such as "Hello" or "Java is fun".

1. Strings are Immutable

The most important feature of a Java String is that it is immutable, meaning once a string is
created, it cannot be changed. If any change is made, Java actually creates a new string with
the updated value instead of modifying the old one.

For example, if we try to change the text of a string, a new object is created in memory with
the new value, and the original string remains unchanged.

2. How to Create a String

There are two main ways to create a string in Java:

 Using string literals:


Example: String greeting = "Hello";
This is the simple way and Java tries to reuse this value if it already exists.
 Using the new keyword:
Example: String name = new String("John");
This always creates a new string object, even if the same value already exists.

3. Common String Methods

The String class has many built-in methods to work with text. Some of the most commonly
used methods are:

 length() – Returns the number of characters in the string.


 charAt(int index) – Returns the character at the given position.
 equals(String str) – Compares two strings and checks if they are equal.
 toLowerCase() and toUpperCase() – Converts the entire string to lowercase or
uppercase letters.
 substring() – Returns a part of the string based on the given index.

4. StringBuilder and StringBuffer

Since Strings are immutable, changing them frequently can be inefficient. For such cases,
Java provides two classes:

 StringBuilder – Used when the string is being changed often. It is fast and suitable
for single-threaded environments.
 StringBuffer – Similar to StringBuilder but safer for multi-threaded programs. It is
slightly slower but thread-safe.

3.d.i) Write notes on Creating and using arrays.(BU 2019) 4

Ans:- (khatai korbo)

Q) Explain public static void main (String args[]) in Java.

Ans: In Java, the method public static void main(String args[]) is the entry point of any
standalone Java program. Each keyword in this statement has a specific meaning:

1. public
It is an access modifier. This means the method can be accessed from anywhere. Since
the Java Virtual Machine (JVM) needs to call this method from outside the class, it must
be public.
2. static
This means the method belongs to the class, not to an object of the class. The JVM does
not create an object to call main(), so it must be static.
3. void
This means the method does not return any value.
4. main
This is the name of the method. It is predefined in Java and the JVM always looks for
this method to start program execution.
5. String args[]
This is a way to pass command-line arguments to the program. It is an array of String
objects.

Miscellaneous but Repeated

2.c) Why Java is preferred for software development? [DSE B2] cu 3 marks

Java is preferred for software development due to the following reasons:

1. Platform Independent – Java programs can run on any operating system using JVM
(Java Virtual Machine), so the same code works everywhere.
2. Object-Oriented – Java uses object-oriented programming, which makes the code
easier to manage, reuse, and maintain.
3. Built-in Libraries – Java provides a rich set of standard libraries that help in faster
and easier development.

7.a) Differentiate between instance variables and class variables. [WBSU 2021-22]

Ans:-

Point Instance Variable Class Variable (Static Variable)


An instance variable is a variable that is A class variable is a variable that is shared
Definition
created for each object of the class. among all objects of the class.
Point Instance Variable Class Variable (Static Variable)
Memory for an instance variable is Memory for a class variable is allocated
Memory
allocated when an object of the class is only once when the class is loaded into
Allocation
created. memory.
Keyword Instance variables are declared without Class variables are declared using the
Used using the static keyword. static keyword.
Instance variables are accessed using Class variables can be accessed using the
Access
object references. class name or object reference.
For example: int age; is an instance For example: static int count; is a class
Example
variable. variable.

3.c) What is static variable and static method?[WBSU 2023] 2

Ans:- Static Variable:

A static variable is a variable that belongs to the class, not to any single object. This means all
objects of the class share the same copy of the variable. It is declared using the static
keyword. Memory for a static variable is given only once when the class is loaded.

Example:

static int count;

Static Method:

A static method is a method that also belongs to the class, not to an object. It can be used
without creating any object of the class. It is declared using the static keyword. A static
method can directly use only static variables. It cannot directly use instance (non-static)
variables or methods.

Example:

static void display() {

System.out.println("Static method called");

8.c) Explain 'new' Operator in Java (2 Marks)[ WBSU 2021-2022]

The new operator in Java is used to create objects of a class. It allocates memory in the heap
and calls the constructor to initialize the object.
Example:

Student s = new Student();

Here, new Student() creates a new object of the Student class.

7.d) Can we override private method? 2 [WBSU dse 1 2021-2022]

Ans:- No, private methods cannot be overridden in Java because they are not accessible
outside the class they are declared in. Since method overriding requires access in a subclass,
and private methods are hidden from subclasses, overriding is not possible.

However, a subclass can define a method with the same name, but it will be treated as a
new method, not an overridden one.

1.g) Illustrate typecasting in Java with an example.(CU 2021 general)

Typecasting in Java means converting one data type into another. It is of two types:

1. Widening (Automatic Typecasting) – Converting a smaller data type into a larger


one.
2. Narrowing (Manual Typecasting) – Converting a larger data type into a smaller one.
This needs explicit casting.

Example:

public class TypeCastingExample {

public static void main(String[] args) {

int a = 10;

double b = a; // Widening – int to double

System.out.println("Widening: " + b);

double x = 9.78;

int y = (int) x; // Narrowing – double to int

System.out.println("Narrowing: " + y);

}
Output:

Widening: 10.0

Narrowing: 9

Explanation:

 int a is automatically converted to double b.


 double x is manually converted to int y using (int).

1.b) Java does not support destructors. Discuss.(BU 2022)

Ans:- Java does not support destructors like C++ because it uses automatic garbage
collection.

In Java, when an object is no longer used, the Garbage Collector automatically deletes it
to free memory. So, there is no need to write destructors manually.

Instead of destructors, Java provides a method called finalize(), but it is rarely used
and not reliable for cleanup tasks.

2.a) What happens if String args[] is not written in main() method? [2021-2022] WBSU

Ans:- If String args[] is not included as a parameter in the main() method signature in Java,
the code will compile successfully. However, when you attempt to run the program using
the Java Virtual Machine (JVM), a runtime error will occur, typically stating "Main method
not found" or "Error: Main method not found in class <YourClass>, please define the main
method as: public static void main(String[] args)".

4.c) Can we apply Modulus operator on floating-point numbers? [DSE 1 2021-2022]


WBSU

Ans:- Yes, Java allows the use of the modulus operator (%) on floating-point numbers like
float and double.

It returns the remainder after dividing one floating-point number by another.

Example:

public class ModulusExample {

public static void main(String[] args) {

double a = 10.5;

double b = 4.2;

double result = a % b;
System.out.println("Result: " + result); // Output: 2.1

So, the modulus operator can be used with both integers and floating-point numbers in Java.

4.b) What is the difference between an executable file and a .class file? [2021-2022]

[DSE 1][WBSU]

Executable File .class File (Java)


It is a file (like .exe) that runs directly on It contains Java bytecode, which runs on the
the operating system. Java Virtual Machine (JVM).
Platform-dependent – runs only on Platform-independent – can run on any OS
specific operating systems. with JVM installed.
Created by compiling programs written in Created by compiling .java files using the Java
languages like C or C++. compiler (javac).
Example: program.exe (runs directly). Example: Hello.class (run using java Hello).

8.b) Name the primitive/single types available in Java.[2021-2022][DSE 1][WBSU]

Ans:- Java has two categories in which data types are segregated

1. Primitive Data Type: These are the basic building blocks that store simple values directly
in memory. Examples of primitive data types are

 boolean

 char

 byte

 short

 int

 long

 float

 double
2. Non-Primitive Data Types (Object Types): These are reference types that store memory
addresses of objects. Examples of Non-primitive data types are

 String

 Array

 Class

 Interface

 Object

9.a) Differentiate between object and object reference. 2 [wbsu 2021-2022] [DSE 1]

Point Object Object Reference


An object is a real instance of a
An object reference is a variable that holds
Definition
class in memory. the memory address of the object.
It contains actual data and behavior
It is used to access or call the methods and
Role
(methods). data of the object.
Automatically created when assigning the
Creation Created using the new keyword.
object to a variable.
Student s = new Student(); → new s is the object reference pointing to that
Example
Student() creates the object. object.

4.a) Java works as "pass by value" or "pass by reference" phenomenon. [WBSU 2023]

Ans:- In Java, method arguments are always passed by value.


This means a copy of the value is passed to methods, not the original variable.

 For primitive types (like int, float), the actual value is passed.
 For objects, the value of the object reference (i.e., memory address) is passed. So,
changes to object data are reflected, but the reference itself cannot be changed to point
to a new object.

👉 Therefore, Java is strictly pass by value, but in the case of objects, it may look like pass
by reference because the reference value is copied.

1.a) How do you define a constant in Java? [BU 2019] 2

Ans:- In Java, a constant is a variable whose value cannot be changed after it is initialized.
Constants are used when a fixed value is needed throughout the program.

Syntax:

final dataType CONSTANT_NAME = value;


 final – makes the variable constant.

 dataType – type of the variable (e.g., int, float, String).

 CONSTANT_NAME – usually written in all capital letters.

 value – the fixed value assigned.

Example:

final int MAX_USERS = 50;

1.b) Write the uses of net and util packages of Java.[BU 2019]

Ans:- ✅ Uses of net and util Packages in Java

🔸 Uses of java.net package:

 Used for network communication between programs.


 Helps in creating client-server applications.
 Supports sending and receiving data over the internet.
 Allows working with IP addresses, URLs, and ports.

🔸 Uses of java.util package:

 Provides data structures like ArrayList, HashMap, etc.


 Used for date and time operations.
 Helps in generating random numbers.
 Supports collection framework utilities like sorting and searching.
 Offers classes for event handling and object manipulation.

1.g) What do you mean by metadata in Java?[BU 2019]

Ans:- In Java, metadata refers to "data about data." It provides additional information and
context about program elements such as classes, interfaces, methods, and fields. This
information can be used by various tools, frameworks, and runtime components to perform
specific actions or provide enhanced functionality.

2.d) How do you define an interface? How do you define multiple inheritance in Java?
[BU 2019] 2+3

Ans:- In Java, an interface is a collection of abstract methods (methods without a body). It is used to
define a contract that other classes can implement.

✔️Syntax:

interface Animal {
void sound(); // abstract method

✔️Implementation by a class:

class Dog implements Animal {

public void sound() {

System.out.println("Barks");

You might also like