0% found this document useful (0 votes)
2 views

JAVA

java question imp

Uploaded by

aadityarp32
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JAVA

java question imp

Uploaded by

aadityarp32
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

JAVA

|Assignment 1

1.​ What is Java? what are features of Java.

Java is a high-level, object-oriented, and


platform-independent programming language developed
by James Gosling at Sun Microsystems (now owned by
Oracle) in 1995. It follows the WORA (Write Once, Run
Anywhere) principle, meaning that Java programs can
run on any platform without modification, thanks to the
Java Virtual Machine (JVM).

Features of Java

Java has several key features that make it widely used in


software development:

1. Object-Oriented

●​ Java follows the OOP (Object-Oriented


Programming) approach, which includes concepts
like Classes, Objects, Inheritance, Polymorphism,
Encapsulation, and Abstraction.​
●​ This makes Java modular, reusable, and
maintainable.​

2. Platform-Independent

●​ Java programs are compiled into bytecode, which


runs on any device with a JVM (Java Virtual
Machine).​

●​ This allows Java to follow the WORA (Write Once,


Run Anywhere) principle.​

3. Simple and Easy to Learn

●​ Java has a clear and readable syntax similar to C++


but with simpler memory management (thanks to
automatic garbage collection).​

●​ It removes complex features like pointers and


multiple inheritance, making it easier to use.​

4. Secure

●​ Java has built-in security mechanisms such as:​


○​ Bytecode verification to prevent malicious code
execution.​

○​ Memory management to prevent memory leaks.​

○​ No use of explicit pointers, reducing


vulnerabilities.​

5. Robust and Reliable

●​ Java has automatic memory management (Garbage


Collection), which prevents memory leaks.​

●​ It has exception handling to manage runtime errors


efficiently.​

6. Multithreading Support

●​ Java supports multithreading, allowing multiple


tasks to run simultaneously.​

●​ This makes Java efficient for applications like


gaming, web applications, and real-time systems.​

7. Distributed Computing
●​ Java has built-in networking capabilities that allow
the creation of distributed applications.​

●​ Technologies like RMI (Remote Method Invocation)


and CORBA help in distributed computing.​

8. High Performance

●​ Though slower than C/C++, Java’s JIT (Just-In-Time)


Compiler improves execution speed.​

●​ Java also uses efficient memory management to


optimize performance.​

9. Dynamic and Extensible

●​ Java supports dynamic memory allocation, reducing


memory wastage.​

●​ It allows interaction with other programming


languages using JNI (Java Native Interface).​

10. Rich API and Community Support


●​ Java provides a vast Standard API (Java Standard
Library) for networking, data structures, database
connectivity, and more.​

●​ It has a large community, making it easy to find


resources and support.​

Conclusion

Java is a powerful, secure, and platform-independent


language widely used for web development, mobile apps
(Android), enterprise applications, and cloud computing.
Its features make it one of the most preferred
programming languages in the industry..

2.​Write difference between procedure oriented and


object oriented programming .

1. Introduction

●​ Procedure-Oriented Programming (POP) is a


traditional programming paradigm that focuses on
functions (procedures).​
●​ Object-Oriented Programming (OOP) is a modern
approach that focuses on objects and classes to
organize code.

2. Key Differences

Feature Procedure-Orien Object-Oriented


ted Programming
Programming (OOP)
(POP)

Approach Follows a Follows a


top-down bottom-up
approach (starts approach (starts
with functions with objects and
and procedures). classes).

Focus Focuses on Focuses on


functions objects and
(procedures). classes.

Data Handling Data is global, Data is


and functions encapsulated
operate on it. inside objects.
Security Less secure as More secure due
data is shared to encapsulation
among all and access
functions. control.

Code Reusability Less reusability; More reusability


code duplication through
is common. inheritance and
polymorphism.

Data Hiding No data hiding, Supports data


as all data is hiding using
accessible. access modifiers
(private,
protected, etc.).

Ease of Harder to modify Easier to


Maintenance and maintain maintain due to
large programs. modular
structure.

Example C, Pascal, Java, C++,


Languages FORTRAN Python, C#
3. Example of POP (C Language)

4.. Example of OOP (Java)


5. Conclusion

●​ POP is function-based, while OOP is object-based.​


●​ OOP provides better security, reusability, and
maintainability than POP.​

●​ Most modern languages like Java, Python, and C++


use OOP because of its advantages.​

3.​Explanation of Terms: Variable, Data Types,


Operator, and Keyword in Java

1. Variable
A variable is a named memory location used to store
values in a program. The value of a variable can change
during execution.

Types of Variables in Java:

1.​ Local Variable – Declared inside a method or block


and can only be used there.​

2.​Instance Variable – Defined inside a class but


outside methods; each object gets its own copy.​
3.​Static Variable – Defined with static, shared among
all objects of the class.​

2. Data Types
Data types define the type of values a variable can hold.
Java has two main categories of data types:

1. Primitive Data Types

(Store single values)

Data Type Size Example

byte 1 byte byte b = 10;

short 2 bytes short s = 1000;

int 4 bytes int x = 50000;

long 8 bytes long y = 100000L;

float 4 bytes float f = 5.5f;


double 8 bytes double d = 10.99;

char 2 bytes char c = 'A';

boolean 1 bit boolean flag =


true;

2. Non-Primitive Data Types

(Store objects and reference data)

Examples: String, Arrays, Classes, Interfaces

●​ String name = "Aaditya";

int[] numbers = {1, 2, 3, 4};

3. Operator
An operator is a symbol that performs operations on
variables and values.

Types of Operators in Java:


1.​ Arithmetic Operators (+, -, *, /, %) – Perform
mathematical operations.​

2.​Relational (Comparison) Operators (==, !=, >, <, >=, <=)


– Compare values.​

3.​Logical Operators (&&, ||, !) – Used in conditions.​

4.​Assignment Operators (=, +=, -=, *=, /=) – Assign


values to variables.​

5.​Bitwise Operators (&, |, ^, <<, >>) – Work on bits.​

6.​Increment/Decrement Operators (++, --) – Increase


or decrease values.​

7.​ Ternary Operator (condition ? trueValue : falseValue)


– A shorthand for if-else.

4. Keyword
A keyword is a reserved word in Java that has a
predefined meaning and cannot be used as a variable
name.

Examples of Keywords in Java:


Category Keywords

Data Types int, float, double, char,


boolean, void

Control Statements if, else, switch, for, while,


do, break, continue

Class and Object Keywords class, interface, extends,


implements, new, this,
super

Exception Handling try, catch, finally, throw,


throws

Access Modifiers public, private, protected

Other Keywords static, final, return, import,


package, instanceof

Conclusion
Term Definition

Variable A named memory location


to store values.

Data Type Defines the type of values


a variable can hold.

Operator Symbols that perform


operations on variables.

Keyword Reserved words in Java


that have predefined
meanings.
4. write notes on comments in java

Comments in Java are used to add explanations or notes


in the code. They are ignored by the compiler and do not
affect program execution. Comments help improve code
readability and make it easier to understand.

Types of Comments in Java

Java supports three types of comments:

1.​ Single-line Comments (//)​

2.​Multi-line Comments (/* ... */)​

3.​Documentation Comments (/** ... */)​

1. Single-line Comments (//)

●​ Used to write short comments on a single line.​

●​ Starts with //, and everything after it on the same


line is ignored by the compiler.​

Example:
public class SingleLineComment {

public static void main(String[] args) {

int a = 10; // This is a single-line comment

System.out.println("Value of a: " + a); // Printing value of a

2. Multi-line Comments (/* ... */)

●​ Used for longer explanations, covering multiple lines.​

●​ Starts with /* and ends with */.​

Example:

public class MultiLineComment {

public static void main(String[] args) {

/* This is a multi-line comment

It explains the following code

which calculates the sum of two numbers */

int a = 10, b = 20;

int sum = a + b;

System.out.println("Sum: " + sum);

3. Documentation Comments (/** ... */)


●​ Used to generate documentation using the Javadoc
tool.​

●​ Begins with /** and ends with */.​

●​ Can include special tags like @author, @version,


@param, and @return.​

Example:

/**

* This class demonstrates documentation comments.

* @author Aaditya

* @version 1.0

*/

public class DocumentationComment {

/**

* This method adds two numbers.

* @param a First number

* @param b Second number

* @return Sum of a and b

*/

public int add(int a, int b) {

return a + b;

}
public static void main(String[] args) {

DocumentationComment obj = new DocumentationComment();

System.out.println("Sum: " + obj.add(10, 20));

}.

Comparison of Java Comment Types

Comment Type Syntax Usage

Single-line // This is a Short, one-line


comment explanations

Multi-line /* This is a Longer


multi-line explanations
comment */ spanning multiple
lines

Documentation /** This is a Generates API


documentation documentation
comment */ using javadoc
Conclusion

●​ Comments improve code readability and help


programmers understand the code.​

●​ Single-line comments (//) are used for short


explanations.​

●​ Multi-line comments (/* ... */) are used for larger


blocks of comments.​

●​ Documentation comments (/** ... */) are used to


generate Java documentation.​

5. Explain if, if else if-else-if with example

Conditional Statements in Java

Conditional statements are used to make decisions in


Java programs based on certain conditions.

1. if Statement
●​ It checks a condition.​

●​ If the condition is true, the code inside the if block


runs.​

●​ If it’s false, nothing happens.​

Syntax:

if (condition) {

// Code to execute if condition is true

Example:

int age = 18;

if (age >= 18) {

System.out.println("You are eligible to vote.");

2. if-else Statement
●​ If the condition is true, the if block executes.​

●​ If false, the else block executes.​

Syntax:

if (condition) {

// Executes if condition is true

} else {

// Executes if condition is false

Example:

int number = 10;

if (number % 2 == 0) {

System.out.println("Even number");

} else {

System.out.println("Odd number");

3. if-else-if Ladder
●​ Used when you have multiple conditions to check.​

●​ The program checks each condition from top to


bottom and executes the block for the first true
condition.​

Syntax:
if (condition1) {

// Executes if condition1 is true

} else if (condition2) {

// Executes if condition2 is true

} else if (condition3) {

// Executes if condition3 is true

} else {

// Executes if none of the conditions are true

Example:
int marks = 75;

if (marks >= 90) {

System.out.println("Grade A");

} else if (marks >= 75) {


System.out.println("Grade B");

} else if (marks >= 60) {

System.out.println("Grade C");

} else {

System.out.println("Fail");

Conclusion:
●​ Use if for a single condition.​

●​ Use if-else when you have two options (true or false).​

●​ Use if-else-if when there are multiple conditions or


choices.​

5. Write short notes on JDK, JVM, and JRE.

1. JDK (Java Development Kit)

●​ JDK is a complete software development kit used to


develop Java applications.​

●​ It includes the JVM (Java Virtual Machine), JRE


(Java Runtime Environment), compiler (javac), and
development tools like debuggers.​

●​ Required for writing, compiling, and running Java


programs.​

Example: If you are a developer, you need JDK to write


and compile Java code.
2. JVM (Java Virtual Machine)

●​ JVM is a part of JRE that executes Java bytecode


and makes Java platform-independent.​

●​ Converts compiled bytecode into machine code for


the specific OS.​

●​ It handles memory management, garbage collection,


and security.​

Example: When you run a Java program (.class file), the


JVM interprets and executes it.

3. JRE (Java Runtime Environment)

●​ JRE provides the necessary environment to run Java


applications.​

●​ Includes the JVM and Java libraries, but does not


include the compiler.​

●​ Used by end-users to execute Java programs but not


develop them.​
Example: If you only want to run Java applications (not
develop them), JRE is enough.

●​ JDK = JRE + Compiler + Tools (For Developers)​

●​ JRE = JVM + Libraries (For Users)​

●​ JVM = Executes Bytecode (For Execution)​

6. Explain while, do-while, for, and for-each loops with


syntax and example.

1. while loop

●​ Check condition first, then executes the loop.​

●​ Use when you don’t know in advance how many


times to loop.​

Syntax:
while(condition) {

// code to execute

Example:
int i = 1;

while(i <= 5) {

System.out.println(i);

i++;

2. do-while loop
●​ Executes code once, then checks the condition.​

●​ Use when the loop should run at least once.​

Syntax:
do {

// code to execute

} while(condition);

Example:
int i = 1;

do {

System.out.println(i);

i++;

} while(i <= 5);

3. for loop
●​ Used when you know how many times to run the
loop.​

Syntax:
for(initialization; condition; update) {

// code to execute

Example:
for(int i = 1; i <= 5; i++) {

System.out.println(i);

4. for-each loop
●​ Used to iterate over arrays or collections.​

●​ Simplifies reading elements (cannot modify index).​

Syntax:
for(dataType variable : array) {

// code to execute

Example:
int[] numbers = {1, 2, 3, 4, 5};

for(int num : numbers) {

System.out.println(num);

|Assignment 2
1.​ Define the terms Class, Object, and Constructor in
Java.

1. Class

●​ A class is a blueprint or template for creating objects.​

●​ It defines variables and methods that describe the


behavior and state of objects.​

Syntax:
class Car {

int speed;

void drive() {

System.out.println("Car is driving");

2. Object

●​ An object is an instance of a class.​

●​ It is created using the new keyword.​


●​ It has its own values for the variables defined in the
class.​

Syntax:
Car myCar = new Car(); // myCar is an object of class Car

myCar.speed = 60;

myCar.drive();

3. Constructor

●​ A constructor is a special method that is


automatically called when an object is created.​

●​ It has the same name as the class and no return


type.​

●​ Used to initialize object values.​

Syntax:
class Car {

int speed;

// Constructor

Car() {
speed = 50;

System.out.println("Constructor called!");

Creating an object with constructor:


Car myCar = new Car(); // Automatically calls the constructor

2.​Write an example how to create class in Java (main


method within the Class)

Java Program Example:

public class Car {

// Data members (variables)

String brand = "Toyota";

int speed = 120;

// Method

void displayInfo() {

System.out.println("Brand: " + brand);

System.out.println("Speed: " + speed + " km/h");

}
// Main method

public static void main(String[] args) {

// Creating an object of the Car class

Car myCar = new Car();

// Calling the method using the object

myCar.displayInfo();

Explanation:

●​ public class Car – A class named Car is created.​

●​ Variables brand and speed hold information.​

●​ displayInfo() is a method to print the car’s details.​

●​ The main() method is the starting point of the


program.​

●​ Inside main(), we create an object of the class and


call the method.​

3.​Write an example in Java to create a class and write


its main method in another Class.
Showing how to create a class in one file and write its
main method in another class:

1. Class File –
Student.java

// Student.java

public class Student {

String name;

int age;

// Constructor

public Student(String name, int age) {

this.name = name;

this.age = age;

// Method to display student details

public void displayInfo() {

System.out.println("Name: " + name);

System.out.println("Age: " + age);

2. Main Method File –


MainClass.java

// MainClass.java

public class MainClass {

public static void main(String[] args) {

// Creating an object of Student class

Student s1 = new Student("Aaditya", 21);

// Calling method to display info

s1.displayInfo();

How to Run:

1.​ Save both files (Student.java and MainClass.java) in


the same directory.​

2.​Compile both:​

javac Student.java

javac MainClass.java​
3.Run the main class:​

java Mainclass

4.​How to initialize an object using, reference variable


and using method.

In Java, you can initialize an object in different ways.


Here’s a simple explanation and example showing:

1.​ Using a reference variable (direct initialization)​

2.​Using a method (initialization through a method call)​

1.

Using a Reference Variable


You create an object and initialize its attributes directly
using the reference variable.
public class Student {

String name;

int age;

public void display() {

System.out.println("Name: " + name);

System.out.println("Age: " + age);

class MainClass {

public static void main(String[] args) {

Student s1 = new Student(); // Object created using reference variable

// Initializing fields directly

s1.name = "Aaditya";

s1.age = 21;

s1.display();

}
2.

Using a Method
You create a method to initialize the object’s attributes.
public class Student {

String name;

int age;

// Method to initialize object

public void setDetails(String n, int a) {

name = n;

age = a;

public void display() {

System.out.println("Name: " + name);

System.out.println("Age: " + age);

class MainClass {

public static void main(String[] args) {

Student s2 = new Student(); // Object created

// Initializing using method

s2.setDetails("Teju", 18);

s2.display();
}

5.​What is constructor ? and what are the different


types of constructor

A constructor in Java is a special method that is


automatically called when an object is created.

Its main purpose is to initialize the object (i.e., assign


values to the fields of a class).

Key Features of a Constructor:

●​ Constructor name must be the same as the class


name.​

●​ It does not have a return type, not even void.​

●​ It is automatically invoked when an object is created


using the new keyword.​

Types of Constructors in Java

There are three types:


1. Default Constructor

●​ A constructor with no parameters.​

●​ If you don’t write any constructor, Java provides a


default one automatically.​

Example:
class Student {

String name;

int age;

// Default constructor

Student() {

name = "Unknown";

age = 0;

void display() {

System.out.println("Name: " + name + ", Age: " + age);

class MainClass {
public static void main(String[] args) {

Student s = new Student(); // Calls default constructor

s.display();

2. Parameterized Constructor

●​ A constructor that accepts arguments to initialize


fields.​

Example:
class Student {

String name;

int age;

// Parameterized constructor

Student(String n, int a) {

name = n;

age = a;

void display() {

System.out.println("Name: " + name + ", Age: " + age);


}

class MainClass {

public static void main(String[] args) {

Student s = new Student("Aaditya", 21); // Calls parameterized constructor

s.display();

3. Copy Constructor (Not built-in like C++, but can be


created manually)

●​ Used to copy values from one object to another.​

Example:
class Student {

String name;

int age;

// Parameterized constructor

Student(String n, int a) {

name = n;

age = a;
}

// Copy constructor

Student(Student s) {

name = s.name;

age = s.age;

void display() {

System.out.println("Name: " + name + ", Age: " + age);

class MainClass {

public static void main(String[] args) {

Student s1 = new Student("Teju", 18);

Student s2 = new Student(s1); // Copy constructor

s2.display();

}
|Assignment 3

1.​ What is inheritance ? What are the different types of


inheritance ?

What is Inheritance in Java?

Inheritance is a feature in object-oriented programming


where one class (child/subclass) inherits the properties
and behaviors (fields and methods) of another class
(parent/superclass).

It promotes code reusability and establishes a


relationship between classes (is-a relationship).

Syntax:
class Parent {

// parent class members

class Child extends Parent {

// child class members

Benefits of Inheritance:

●​ Code reuse: Avoids duplication.​

●​ Method overriding: Allows changing parent class


behavior in the child class.​

●​ Polymorphism support.​

Types of Inheritance in Java:


Java supports 4 types of inheritance, and one type
(Multiple Inheritance with classes) is not directly
supported to avoid ambiguity.

1. Single Inheritance

●​ One child class inherits from one parent class.​

class Animal {

void eat() {

System.out.println("This animal eats food.");

class Dog extends Animal {

void bark() {

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

2. Multilevel Inheritance
●​ A class inherits from a class which is itself inherited
from another class.​

class Animal {

void eat() {

System.out.println("Animal eats.");

class Dog extends Animal {

void bark() {

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

class Puppy extends Dog {

void weep() {

System.out.println("Puppy weeps.");

3. Hierarchical Inheritance
●​ Multiple child classes inherit from a single parent
class.​

class Animal {

void eat() {

System.out.println("Animal eats.");

class Dog extends Animal {

void bark() {

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

class Cat extends Animal {

void meow() {

System.out.println("Cat meows.");

4. Hybrid Inheritance (Achieved using Interfaces)


●​ A combination of two or more types of inheritance.​

●​ Java does not support hybrid or multiple inheritance


with classes, but interfaces can be used.​

interface A {

void methodA();

interface B {

void methodB();

class C implements A, B {

public void methodA() {

System.out.println("Method A");

public void methodB() {

System.out.println("Method B");

Note:
Java does not support multiple inheritance with classes to
avoid ambiguity (like the Diamond Problem).

can be achieved multiple inheritance using interfaces.


2.​Explain single inheritance with example.

What is Single Inheritance?

In single inheritance, one child class inherits from one


parent class.

This means the child class gets access to the fields and
methods of the parent class.

Example:

// Parent Class

class Animal {

void eat() {

System.out.println("This animal eats food.");

// Child Class

class Dog extends Animal {

void bark() {

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

}
// Main Class

public class MainClass {

public static void main(String[] args) {

Dog d = new Dog();

d.eat(); // calling method from parent class

d.bark(); // calling method from child class

Output:

This animal eats food.

Dog barks.

Explanation:

●​ Dog class inherits from Animal using extends.​

●​ Dog can access both:​

○​ its own method: bark()​

○​ and inherited method: eat() from Animal​


3.​Explain multi-level and hierarchical inheritance with
example.
1. Multi-Level Inheritance

In multi-level inheritance, a class inherits from a class


which is itself inherited from another class.

This forms a chain of inheritance.

Example:

// Grandparent Class

class Animal {

void eat() {

System.out.println("Animal eats.");

// Parent Class

class Dog extends Animal {

void bark() {

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

// Child Class

class Puppy extends Dog {


void weep() {

System.out.println("Puppy weeps.");

// Main Class

public class MainClass {

public static void main(String[] args) {

Puppy p = new Puppy();

p.eat(); // From Animal class

p.bark(); // From Dog class

p.weep(); // From Puppy class

Output:

Animal eats.

Dog barks.

Puppy weeps.

Explanation:
●​ Puppy inherits from Dog, and Dog inherits from
Animal.​

●​ So, Puppy has access to all methods from both Dog


and Animal.​

2. Hierarchical Inheritance

In hierarchical inheritance, multiple child classes inherit


from a single parent class.

Example:

// Parent Class

class Animal {

void eat() {

System.out.println("Animal eats.");

// First Child Class

class Dog extends Animal {

void bark() {

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

// Second Child Class

class Cat extends Animal {

void meow() {

System.out.println("Cat meows.");

// Main Class

public class MainClass {

public static void main(String[] args) {

Dog d = new Dog();

Cat c = new Cat();

d.eat(); // From Animal

d.bark(); // From Dog

c.eat(); // From Animal

c.meow(); // From Cat

}
Output:

Animal eats.

Dog barks.

Animal eats.

Cat meows.

Explanation:

●​ Both Dog and Cat inherit from Animal.​

●​ Each child class has its own methods, and also


inherits the eat() method from Animal.​

4. Why does Multiple Inheritance not work in Java (with


classes)?

Java does not support multiple inheritance with classes to


avoid ambiguity and confusion, especially when two
parent classes have the same method name.
What is Multiple Inheritance?

It means a child class inherits from more than one parent


class.
// This is not allowed in Java

class A {

void show() {

System.out.println("Class A");

class B {

void show() {

System.out.println("Class B");

class C extends A, B { // Not allowed in Java

// Ambiguity: which show() to use?

Why it doesn’t work?

●​ Ambiguity arises if both parent classes have methods


with the same signature.​
●​ The compiler won’t know which method to call,
leading to the “Diamond Problem”.​

Diamond Problem Example:

Imagine:
A

/\

B C

\/

●​ Class B and C both inherit from A.​

●​ Class D inherits from both B and C.​

●​ Now if A has a method show(), and D tries to call it,


which path should it follow—through B or C?​

Java’s Solution: Use Interfaces

Java allows multiple inheritance through interfaces


because:
●​ Interfaces only declare methods, they don’t define
them (until Java 8).​

●​ This avoids ambiguity, and even if there’s conflict,


Java provides clear rules to resolve it.​

interface A {

void show();

interface B {

void show();

class C implements A, B {

public void show() {

System.out.println("Class C implementing A and B");

Summary:

●​ Java avoids multiple inheritance with classes to keep


it simple and avoid confusion.​
●​ It supports multiple inheritance with interfaces,
which is safer and more flexible.​

5. What is polymorphism? What are the different types of


polymorphism

Polymorphism is an important concept in Object-Oriented


Programming (OOP) that means “one name, many forms”.

In Java, polymorphism allows the same method or


function to behave differently based on the object or data
it is working with.

Types of Polymorphism in Java:

Java supports two main types of polymorphism:

Type Also Called When It


Happens

1. Compile-time Method At Compile Time


Polymorphism Overloading
2. Runtime Method At Runtime
Polymorphism Overriding
1. Compile-Time Polymorphism (Method
Overloading)

This occurs when multiple methods with the same name


exist in the same class, but have different parameters
(type, number, or order).

Example:

class Calculator {

int add(int a, int b) {

return a + b;

double add(double a, double b) {

return a + b;

int add(int a, int b, int c) {

return a + b + c;

●​ The add() method is overloaded with different


parameters.​
●​ The method to be called is chosen at compile time.​

2. Runtime Polymorphism (Method Overriding)

This occurs when a child class provides a specific


implementation of a method that is already defined in its
parent class.

The method call is determined at runtime, based on the


actual object being referred to.

Example:

class Animal {

void sound() {

System.out.println("Animal makes sound");

class Dog extends Animal {

void sound() {

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

class Cat extends Animal {


void sound() {

System.out.println("Cat meows");

class MainClass {

public static void main(String[] args) {

Animal a;

a = new Dog();

a.sound(); // Output: Dog barks

a = new Cat();

a.sound(); // Output: Cat meows

●​ Even though the reference is of type Animal, the


actual object’s method is called at runtime.​

6. Explain function overloading and function overriding in


polymorphism with example.
1. Function Overloading (Compile-Time
Polymorphism)

Definition:

Function overloading means having multiple methods


with the same name in the same class, but with different
parameter lists (type, number, or order of parameters).

Purpose:

To perform different tasks using the same method name,


based on the arguments passed.

Example of Function Overloading:

class Calculator {

// Method with 2 int parameters

int add(int a, int b) {

return a + b;

// Method with 2 double parameters

double add(double a, double b) {

return a + b;

// Method with 3 int parameters


int add(int a, int b, int c) {

return a + b + c;

public class MainClass {

public static void main(String[] args) {

Calculator c = new Calculator();

System.out.println(c.add(10, 20)); // int version

System.out.println(c.add(5.5, 4.5)); // double version

System.out.println(c.add(1, 2, 3)); // 3-arg version

Output:

30

10.0

2. Function Overriding (Runtime Polymorphism)

Definition:
Function overriding means a subclass provides its own
version of a method that is already defined in its
superclass.

Purpose:

To change or customize the behavior of a method for a


specific child class.

Example of Function Overriding:

class Animal {

void sound() {

System.out.println("Animal makes sound");

class Dog extends Animal {

@Override

void sound() {

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

class Cat extends Animal {

@Override

void sound() {
System.out.println("Cat meows");

public class MainClass {

public static void main(String[] args) {

Animal a;

a = new Dog();

a.sound(); // Calls Dog's version

a = new Cat();

a.sound(); // Calls Cat's version

Output:

Dog barks

Cat meows

Difference Between Overloading and Overriding:

Feature Function Function


Overloading Overriding
Based On Number/type/or Method in child
der of class with same
parameters signature

Occurs In Same class Between parent


and child class

Inheritance No Yes
Required

Polymorphism Compile-time Runtime


Type

Return Type Can be same or Must be same or


different covariant

|Assignment 4
1.​ what is exception handling in Java and what is
difference between check and uncheck exception.
Exception Handling in Java is a mechanism to handle
runtime errors so that the normal flow of the program can
be maintained. It helps to catch, handle, and resolve
errors gracefully without crashing the program.
Key Terms:

●​ Exception – An event that disrupts the normal flow of


the program.​

●​ Try – The block where you write the code that might
throw an exception.​

●​ Catch – The block that handles the exception.​

●​ Finally – Block that executes whether an exception


occurs or not.​

●​ Throw – Used to explicitly throw an exception.​

●​ Throws – Declares exceptions in method signature.

public class Example {

public static void main(String[] args) {

try {

int result = 10 / 0; // This will throw ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Error: Cannot divide by zero.");


} finally {

System.out.println("This will always execute.");

Difference Between Checked and Unchecked


Exceptions

Feature Checked Unchecked


Exception Exception

Definition Exceptions that Exceptions that


are checked at occur at runtime
compile-time

Compiler Must be either Not required to


Handling caught or be caught or
declared using declared
throws
Examples IOException, NullPointerExcept
SQLException, ion,
FileNotFoundExc ArithmeticExcepti
eption on,
ArrayIndexOutOf
BoundsException

Belongs to Subclasses of Subclasses of


Exception (except RuntimeExceptio
RuntimeExceptio n
n)

When to Use When the When the error is


program should due to
recover from programming
error mistakes

Checked Exception Example:


import java.io.*;

public class CheckedExample {

public static void main(String[] args) throws IOException {

FileReader file = new FileReader("file.txt"); // May throw FileNotFoundException

BufferedReader fileInput = new BufferedReader(file);

System.out.println(fileInput.readLine());

fileInput.close();

Unchecked Exception Example:

import java.io.*;

public class CheckedExample {

public static void main(String[] args) throws IOException {

FileReader file = new FileReader("file.txt"); // May throw FileNotFoundException

BufferedReader fileInput = new BufferedReader(file);

System.out.println(fileInput.readLine());

fileInput.close();

}
2.​write note on Java exceptions key word.

Java Exception Keywords

Java provides several keywords that are used in


exception handling. These keywords help in detecting,
handling, and recovering from errors during program
execution.

1. try

●​ The try block contains code that might throw an


exception.​

●​ It must be followed by either catch or finally.​

try {

int result = 10 / 0;

}
2. catch

●​ The catch block handles the exception thrown in the


try block.​

●​ You can have multiple catch blocks for different


exception types.​

catch (ArithmeticException e) {

System.out.println("Cannot divide by zero");

3.finally

●​ The finally block contains code that will always


execute, whether an exception occurs or not.​

●​ It is usually used for cleanup tasks, like closing files


or releasing resources.​

finally {

System.out.println("This block always executes");

4. throw
●​ The throw keyword is used to manually throw an
exception.​

finally {

System.out.println("This block always executes");

5. throws

●​ The throws keyword is used in method declarations


to declare exceptions that the method might throw.​

public void readFile() throws IOException {

// code that might throw IOException

Keyword Purpose

try To wrap code that may


cause exception

catch To handle the exception


finally Executes regardless of
exception

throw Manually throw an


exception

throws Declare exceptions in


method signature

3.​Explain with example try catch block.


A try-catch block is used to handle exceptions in Java.

●​ The code that might cause an exception is placed


inside the try block.​

●​ If an exception occurs, the program control is


transferred to the catch block, which handles the
exception.​

Syntex:
try {

// code that may throw an exception

} catch (ExceptionType e) {

// code to handle the exception

}
Example:
public class TryCatchExample {

public static void main(String[] args) {

try {

int num = 10;

int result = num / 0; // This will throw ArithmeticException

System.out.println("Result: " + result); // This line will not be executed

} catch (ArithmeticException e) {

System.out.println("Error: Cannot divide by zero!");

System.out.println("Program continues after exception handling.");

Output:
Error: Cannot divide by zero!

Program continues after exception handling.


Explanation:

●​ 10 / 0 causes an ArithmeticException.​

●​ The exception is caught by the catch block.​

●​ The message “Error: Cannot divide by zero!” is


printed.​

●​ The program doesn’t crash and continues normally.​

4.​explain Java multi catch block with example.

A multi-catch block is used when you want to handle


multiple exceptions using a single catch block.

This was introduced in Java 7 to simplify code and avoid


repetitive catch blocks when the handling logic is the
same for multiple exceptions.
Syntax:
try {

// risky code

} catch (ExceptionType1 | ExceptionType2 e) {

// common exception handling code

Note: All exception types in a multi-catch block must be unrelated (not in a parent-child
relationship).

Example:
public class MultiCatchExample {

public static void main(String[] args) {

try {

String str = null;

System.out.println(str.length()); // May throw NullPointerException

int[] arr = new int[5];

System.out.println(arr[10]); // May throw ArrayIndexOutOfBoundsException

} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {

System.out.println("Caught an exception: " + e);

System.out.println("Program continues after multi-catch block.");

Output:
Caught an exception: java.lang.NullPointerException

Program continues after multi-catch block.

Why Use Multi-Catch?


●​ Simplifies code if the same handling is needed.​

●​ Avoids duplicate catch blocks.​

●​ Improves readability and performance.​

5.​explain note on Java nested try block.

Why Use Multi-Catch?


●​ Simplifies code if the same handling is needed.​

●​ Avoids dupHere’s a clear and concise note on Java


Nested try Block for your assignment:

Java Nested try Block

In Java, a nested try block means placing one try block


inside another try block. It is useful when certain parts of
code inside a try block may also throw exceptions and
need separate handling.

Why Use Nested try?

●​ To handle multiple levels of errors.​

●​ To provide fine-grained control over different


exception-prone code blocks.​

Syntax:

try {

// Outer try block

try {
// Inner try block

} catch (ExceptionType1 e) {

// Handle inner exception

} catch (ExceptionType2 e) {

// Handle outer exception

Example:

public class NestedTryExample {

public static void main(String[] args) {

try {

int[] numbers = {1, 2, 3};

try {

System.out.println(numbers[5]); // Throws ArrayIndexOutOfBoundsException

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Inner Catch: Array index out of bounds.");

int result = 10 / 0; // Throws ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Outer Catch: Cannot divide by zero.");

}
}

Output:

Inner Catch: Array index out of bounds.

Outer Catch: Cannot divide by zero.

Conclusion:

●​ Nested try blocks help to isolate different risky code


sections.​

●​ Each try block can have its own specific catch block,
improving error handling clarity.​

6.​what is finery block why it is necessary.

Why Use Multi-Catch?


●​ Simplifies code if the same handling is needed.​

●​ Avoids dupHere’s a clear and concise note on Java


Nested try Block for your assignment:

Java Nested try Block

In Java, a nested try block means placing one try block


inside another try block. It is useful when certain parts of
code inside a try block may also throw exceptions and
need separate handling.

Why Use Nested try?

What is the finally block in Java? Why is it necessary?

The finally block in Java is a block that is always executed


after the try and catch blocks—regardless of whether an
exception is thrown or not.

Purpose of finally block:

●​ To perform cleanup operations such as:​

○​ Closing files​
○​ Releasing resources (e.g., database connections)​

○​ Ending a process cleanly​

Syntax:

try {

// code that may throw exception

} catch (Exception e) {

// handle exception

} finally {

// code that always executes

Example:

public class FinallyExample {

public static void main(String[] args) {

try {

int result = 10 / 2;

System.out.println("Result: " + result);

} catch (ArithmeticException e) {

System.out.println("Exception caught!");

} finally {
System.out.println("This block always executes.");

Output:

Result: 5

This block always executes.

Even if an exception occurs or doesn’t, the finally block


will run.

Why is finally block necessary?

●​ It ensures that important cleanup code is always


executed, even if:​

○​ An exception is thrown​

○​ A return statement is used in the try or catch​

○​ The program ends abruptly​


Conclusion:

The finally block is essential for resource management


and to avoid resource leakage, making your code more
reliable and secure.

7.​Explain with examples throw exceptions in Java

What is throw in Java?

The throw keyword in Java is used to manually throw an


exception from your code.

It helps in customizing exception handling and is typically


used to throw built-in or user-defined exceptions.

Syntax:
throw new ExceptionType("Error message");

Note: When you use throw, the program stops at that


line unless the exception is handled using try-catch.

Example 1: Throwing a built-in exception


public class ThrowExample {

public static void main(String[] args) {

int age = 15;

if (age < 18) {

throw new ArithmeticException("You are not eligible to vote");

} else {

System.out.println("You can vote");

Output:

Exception in thread "main" java.lang.ArithmeticException: You are not eligible to vote

Example 2: Throwing inside try-catch


public class ThrowInTryCatch {

public static void main(String[] args) {

try {

validateAge(16);

} catch (ArithmeticException e) {

System.out.println("Caught Exception: " + e.getMessage());

static void validateAge(int age) {

if (age < 18) {

throw new ArithmeticException("Age must be 18 or above");

System.out.println("Valid age for voting.");

Output:

Caught Exception: Age must be 18 or above

Key Points:
●​ throw is used to explicitly generate an exception.​

●​ Only one exception can be thrown at a time using


throw.​

●​ After throw, no code is executed in that block unless


caught.​

●​ You can throw both built-in and custom exceptions.​

You might also like