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

All Importanant Java Questions

The document covers various fundamental concepts of Java programming, including primitive data types, array syntax, tokens, loops, and the differences between String and StringBuffer. It also explains object creation, method and constructor overloading, garbage collection, and visibility controls. Additionally, it includes sample code snippets and examples to illustrate these concepts.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views97 pages

All Importanant Java Questions

The document covers various fundamental concepts of Java programming, including primitive data types, array syntax, tokens, loops, and the differences between String and StringBuffer. It also explains object creation, method and constructor overloading, garbage collection, and visibility controls. Additionally, it includes sample code snippets and examples to illustrate these concepts.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 1: Basic syntactical constructs in java

Q1. Write all primitive data types available in java with their storage size in bytes

Ans.

s
sse
Cla
tik

Q2. Write down the syntax of array declaration and initialization in Java.

Ans:
as

An array in Java is a container object that holds a fixed number of values of a single type.

Syntax:
Sw

// Declaration

int[] arr;

// Initialization

arr = new int[5]; // Creates an array of size 5

// Declaration and Initialization together

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

●​ Arrays are indexed from 0.

●​ int[] arr means it holds integers.

Contact
7972423160
●​ The size of the array is fixed after initialization.

Q3. Define the term token and enlist types of tokens in Java.

Answer:

In Java, a token is the smallest individual unit in a program that has meaning to the compiler.

Types of Tokens:

1.​ Keywords – Reserved words (e.g., class, public, void)

2.​ Identifiers – Names for variables, methods, classes (e.g., sum, main)

3.​ Literals – Constant values (e.g., 100, 3.14, 'A', true)

s
4.​ Operators – Symbols that perform operations (e.g., +, -, *, /)

sse
5.​ Separators – Used to separate code (e.g., (), {}, [], ;, ,)

These tokens are combined to form statements and expressions in Java programs.
Cla
Q4. Write syntax and example of for-each loop in Java.

Answer:

The for-each loop is used to iterate over arrays and collections without using indexes.

Syntax:
tik

for (dataType var : array)

// code block
as

Example:
Sw

int[] numbers = {10, 20, 30};

for (int num : numbers)

[Link](num);

●​ num takes each value of the numbers array one by one.

●​ Easier and safer than using traditional for loop when you don't need an index.

Contact
7972423160
Q5. Explain the difference between String and StringBuffer in Java.

Answer:

Both String and StringBuffer are classes used to handle text data, but they differ in mutability and
performance.

Feature String StringBuffer

Mutability Immutable (cannot be changed) Mutable (can be modified)

Performance Slower for many modifications Faster for repeated modifications

s
Thread Safety Not thread-safe Thread-safe

sse
Q6. Describe instanceof and dot (.) operators in Java with suitable examples.

Answer:

instanceof Operator:
Cla
Used to test whether an object is an instance of a specific class or subclass.

String str = "Hello";

[Link](str instanceof String); // true


tik

Dot (.) Operator:

Used to access members (fields and methods) of a class or object.

String s = "Java";
as

int length = [Link](); // Using . operator to call method

●​ It is also used to access classes from packages: [Link].


Sw

Q7. Enlist any two bitwise and logical operators in Java.

Answer:

Bitwise Operators:

Operate on bits of integer values.

1.​ & – Bitwise AND

2.​ | – Bitwise OR

Logical Operators:

Contact
7972423160
Operate on boolean values (true/false).

1.​ && – Logical AND

2.​ || – Logical OR

Q8. What is an Object? How to create it? Explain with Example.

Answer:

An object is an instance of a class. It is created based on a class blueprint and holds both data (fields)
and behaviors (methods).

Creating an Object:

s
ClassName obj = new ClassName();

sse
Example:

class Car

{
Cla
void drive()

[Link]("Driving...");
tik

public class Main


as

public static void main(String[] args)


Sw

Car myCar = new Car();

[Link]();

●​ myCar is the object of the class Car.

●​ Object creation allocates memory and allows access to the class's functionality.

Q9. Explain any four features of Java.

Contact
7972423160
Java is a powerful, secure, and easy-to-learn programming language. Below are four key features:

1. Object-Oriented Programming (OOP)

●​ Java is based on OOP concepts such as class, object, inheritance, and polymorphism.

●​ Makes the code more modular and reusable.

2. Platform-Independent

●​ Java programs are compiled into bytecode that runs on any system with a Java Virtual
Machine (JVM).

●​ This makes Java "write once, run anywhere."

3. Simple and Easy to Learn

s
●​ Java has a clean and readable syntax similar to C++, but without complex features like
pointers or operator overloading.

sse
●​ Built-in memory management makes development easier.

4. Robust and Secure

●​ Java prevents errors using exception handling and strong type checking.
Cla
●​ Memory leaks and pointer errors are avoided, making applications more secure and reliable.
tik

Q10. Write a program to accept marks and find grade using if statement.

Code:
as

import [Link];

public class GradeCalculator


Sw

public static void main(String[] args)

Scanner sc = new Scanner([Link]);

[Link]("Enter your marks (0 to 100): ");

int marks = [Link]();

if (marks >= 90)

[Link]("Grade: A");

Contact
7972423160
}

else if (marks >= 80)

[Link]("Grade: B");

else if (marks >= 70)

[Link]("Grade: C");

s
else if (marks >= 60)

sse
{

[Link]("Grade: D");

else
Cla
{

[Link]("Grade: F (Fail)");

}
tik

[Link]();

}
as

Sample Output:
Sw

Enter your marks (0 to 100): 85

Grade: B

Q11. Describe the concept of type casting and explain its types with proper syntax and example.

Ans.

Type casting is converting one data type into another. Java supports two types:

1. Implicit Type Casting (Widening)

●​ Done automatically when converting smaller types to larger types.

Syntax:

Contact
7972423160
int a = 10;

double b = a;

Example:

public class ImplicitCasting

public static void main(String[] args)

int x = 5;

double y = x;

s
[Link]("int value: " + x);

sse
[Link]("Converted to double: " + y);

Output:
Cla
int value: 5

Converted to double: 5.0


tik

2. Explicit Type Casting (Narrowing)

●​ Done manually by the programmer, usually from a larger to a smaller type.


as

Syntax:

double a = 10.5;
Sw

int b = (int) a;

Example:

public class ExplicitCasting

public static void main(String[] args)

double x = 9.8;

int y = (int) x;

[Link]("double value: " + x);

Contact
7972423160
[Link]("Converted to int: " + y);

Output:

double value: 9.8

Converted to int: 9

Q12. State & explain scope of variable with an example.

In Java, scope refers to where a variable can be accessed within the code.

s
Types of Scope:

sse
1.​ Local Scope – Variables inside a method or block.

2.​ Instance Scope – Non-static variables inside a class, available to object instances.

3.​ Class Scope – Static variables shared by all objects of the class.
Cla
Example:

public class ScopeExample

{
tik

int instanceVar = 10; // Instance scope

static int classVar = 20; // Class scope


as

public void method()

{
Sw

int localVar = 30; // Local scope

[Link]("Instance Var: " + instanceVar);

[Link]("Class Var: " + classVar);

[Link]("Local Var: " + localVar);

public static void main(String[] args)

ScopeExample obj = new ScopeExample();

[Link]();

Contact
7972423160
}

Output:

Instance Var: 10

Class Var: 20

Local Var: 30

[Link] a program to accept a character and check whether it is a vowel or consonant using
switch-case statement.

s
import [Link];

sse
public class VowelOrConsonant

public static void main(String[] args)

{
Cla
Scanner sc = new Scanner([Link]);

[Link]("Enter a character: ");

char ch = [Link]().toLowerCase();
tik

switch (ch)

{
as

case 'a':

case 'e':
Sw

case 'i':

case 'o':

case 'u':

[Link]("It is a Vowel.");

break;

default:

[Link]("It is a Consonant.");

[Link]();

Contact
7972423160
}

✅ Sample Output:
Enter a character: e

It is a Vowel.

Q14. Write a program to copy all elements of one array into another array.
import [Link].*;
import [Link].*;

s
public class ArrayCopy

sse
{

public static void main(String[] args)

int[] originalArray = {10, 20, 30, 40, 50};


Cla
int[] copiedArray = new int[[Link]];

for (int i = 0; i < [Link]; i++)

{
tik

copiedArray[i] = originalArray[i];

[Link]("Copied Array: ");


as

for (int value : copiedArray)

{
Sw

[Link](value + " ");

✅ Output:
Copied Array: 10 20 30 40 50

Q15. What is Method Overloading and Constructor Overloading? Give Examples.

Contact
7972423160
Ans.

1. Method Overloading

Definition:

Method overloading means defining multiple methods in the same class with the same method
name but different parameters (number, type, or order).

Purpose:

●​ To perform similar tasks in different ways.

●​ Improves code readability and reusability.

●​ It is an example of compile-time polymorphism (method binding happens at compile time).

s
Rules for Method Overloading:

sse
●​ Methods must have different parameter lists.

●​ Overloading does not depend on return type only.

Example:

public class MethodOverloadingExample


Cla
{

void display()

[Link]("Display with no arguments");


tik

void display(int a)
as

[Link]("Display with int: " + a);


Sw

void display(String s)

[Link]("Display with String: " + s);

public static void main(String[] args)

MethodOverloadingExample obj = new MethodOverloadingExample();

[Link]();

Contact
7972423160
[Link](10);

[Link]("Java");

🖥️ Output:
Display with no arguments

Display with int: 10

Display with String: Java

s
2. Constructor Overloading

sse
Definition:

Constructor overloading means having multiple constructors in a class, each with a different
parameter list.

Purpose:
Cla
●​ To create objects in multiple ways depending on what information is available.

●​ Enhances flexibility while creating instances of a class.

Rules for Constructor Overloading:

●​ Must be in the same class.


tik

●​ Parameter list must be different.

●​ Return type is not allowed for constructors.


as

Example:

public class Student


Sw

String name;

int age;

public Student()

name = "Unknown";

age = 0;

public Student(String n, int a)

Contact
7972423160
{

name = n;

age = a;

public void display()

[Link]("Name: " + name + ", Age: " + age);

public static void main(String[] args)

s
{

sse
Student s1 = new Student();

Student s2 = new Student("Alice", 20);

[Link]();

[Link]();
Cla
}

}
tik

🖥️ Output:
Name: Unknown, Age: 0
as

Name: Alice, Age: 20


Sw

Q16. Difference between

Contact
7972423160
s
sse
Cla
Q17. Explain the significance of garbage collection in Java. How does it contribute to memory
management?
tik

Garbage Collection in Java

Definition:

●​ Garbage Collection in Java is a process through which unused objects are automatically
as

deleted to free up memory for new objects.

●​ Java has a built-in Garbage Collector (GC), which runs in the background and manages
memory allocation and deallocation.
Sw

How Garbage Collection Works:

1.​ Memory Allocation:

o​ When an object is created, memory is allocated from the heap.

2.​ Object Usage:

o​ Objects that are no longer referenced by any part of the program are considered
garbage.

3.​ Garbage Collection Process:

o​ The Garbage Collector detects which objects are no longer reachable.

o​ It frees the memory used by these objects to prevent memory leaks.

Contact
7972423160
Significance of Garbage Collection:

1.​ Automatic Memory Management:

o​ Java's GC automates the memory management process, reducing the need for the
programmer to manually allocate and free memory.

2.​ Prevention of Memory Leaks:

o​ By automatically reclaiming memory from unused objects, garbage collection helps


avoid memory leaks (where memory is allocated but not freed).

3.​ Improved Program Efficiency:

o​ GC helps keep the memory usage optimal, thus improving overall application
performance.

s
4.​ Simplicity:

sse
o​ Java developers do not need to manually manage memory, reducing the complexity
of code and making it easier to write and maintain.

GC Trigger:

●​ Java’s GC is triggered automatically by the JVM when it detects that the heap memory is
Cla
running low.

●​ Developers can also request a garbage collection using [Link](), but this is not
guaranteed to initiate GC immediately.
tik

Q18. Write a program to print all the Armstrong numbers from 0 to 999.

import [Link].*;

import [Link].*;
as

public class ArmstrongNumbers

{
Sw

public static void main(String[] args)

[Link]("Armstrong numbers between 0 and 999:");

for (int num = 0; num <= 999; num++)

int sum = 0;

int temp = num;

int digits = [Link](num).length();

while (temp != 0)

Contact
7972423160
{

int remainder = temp % 10;

sum=sum+remainder*remainder*remainder;

temp =temp/10;

if (sum == num)

[Link](num);

s
}

sse
}

✅ Sample Output:
Cla
Armstrong numbers between 0 and 999:

1
tik

153

370

371
as

407
Sw

Q19. Explain visibility controls in Java.

Ans.

Types of Access Modifiers:

1.​ public

o​ Visibility: Can be accessed from anywhere (within the same package, from other
packages).

o​ Usage: Classes, methods, and variables can be declared public to allow access
globally.

Contact
7972423160
s
2.​ private

sse
o​ Visibility: The member is accessible only within the same class.

o​ Usage: Often used for encapsulation to restrict access to class variables and
methods. Cla
tik
as
Sw

3.​ protected

o​ Visibility: The member is accessible within the same package and by subclasses (even
if they are in different packages).

o​ Usage: Typically used in inheritance to allow subclasses to access inherited


fields/methods.

Contact
7972423160
s
sse
4.​ Default (Package-Private)

o​ Visibility: If no access modifier is provided, it is package-private by default, meaning


the member is accessible only within the same package.
Cla
o​ Usage: Useful when you want to restrict access to the same package.
tik
as
Sw

Summary of Access Levels:

Same
Modifier Same Class Subclass Anywhere
Package

public Yes Yes Yes Yes

private Yes No No No

Contact
7972423160
Same
Modifier Same Class Subclass Anywhere
Package

protected Yes Yes Yes No

Default Yes Yes No No

Q20. Compare Array and Vector in Java.

s
sse
Cla
Q21. Checked whether entered string is palindrome or not.
tik

import [Link];

public class SimplePalindromeCheck


as

public static void main(String[] args)

{
Sw

Scanner sc = new Scanner([Link]);

[Link]("Enter a string: ");

String input = [Link]();

String cleanedString = [Link]();

boolean isPalindrome = true;

int length = [Link]();

for (int i = 0; i < length; i++)

Contact
7972423160
if ([Link](i) != [Link](length - i - 1))

isPalindrome = false;

break;

if (isPalindrome)

[Link](input + " is a palindrome.");

s
}

sse
else

[Link](input + " is not a palindrome.");

}
Cla
[Link]();

}
tik

Output

Enter a string: madam

madam is a palindrome.
as

[Link] the use of any methods of the Vector class with their syntax.
Sw

Vector Class in Java

The Vector class implements a growable array of objects. It is part of the [Link] package and
implements the List interface, making it similar to an array, but it can dynamically resize itself when
elements are added or removed.

Four important methods of the Vector class:

1.​ add(E e)

Purpose: Adds an element to the end of the vector.

Syntax:

[Link](E e);

Contact
7972423160
Example:

Vector<Integer> vector = new Vector<>();

[Link](10); // Adds 10 to the vector

2.​ size()

Purpose: Returns the number of elements in the vector.

Syntax:

int size = [Link]();

s
Example:

sse
int size = [Link](); // Returns the size of the vector

[Link]("Size of vector: " + size);


Cla
3.​ get(int index)

Purpose: Returns the element at the specified position in the vector.

Syntax:

E element = [Link](int index);


tik

Example:

int element = [Link](0); // Gets the first element of the vector

[Link]("First element: " + element);


as

4.​ remove(int index)


Sw

Purpose: Removes the element at the specified index.

Syntax:

[Link](int index);

Example:

[Link](0); // Removes the element at index 0

Contact
7972423160
Example code

import [Link];

public class SimpleVectorExample

public static void main(String[] args)

Vector<Integer> vector = new Vector<>();

[Link](10);

[Link](20);

s
[Link](30);

sse
[Link]("Element at index 0: " + [Link](0));

[Link]("Element at index 1: " + [Link](1));

[Link]("Size of the vector: " + [Link]());


Cla
[Link](1); // Removes the element at index 1

[Link]("Vector after removal: " + vector);

}
tik

Output

Element at index 0: 10

Element at index 1: 20
as

Size of the vector: 3

Vector after removal: [10, 30]


Sw

Q23. Explain the command line arguments with a suitable example.

Command Line Arguments in Java

Command line arguments are values passed to the program when it is executed from the command
line. These arguments are provided after the class name in the command.

●​ Syntax:

public class CommandLineExample

public static void main(String args[])

Contact
7972423160
{

for (int i = 0; i < [Link]; i++)

[Link]("Argument " + (i + 1) + ": " + args[i]);

●​ Explanation:

o​ args[] is an array of strings that stores the command line arguments.

s
o​ Each argument is accessed using the array index.

sse
●​ Example: Running the program with command line arguments:

java CommandLineExample Hello World 123

Output:

Argument 1: Hello
Cla
Argument 2: World

Argument 3: 123
tik

Q24.. What is a constructor? List types of constructors. Explain parameterized constructor with a
suitable example.

Constructors in Java
as

A constructor is a special type of method that is used to initialize objects. It has the same name as
the class and is called when an object of the class is created.

Types of Constructors:
Sw

1.​ Default Constructor: A constructor that takes no parameters and initializes the object with
default values.

o​ Syntax:

public ClassName()

// Initialization code

2.​ Parameterized Constructor: A constructor that takes parameters to initialize the object with
specific values at the time of creation.

Contact
7972423160
o​ Syntax:

public ClassName(type1 param1, type2 param2)

// Initialization code using parameters

Code for Default Constructor

import [Link];

class Student

s
{

sse
String name;

int age;

Student()

{
Cla
name = "Unknown";

age = 0;

}
tik

void display()

[Link]("Name: " + name + ", Age: " + age);


as

}
Sw

public static void main(String[] args)

Student student1 = new Student();

[Link]("Student 1 - ");

[Link]();

Output:

Student 1 - Name: Unknown, Age: 0

Contact
7972423160
Code for Parameterized Constructor

import [Link];

class Student

String name;

int age;

Student(String name, int age)

s
[Link] = name;

sse
[Link] = age;

void display()

{
Cla
[Link]("Name: " + name + ", Age: " + age);

}
tik

public static void main(String[] args)

Student student2 = new Student("Alice", 22);


as

[Link]("Student 2 - ");

[Link]();
Sw

Output:

Student 2 - Name: Alice, Age: 22

Q25.. Explain Vector with the help of an example. Explain any 4 methods of the Vector class.

Vector Class in Java

A Vector is part of the [Link] package and implements the List interface. It is similar to an array but
with dynamic resizing.

●​ Example of Vector:

Contact
7972423160
import [Link].*;

public class VectorExample

public static void main(String[] args)

Vector<String> vector = new Vector<>();

[Link]("Apple");

[Link]("Banana");

[Link]("Cherry");

s
[Link]("Vector elements: " + vector);

sse
[Link]("Element at index 1: " + [Link](1));

[Link]("Size of vector: " + [Link]());

[Link](1); // Removes "Banana"


Cla
[Link]("After removal: " + vector);

}
tik

4 Important Methods of Vector Class:

1.​ add(E e)

o​ Adds an element to the vector.


as

o​ Syntax: [Link](element);

2.​ size()
Sw

o​ Returns the number of elements in the vector.

o​ Syntax: int size = [Link]();

3.​ get(int index)

o​ Retrieves the element at the specified index.

o​ Syntax: E element = [Link](index);

4.​ remove(int index)

o​ Removes the element at the specified index.

o​ Syntax: [Link](index);

Contact
7972423160
[Link] String class in java with example. Explain any 6 methods.

Ans.

The String class in Java represents a sequence of characters. It is a part of the [Link] package and
is immutable, meaning once a String object is created, its value cannot be changed.

Java provides various methods to manipulate and work with strings. Since strings are widely used in
Java, understanding the String class and its methods is essential.

Key Points about String in Java:

●​ Immutable: Once a String object is created, its value cannot be changed. Any operation that
appears to modify a string will actually create a new string object.

●​ String Pool: Java maintains a pool of strings for memory optimization. If two String variables

s
have the same value, they will refer to the same object in memory rather than creating new
objects.

sse
Methods of the String Class:

1. length() Method

The length() method returns the length of the string, i.e., the number of characters present in the
string.
Cla
Syntax:

int length()
tik

Example:

public class StringExample

{
as

public static void main(String[] args)

{
Sw

String str = "Hello, World!";

[Link]("Length of the string: " + [Link]());

Output:

Length of the string: 13

2. charAt() Method

The charAt() method returns the character at a specified index in the string.

Contact
7972423160
Syntax:

char charAt(int index)

Example:

public class StringExample

public static void main(String[] args)

String str = "Hello, World!";

s
[Link]("Character at index 7: " + [Link](7));

sse
}

Output:

Character at index 7: W
Cla
3. substring() Method

The substring() method is used to extract a portion of the string. It can be called with one or two
tik

arguments.

●​ One argument: Extracts the substring starting from the given index.

●​ Two arguments: Extracts the substring between the two indices.


as

Syntax:

String substring(int startIndex)


Sw

String substring(int startIndex, int endIndex)

Example:

public class StringExample

public static void main(String[] args)

String str = "Hello, World!";

[Link]("Substring (7, 12): " + [Link](7, 12));

Contact
7972423160
[Link]("Substring from index 7: " + [Link](7));

Output:

Substring (7, 12): World

Substring from index 7: World!

4. toLowerCase() Method

The toLowerCase() method converts all characters in the string to lowercase.

s
Syntax:

sse
String toLowerCase()

Example:

public class StringExample


Cla
{

public static void main(String[] args)

{
tik

String str = "HELLO, WORLD!";

[Link]("Lowercase: " + [Link]());

}
as

Output:
Sw

Lowercase: hello, world!

5. toUpperCase() Method

The toUpperCase() method converts all characters in the string to uppercase.

Syntax:

String toUpperCase()

Example:

public class StringExample

Contact
7972423160
{

public static void main(String[] args)

String str = "hello, world!";

[Link]("Uppercase: " + [Link]());

Output:

Uppercase: HELLO, WORLD!

s
sse
6. equals() Method

The equals() method compares two strings and returns true if the strings are equal, and false if they
are not. It compares the content of the strings, not the reference.

Syntax:
Cla
boolean equals(String otherString)

Example:
tik

public class StringExample

public static void main(String[] args)


as

String str1 = "Hello";


Sw

String str2 = "Hello";

String str3 = "World";

[Link]("str1 equals str2: " + [Link](str2));

[Link]("str1 equals str3: " + [Link](str3));

Output:

str1 equals str2: true

Contact
7972423160
str1 equals str3: false

Full Example Code:

public class StringExample

public static void main(String[] args)

String str = " Hello, World! ";

s
// 1. length()

sse
[Link]("Length: " + [Link]());

// 2. charAt()
Cla
[Link]("Character at index 7: " + [Link](7));

// 3. substring()

[Link]("Substring (7, 12): " + [Link](7, 12));


tik

[Link]("Substring from index 7: " + [Link](7));

// 4. toLowerCase()
as

[Link]("Lowercase: " + [Link]());


Sw

// 5. toUpperCase()

[Link]("Uppercase: " + [Link]());

// 6. equals()

[Link]("str equals 'Hello, World!': " + [Link]("Hello, World!"));

[Link]("str equals 'hello, world!': " + [Link]("hello, world!"));

// 7. trim()

[Link]("Trimmed string: '" + [Link]() + "'");

Contact
7972423160
}

Output:

Length: 17

Character at index 7: W

Substring (7, 12): World

Substring from index 7: World!

Lowercase: hello, world!

Uppercase: HELLO, WORLD!

s
str equals 'Hello, World!': true

sse
str equals 'hello, world!': false

Trimmed string: 'Hello, World!' Cla


[Link] String buffer reader class in java with example. Explain any 6 methods.

Ans.

The StringBuffer class in Java is used to create mutable (modifiable) strings. Unlike the String class,
which is immutable, StringBuffer allows you to modify the contents of a string after it is created,
without creating a new object every time a change is made. It is often used when there are frequent
tik

modifications to the string, as it provides better performance in such cases.

Key Points about StringBuffer:

1.​ Mutable: The string is mutable, meaning you can modify the string without creating a new
as

object.

2.​ Thread-Safety: StringBuffer is synchronized, which makes it thread-safe. This means that it
can be safely used by multiple threads without causing data corruption.
Sw

3.​ Capacity: StringBuffer maintains a capacity to hold characters. When the capacity is
exceeded, it grows dynamically.

1. append() Method

The append() method adds a string, character, or number at the end of the existing StringBuffer
object. This method is often used to combine strings or data.

Syntax:

StringBuffer append(String str)

Contact
7972423160
Example:

public class StringBufferExample

public static void main(String[] args)

StringBuffer sb = new StringBuffer("Hello");

[Link](" World");

[Link](sb);

s
}

sse
Output:

Hello World
Cla
2. insert() Method

The insert() method is used to insert the specified string or character at a specified index in the
StringBuffer.
tik

Syntax:

StringBuffer insert(int index, String str)

StringBuffer insert(int index, char c)


as

Example:
Sw

public class StringBufferExample

public static void main(String[] args)

StringBuffer sb = new StringBuffer("Hello");

[Link](5, " Java");

[Link](sb);

Contact
7972423160
Output:

Hello Java

3. delete() Method

The delete() method removes the characters from the StringBuffer from the start index to the end
index (exclusive).

Syntax:

s
StringBuffer delete(int start, int end)

sse
Example:

public class StringBufferExample

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

StringBuffer sb = new StringBuffer("Hello World");


tik

[Link](5, 11);

[Link](sb);

}
as

Output:
Sw

Hello

4. reverse() Method

The reverse() method reverses the characters in the StringBuffer.

Syntax:

StringBuffer reverse()

Example:

Contact
7972423160
public class StringBufferExample

public static void main(String[] args)

StringBuffer sb = new StringBuffer("Hello");

[Link]();

[Link](sb);

s
sse
Output:

olleH Cla
5. capacity() Method

The capacity() method returns the current capacity (the amount of memory allocated) of the
tik

StringBuffer.

Syntax:
as

int capacity()
Sw

Example:

public class StringBufferExample

public static void main(String[] args)

StringBuffer sb = new StringBuffer("Hello");

[Link]("Capacity: " + [Link]());

Contact
7972423160
Output:

Capacity: 21

6. toString() Method

The toString() method converts the StringBuffer object into a String.

Syntax:

String toString()

Example:

s
public class StringBufferExample

sse
{

public static void main(String[] args)

{
Cla
StringBuffer sb = new StringBuffer("Hello");

String str = [Link]();

[Link](str); // Output: Hello

}
tik

Output:
as

Hello
Sw

7. deleteCharAt() Method

The deleteCharAt() method removes the character at the specified index.

Syntax:

StringBuffer deleteCharAt(int index)

Example:

public class StringBufferExample

Contact
7972423160
public static void main(String[] args)

StringBuffer sb = new StringBuffer("Hello");

[Link](2);

[Link](sb);

Output:

s
Helo

sse
8. replace() Method

The replace() method replaces a part of the string from start index to end index (exclusive) with a
new string.
Cla
Syntax:

StringBuffer replace(int start, int end, String str)


tik

Example:

public class StringBufferExample


as

public static void main(String[] args)


Sw

StringBuffer sb = new StringBuffer("Hello World");

[Link](6, 11, "Java");

[Link](sb);

Output:

Hello Java

9. charAt() Method

Contact
7972423160
The charAt() method returns the character at a specified index in the StringBuffer.

Syntax:

char charAt(int index)

Example:

public class StringBufferExample

public static void main(String[] args)

s
{

sse
StringBuffer sb = new StringBuffer("Hello");

char ch = [Link](1); // Gets the character at index 1 ('e')

[Link](ch); // Output: e

}
Cla
}

Output:
tik

10. setCharAt() Method


as

The setCharAt() method sets the character at the specified index.


Sw

Syntax:

StringBuffer setCharAt(int index, char ch)

Example:

public class StringBufferExample

public static void main(String[] args)

Contact
7972423160
StringBuffer sb = new StringBuffer("Hello");

[Link](0, 'J'); // Changes the character at index 0 ('H') to 'J'

[Link](sb); // Output: Jello

Output:

Jello

s
Full Example of All Methods

sse
public class StringBufferExample

public static void main(String[] args)

{
Cla
// Create a StringBuffer object

StringBuffer sb = new StringBuffer("Hello");


tik

// 1. append() - Adds text to the end

[Link](" World");

[Link]("Appended: " + sb);


as

// 2. insert() - Inserts text at a specific position


Sw

[Link](5, " Java");

[Link]("Inserted: " + sb);

// 3. delete() - Deletes part of the string

[Link](5, 10); // Removes " Java"

[Link]("Deleted: " + sb);

// 4. reverse() - Reverses the string

[Link]();

Contact
7972423160
[Link]("Reversed: " + sb);

// 5. capacity() - Returns current capacity

[Link]("Capacity: " + [Link]());

// 6. toString() - Converts StringBuffer to String

String str = [Link]();

[Link]("Converted to String: " + str);

s
// 7. deleteCharAt() - Deletes a character at specific index

sse
[Link](0); // Deletes the first character

[Link]("After deleteCharAt: " + sb);


Cla
// 8. replace() - Replaces part of the string

[Link](0, 2, "Hi");

[Link]("After replace: " + sb);


tik

// 9. charAt() - Gets the character at a specific index

char ch = [Link](1);

[Link]("Character at index 1: " + ch);


as

// 10. setCharAt() - Sets the character at a specific index


Sw

[Link](1, 'y');

[Link]("After setCharAt: " + sb);

// 11. ensureCapacity() - Ensures minimum capacity

[Link](50);

[Link]("Capacity after ensureCapacity: " + [Link]());

Output:

Contact
7972423160
Appended: Hello World

Inserted: Hello Java World

Deleted: Hello World

Reversed: dlroW olleH

Capacity: 21

Converted to String: dlroW olleH

After deleteCharAt: lroW olleH

After replace: HiW olleH

Character at index 1: y

s
After setCharAt: HyW olleH

sse
Capacity after ensureCapacity: 50

Q28. Difference between string class and string buffer reader class.
Cla
tik
as
Sw

Contact
7972423160
Chapter 2 Inheritance, Interface and Package

Q1. Define Inheritance. List types of Inheritance with suitable Example.


Definition:
Inheritance in Java allows a class (called a subclass) to inherit fields and methods from
another class (called a superclass). This promotes code reuse, helps with method overriding,
and models "is-a" relationships.
🔹 Types of Inheritance in Java:
1.​ Single Inheritance – One subclass inherits from one superclass.

s
2.​ Multilevel Inheritance – A subclass inherits from another subclass.

sse
3.​ Hierarchical Inheritance – Multiple subclasses inherit from one superclass.
4.​ (Java does not support multiple inheritance using classes, but it does using
interfaces.)
Cla
tik
as
Sw

Example: Single Inheritance


import [Link].*;
class Animal
{
void sound()
{

Contact
7972423160
[Link]("Animal makes sound");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("Dog barks");

s
}

sse
public static void main(String[] args)
{
Dog d = new Dog();
[Link](); // inherited method
Cla
[Link](); // own method
}
}
tik

Output:
Animal makes sound
Dog barks
as

Q2. List the Uses of keywords: 1. final 2. this 3. super


Sw

1. final
●​ Used to declare constants, prevent method overriding, and inheritance.
●​ Final variable acts as a constant. Value cannot be changed.
●​ Final method does not override.
●​ Final class cannot be inherited.
●​ Examples:
final int x = 10; // constant
final void display() { } // cannot be overridden

Contact
7972423160
final class A { } // cannot be extended
2. this
●​ Refers to the current object of the class.
●​ Used to resolve naming conflict between instance variables and parameters.
●​ Example:
class Test
{
int x;

s
Test(int x)

sse
{
this.x = x; // this refers to the instance variable
}
}
Cla
3. super
●​ Refers to the superclass (parent class) object.
●​ Used to call parent class constructors or methods.
tik

●​ Example:
class Parent
{
as

void show()
{
Sw

[Link]("Parent class method");


}
}
class Child extends Parent
{
void display()
{
[Link]();

Contact
7972423160
}
}

Q3. List any four built-in packages in Java.


Built-in Packages:
1.​ [Link] – Core classes (Object, Math, String, etc.)
2.​ [Link] – Utility classes (Scanner, ArrayList, etc.)
3.​ [Link] – Input/output (File, BufferedReader, etc.)

s
4.​ [Link] – Networking (Socket, URL, etc.)

sse
Q4. Describe concept of package and its syntax.
Definition:
A package in Java is a way to group related classes and interfaces. It helps with:
Cla
●​ Organizing code
●​ Avoiding name conflicts
●​ Access protection
tik

Syntax to Declare a Package:


package mypackage;
public class MyClass
as

{
public void display()
Sw

{
[Link]("Hello from package!");
}
}
Using the Package in Another File:
import [Link];
class Test
{

Contact
7972423160
public static void main(String[] args)
{
MyClass obj = new MyClass();
[Link]();
}
}

Q5. Define syntax of abstract class and method.

s
Definition:

sse
An abstract class is a class that cannot be instantiated and may contain abstract methods
(methods without a body). Abstract classes are used when we want to define a common
template for subclasses.
Syntax:
abstract class Animal
Cla
{
abstract void sound();
}
tik

Example:
abstract class Animal
as

{
abstract void sound();
}
Sw

class Dog extends Animal


{
void sound()
{
[Link]("Dog barks");
}
public static void main(String[] args)
{

Contact
7972423160
Dog d = new Dog();
[Link]();
}
}
Output:
Dog barks

Q6. Write the three uses of final keyword with suitable example

s
final is a Java keyword used in three main ways:

sse
1. To create constants (final variables)
Once a variable is marked final, its value cannot be changed.
public class FinalVariable
{
Cla
public static void main(String[] args)
{
final int x = 10;
tik

[Link]("Value of x: " + x);


// x = 20; // ❌ Error: cannot assign a value to final variable
}
as

}
2. To prevent method overriding
Sw

A method declared as final cannot be overridden by subclasses.


class Parent
{
final void show()
{
[Link]("Final method in Parent");
}
}

Contact
7972423160
class Child extends Parent
{
// void show() {} // ❌Error: Cannot override final method
}
public class FinalMethod
{
public static void main(String[] args)
{

s
Child obj = new Child();

sse
[Link]();
}
}
Cla
3. To prevent inheritance (final class)
A class declared final cannot be extended.
final class A
tik

{
void display()
{
as

[Link]("Final class A");


}
Sw

}
// class B extends A {} // ❌ Error: Cannot inherit from final class
public class FinalClass
{
public static void main(String[] args) {
A obj = new A();
[Link]();
}

Contact
7972423160
}

Q7. What is Interface? Describe syntax, feature & need of an interface


Definition:
An interface is a blueprint in Java that contains abstract methods (and constants). It allows
you to achieve multiple inheritance and supports polymorphism.

Syntax:
interface Shape

s
{

sse
void draw(); // abstract method
} Cla
Features of Interface:
●​ Can contain only abstract methods (until Java 7).
●​ All methods are public and abstract by default.
●​ Supports multiple inheritance.
tik

●​ Cannot be instantiated.
●​ From Java 8+, interfaces can have default and static methods.
as

Need of Interface:
Sw

●​ To achieve abstraction.
●​ To implement multiple inheritance.
●​ To standardize method structures across unrelated classes.

Q8. Write a single program to implement inheritance and polymorphism (method


overriding).
Method with same name and same parameters but in the different classes known as
method overriding.
It is also called as a run time or dynamic polymorphism.

Contact
7972423160
Example:
class Animal
{
void sound()
{
[Link]("Animal makes sound");
}

s
}

sse
class Dog extends Animal
{
void sound()
{
Cla
[Link]("Dog barks");
}
}
tik

class Cat extends Animal


{
void sound()
as

{
[Link]("Cat meows");
Sw

}
}
public class InheritancePolymorphism
{
public static void main(String[] args)
{
Animal a;
a = new Dog();

Contact
7972423160
[Link]();
a = new Cat();
[Link]();
}
}
🔹 Output:
Dog barks
Cat meows

s
sse
Q9. Program to find area of rectangle and circle using interfaces
import [Link];
interface Shape
{
Cla
void area(); // abstract method
}
class Rectangle implements Shape
tik

{
int length, breadth;
Rectangle(int l, int b)
as

{
length = l;
Sw

breadth = b;
}
public void area()
{
int result = length * breadth;
[Link]("Area of Rectangle: " + result);
}
}

Contact
7972423160
class Circle implements Shape
{
int radius;
Circle(int r)
{
radius = r;
}
public void area()

s
{

sse
double result = 3.14 * radius * radius;
[Link]("Area of Circle: " + result);
}
}
Cla
public class InterfaceArea
{
public static void main(String[] args)
tik

{
Rectangle rect = new Rectangle(5, 4);
Circle circ = new Circle(3);
as

[Link]();
[Link]();
Sw

}
}
🔹 Output:
Area of Rectangle: 20
Area of Circle: 28.259999999999998

Contact
7972423160
Q10. Explain how to create a package and import it with suitable example
🔹 Step 1: Create a package and class inside it
File: MyPackage/[Link]
package MyPackage;
public class Message
{
public void greet()

s
{

sse
[Link]("Hello from MyPackage!");
}
}
📁 Folder structure should be:
Cla
MyPackage/
└── [Link]
Step 2: Use the package in another class
tik

File: [Link]
import [Link];
public class Main
as

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

{
Message msg = new Message();
[Link]();
}
}
🔹 Output:
Hello from MyPackage!

Contact
7972423160
Q11. All types of inheritances (study all)
Types of Inheritance in Java

1. Single Inheritance

🔹 Theory:
●​ In single inheritance, one class inherits from one other class.

●​ It supports an "is-a" relationship.

●​ Allows the child class to reuse methods and fields of the parent class.

Example in real life: A Car is a Vehicle. So, Car can use Vehicle's properties.

s
🔹 Code:

sse
import [Link].*;

import [Link].*;

class Vehicle

{
Cla
void run()

[Link]("Vehicle is running");
tik

public class Car extends Vehicle


as

void speed()
Sw

[Link]("Car runs at 120 km/h");

public static void main(String[] args)

Car c = new Car();

[Link](); // Inherited method

[Link](); // Own method

Contact
7972423160
}

Output:

Vehicle is running

Car runs at 120 km/h

2. Multilevel Inheritance

Theory:

●​ In multilevel inheritance, a class is derived from a class which is also derived from another
class.

s
●​ It builds a chain of inheritance.

sse
Example: Dog inherits from Animal, and Puppy inherits from Dog.

🔹 Code:
import [Link].*;

import [Link].*;
Cla
class Animal

void eat()
tik

[Link]("Animal eats food");

}
as

class Dog extends Animal


Sw

void bark()

[Link]("Dog barks");

public class Puppy extends Dog

void weep()

Contact
7972423160
{

[Link]("Puppy weeps");

public static void main(String[] args)

Puppy p = new Puppy();

[Link]();

[Link]();

[Link]();

s
}

sse
}

Output:

Animal eats food

Dog barks
Cla
Puppy weeps

3. Hierarchical Inheritance
tik

Theory:

●​ In hierarchical inheritance, multiple child classes inherit from a single parent class.

●​ All child classes get access to the parent’s methods.


as

Example: Both Dog and Cat are Animal.

🔹 Code:
Sw

import [Link].*;

import [Link].*;

class Animal

void eat()

[Link]("Animal eats");

Contact
7972423160
}

class Dog extends Animal

void bark()

[Link]("Dog barks");

class Cat extends Animal

s
{

sse
void meow()

[Link]("Cat meows");

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

Dog d = new Dog();

[Link]();
tik

[Link]();

Cat c = new Cat();

[Link]();
as

[Link]();

}
Sw

🔹 Output:
Animal eats

Dog barks

Animal eats

Cat meows

4. Multiple Inheritance (Using Interfaces)

🔹 Theory:
Contact
7972423160
●​ Java does not support multiple class inheritance (to avoid ambiguity).

●​ But you can achieve multiple inheritance using interfaces.

Why interfaces?​
Because interfaces only have method declarations, not implementations, so no conflicts.

🔹 Code:
import [Link].*;

import [Link].*;

interface Printable

s
{

sse
void print();

interface Showable
Cla
{

void show();

}
tik

public class Report implements Printable, Showable

public void print()


as

[Link]("Printing Report");
Sw

public void show()

[Link]("Showing Report");

public static void main(String[] args)

Report r = new Report();

[Link]();

Contact
7972423160
[Link]();

🔹 Output:
Printing Report

Showing Report

5. Hybrid Inheritance

Theory:

s
●​ A combination of two or more types of inheritance (e.g., single + multiple) is hybrid

sse
inheritance.

●​ Java supports it using classes + interfaces only.

Code:
Cla
import [Link].*;

import [Link].*;

interface A
tik

void methodA();

}
as

interface B extends A

{
Sw

void methodB();

class C

void methodC()

[Link]("Method of Class C");

Contact
7972423160
public class D extends C implements B

public void methodA()

[Link]("Method A from interface A");

public void methodB()

[Link]("Method B from interface B");

s
}

sse
public static void main(String[] args)

D obj = new D();

[Link]();
Cla
[Link]();

[Link]();

}
tik

🔹 Output:
Method A from interface A
as

Method B from interface B

Method of Class C
Sw

Q12. Write a single program to implement Inheritance and Polymorphism in Java

Inheritance allows a class to inherit properties and methods from another class.​
Polymorphism allows one method to behave differently based on the object that calls it.

🔸 Polymorphism is of two types:


●​ Compile-time (method overloading)

●​ Run-time (method overriding)

Code (Inheritance + Polymorphism)

class Animal

Contact
7972423160
{

void sound()

[Link]("Animal makes sound");

class Dog extends Animal

void sound()

s
{

sse
[Link]("Dog barks");

}
Cla
class Cat extends Animal

void sound()
tik

[Link]("Cat meows");

}
as

public class InheritancePolymorphism


Sw

public static void main(String[] args)

Animal a;

a = new Dog();

[Link]();

a = new Cat();

[Link]();

Contact
7972423160
}

Output

Dog barks

Cat meows

Q13. Develop a program to find area of Rectangle and Circle using Interfaces

🔹 Theory
●​ Interface is a blueprint for classes. It only contains method signatures.

●​ You can implement multiple interfaces in a class.

s
●​ This is used for abstraction and multiple inheritance in Java.

sse
🔹 Code
import [Link];

interface Shape
Cla
{

void area();

}
tik

class Rectangle implements Shape

{
as

public void area()

{
Sw

Scanner sc = new Scanner([Link]);

[Link]("Enter length: ");

double l = [Link]();

[Link]("Enter breadth: ");

double b = [Link]();

[Link]("Area of Rectangle: " + (l * b));

Contact
7972423160
class Circle implements Shape

public void area()

Scanner sc = new Scanner([Link]);

[Link]("Enter radius: ");

double r = [Link]();

[Link]("Area of Circle: " + ([Link] * r * r));

s
}

sse
public class AreaInterface

public static void main(String[] args)

{
Cla
Rectangle r = new Rectangle();

[Link]();

Circle c = new Circle();


tik

[Link]();

🔹 Output (Sample)
as

Enter length: 5
Sw

Enter breadth: 3

Area of Rectangle: 15.0

Enter radius: 2

Area of Circle: 12.566370614359172

Contact
7972423160
Q14. Explain how to create a package and import it with suitable example

🔹 Theory
A package is a group of related classes and interfaces.​
It helps to avoid class name conflicts and control access with modifiers.

🔹 Types:
●​ Built-in packages ([Link], [Link], etc.)

●​ User-defined packages

🔹 Creating a package (Steps)

s
1.​ Create a package folder:​
Example: myPackage

sse
2.​ Create class in the package:

// File: myPackage/[Link]

package myPackage;
Cla
public class Message

public void display()

{
tik

[Link]("Hello from myPackage!");

}
as

3.​ Create a main class and import it:

// File: [Link]
Sw

import [Link];

public class TestPackage

public static void main(String[] args)

Message m = new Message();

[Link]();

Contact
7972423160
🔹 Output
Hello from myPackage!

Q15. Differentiate between method overloading and method overriding.

s
sse
Cla
tik

Q16. Explain method overriding with suitable example.

●​ Method overriding happens when a subclass provides its own version of a method that is
already defined in its superclass.
as

●​ The method name, return type, and parameters must be exactly the same as in the parent
class.
Sw

●​ It enables runtime polymorphism — the Java Virtual Machine (JVM) decides which method
to run at runtime based on the object type.

Rules for Method Overriding:

1.​ The method must have same name, parameters, and return type.

2.​ The method in the child class should not have lesser visibility than the parent method.

3.​ Static, final, and private methods cannot be overridden.

4.​ It supports dynamic method dispatch (runtime polymorphism).

Example of Method Overriding in Java

Import [Link].*;

Contact
7972423160
Import [Link].*;

class Animal

void sound()

[Link]("Animal makes a sound");

s
class Dog extends Animal

sse
{

void sound()

[Link]("Dog barks");
Cla
}

class Cat extends Animal


tik

void sound()

{
as

[Link]("Cat meows");

}
Sw

public class MethodOverridingDemo

public static void main(String[] args)

Animal a1 = new Dog();

Animal a2 = new Cat();

[Link]();

[Link]();

Contact
7972423160
}

🔹 Output:
Dog barks

Cat meows

Q17. Develop an Interest Interface which contains simple interest and compound interest methods
and static final field of rate25%. Write a class to implement those methods.

interface Interest

s
static final double RATE = 25.0;

sse
void simpleInterest(double principal, double time);

void compoundInterest(double principal, double time);

}
Cla
class InterestCalculator implements Interest {

public void simpleInterest(double principal, double time)

{
tik

double simpleInterest = (principal * RATE * time) / 100;

[Link]("Simple Interest: " + simpleInterest);

}
as

public void compoundInterest(double principal, double time)

{
Sw

double compoundInterest = principal * [Link](1 + RATE / 100, time) - principal;

[Link]("Compound Interest: " + compoundInterest);

public static void main(String[] args)

InterestCalculator calculator = new InterestCalculator();

double principal = 1000;

double time = 2;

Contact
7972423160
[Link](principal, time);

[Link](principal, time);

✅ Output
Simple Interest: 500.0

Compound Interest: 506.25

Q18. Implement following

s
sse
Cla
tik

Ans.

interface Exam
as

int sports_marks = 20;

}
Sw

class Student

int roll_no;

String s_name;

int m1, m2, m3;

Student(int roll_no, String s_name, int m1, int m2, int m3)

this.roll_no = roll_no;

Contact
7972423160
this.s_name = s_name;

this.m1 = m1;

this.m2 = m2;

this.m3 = m3;

int getTotalMarks()

return m1 + m2 + m3;

s
}

sse
}

class Result extends Student implements Exam

{
Cla
Result(int roll_no, String s_name, int m1, int m2, int m3)

super(roll_no, s_name, m1, m2, m3);

}
tik

void display()

int totalMarks = getTotalMarks();


as

int finalScore = totalMarks + sports_marks;

[Link]("Roll No: " + roll_no);


Sw

[Link]("Student Name: " + s_name);

[Link]("Academic Marks: " + totalMarks);

[Link]("Sports Marks: " + sports_marks);

[Link]("Final Score: " + finalScore);

public class InheritanceDemo

public static void main(String[] args)

Contact
7972423160
{

Result student = new Result(101, "Neeta", 80, 75, 85);

[Link]();

Output

Roll No: 101

Student Name: Neeta

s
Academic Marks: 240

sse
Sports Marks: 20

Final Score: 260 Cla


Q19.
tik
as
Sw

interface Salary

int basic_sal = 50000;

class Employee implements Salary

Contact
7972423160
{

String name;

int age;

Employee(String name, int age)

[Link] = name;

[Link] = age;

void display()

s
{

sse
[Link]("Name: " + name);

[Link]("Age: " + age);

[Link]("Basic Salary: " + basic_sal); // Accessing interface variable

}
Cla
}

public class InheritanceDemo

{
tik

public static void main(String[] args)

Employee emp = new Employee("Neeta", 25);


as

[Link]();

}
Sw

Output

Name: Neeta

Age: 25

Basic Salary: 50000

Q20. Explain abstract method with example

An abstract method is a method that is declared in an abstract class but does not have a body. It only
provides the method signature (name, parameters, return type), but no implementation.

Contact
7972423160
●​ Abstract Method:

o​ The method does not contain any code to execute.

o​ It must be implemented in a subclass.

●​ An abstract class is a class that cannot be instantiated (objects cannot be created from it). It
can have both abstract methods (without a body) and concrete methods (with a body).

🔹 Use
Abstract methods allow a class to provide a common interface to its subclasses without dictating
how the method should be implemented. Each subclass is responsible for providing the specific
behavior for that method.

✅ Key Points

s
sse
1.​ Declaration: An abstract method is declared without a body.

2.​ Implementation: A subclass must override and provide an implementation for the abstract
method.

3.​ Abstract Class: You can only declare abstract methods in an abstract class. A regular class
Cla
cannot have abstract methods.

✅ Example of Abstract Method


abstract class Animal
tik

abstract void sound();

void eat()
as

[Link]("This animal is eating");


Sw

class Dog extends Animal

void sound()

[Link]("Dog barks");

Contact
7972423160
class Cat extends Animal

void sound()

[Link]("Cat meows");

public class AbstractMethodExample

s
public static void main(String[] args)

sse
{

// Animal a = new Animal(); // This will throw an error because Animal is abstract

// Creating objects of subclasses

Animal dog = new Dog();


Cla
Animal cat = new Cat();

[Link]();

[Link]();
tik

[Link]();

[Link]();

}
as

✅ Output:
Sw

Dog barks

This animal is eating

Cat meows

This animal is eating

Contact
7972423160
Unit 3- Exception Handling and Multithreading

Q1. Define the concept of Exception


An exception is an event that occurs during the execution of a program that disrupts its
normal flow. It typically occurs when something goes wrong in the program, such as trying to
access an array element that doesn't exist, dividing by zero, or trying to open a file that

s
doesn't exist.

sse
Exceptions are divided into two types:
1.​ Checked exceptions: These are exceptions that are checked at compile-time.
Example: IOException, SQLException.
2.​ Unchecked exceptions: These are exceptions that are checked at runtime. Example:
Cla
NullPointerException, ArrayIndexOutOfBoundsException.
Java provides the try-catch mechanism to handle exceptions and prevent the program from
crashing.
tik

Q2. Enlist any four compile-time errors


Compile-time errors occur when there are issues with the code that prevent it from being
compiled, such as incorrect syntax or missing methods.
as

Here are four common compile-time errors:


1.​ Syntax errors: Missing semicolons, parentheses, or incorrect spelling of keywords.
Sw

o​ Example: int x = 10 (missing ;)

2.​ Type mismatch: Trying to assign a value to a variable of an incompatible type.


o​ Example: int a = "string"; (cannot assign a String to an int)

3.​ Missing method or constructor: Calling a method that doesn't exist or is not defined.
o​ Example: [Link](); (If method() is not defined in the class)

4.​ Access modifier issues: Trying to access members of a class that have restricted
access.
o​ Example: Trying to access a private member of another class.

Contact
7972423160
Q3. Define Thread. Mention two ways to create a thread.
🔹 Theory
A thread is a lightweight process, and in Java, it allows the execution of multiple tasks
concurrently. A thread is the smallest unit of execution in a program.
Threads are used to perform multiple operations simultaneously. They are commonly used
for tasks like reading files, downloading content, or processing data in the background.
🔹 Two Ways to Create a Thread in Java:

s
sse
1.​ By Extending the Thread class: A new class is created by extending the Thread class
and overriding the run() method.
2.​ By Implementing the Runnable interface: A class implements the Runnable interface
and provides its implementation for the run() method.
Cla
Q4. Write steps to create a thread using the Runnable interface.
Steps
1.​ Implement the Runnable Interface: Create a class that implements the Runnable
tik

interface and override its run() method.


2.​ Create a Thread object: Pass the Runnable object to the Thread class constructor.
as

3.​ Start the thread: Call the start() method of the Thread object to begin execution.
🔹 Code Example
class MyRunnable implements Runnable
Sw

{
public void run()
{
[Link]("Thread is running using Runnable interface");
}
}
public class RunnableExample
{

Contact
7972423160
public static void main(String[] args)
{
MyRunnable obj = new MyRunnable();
Thread t = new Thread(obj); // Passing the Runnable object to the Thread
[Link](); // Start the thread
}
}

s
Q5. Describe thread priority

sse
●​ In Java, each thread has a priority, which determines the order in which it will be
executed.
●​ The priority is an integer value, where higher priority threads are more likely to be
executed before lower priority threads.
●​ The priority value ranges from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY
Cla
(10). By default, threads have a priority of Thread.NORM_PRIORITY (5).
🔹 Code Example to Set Thread Priority
class MyThread extends Thread
{
tik

public void run()


{
as

[Link]("Thread running with priority: " +


[Link]().getPriority());
}
Sw

public class ThreadPriorityExample


{
public static void main(String[] args)
{
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

Contact
7972423160
[Link](Thread.MAX_PRIORITY); // Setting maximum priority
[Link](Thread.MIN_PRIORITY); // Setting minimum priority

[Link](); // Start thread t1


[Link](); // Start thread t2
}
}

s
sse
Q 6. Describe the use of throws with syntax and example
●​ The throws keyword is used in Java to declare that a method might throw certain
types of exceptions.
●​ This tells the compiler that the method may not handle the exception, and it must be
handled by the calling method.
Cla
●​ It's used when a method might generate checked exceptions.
🔹 Syntax:
public void methodName() throws ExceptionType1, ExceptionType2
{
tik

// Code that might throw exceptions


}
🔹 Example:
as

import [Link].*;
Sw

class FileReaderExample
{
public void readFile() throws IOException
{
FileReader fr = new FileReader("non_existing_file.txt");
BufferedReader br = new BufferedReader(fr);
[Link]([Link]());
}
}

Contact
7972423160
public class ThrowsExample
{
public static void main(String[] args)
{
FileReaderExample obj = new FileReaderExample();
try
{
[Link]();

s
}

sse
catch (IOException e)
{
[Link]("Exception occurred: " + [Link]());
}
Cla
}
}
tik

Q7. Define the term:


i. Thread
A thread is a lightweight process in a program that can run concurrently with other threads.
as

Each thread has its own path of execution, but all threads share the same resources of the
process.
ii. Exception
Sw

An exception is an event that disrupts the normal flow of a program, usually due to an error,
and it needs to be handled to prevent the program from crashing.

Q8. Explain try, catch, finally and throw


In Java, exception handling is used to handle runtime errors so the normal flow of the
application can be maintained. It is done using these key clauses:
a) try Block
Theory:
●​ The try block is used to wrap the code that might throw an exception.

Contact
7972423160
●​ If an exception occurs inside the try block, it is caught and handled by a matching
catch block.
Syntax:
try
{
// Code that might throw exception
}
✅ Code Example:
import [Link];

s
public class TryExample

sse
{
public static void main(String[] args)
{
Cla
try
{
int a = 10;
int b = 0;
tik

int result = a / b;
[Link]("Result: " + result);
as

}
// No catch here to show that error will occur if not handled
Sw

}
}
✅ Output:
Exception in thread "main" [Link]: / by zero
🔸 If there is no catch, the program terminates with an exception.
b) catch Block
Theory:
●​ The catch block is used to handle the exception that is thrown in the try block.

Contact
7972423160
●​ You can have multiple catch blocks for different types of exceptions.
Syntax:
try
{
// risky code
}
catch (ExceptionType name)
{

s
// code to handle exception

sse
}
✅ Code Example:
import [Link];
public class CatchExample
Cla
{
public static void main(String[] args)
{
tik

try
{
int[] arr = {1, 2, 3};
as

[Link](arr[5]);
}
Sw

catch (ArrayIndexOutOfBoundsException e)
{
[Link]("Caught an exception: " + [Link]());
}
}
}
✅ Output:
Caught an exception: Index 5 out of bounds for length 3

Contact
7972423160
🔸 catch prevents program termination and handles the error gracefully.

c) throw Keyword
Theory:
●​ The throw keyword is used to manually throw an exception in Java.
●​ You can throw built-in or custom exceptions using throw.
✅ Syntax:

s
throw new ExceptionType("Message");
✅ Code Example:

sse
import [Link];
public class ThrowExample
{
Cla
public static void main(String[] args)
{
int age = 15;
tik

try
{
if (age < 18)
as

{
throw new ArithmeticException("Not eligible to vote");
Sw

}
else
{
[Link]("You can vote!");
}
}
catch (ArithmeticException e)
{

Contact
7972423160
[Link]("Exception caught: " + [Link]());
}
}
}
✅ Output:
Exception caught: Not eligible to vote
🔸 throw is used to create and trigger exceptions based on conditions.
🟩 d) finally Block

s
sse
Theory:
●​ The finally block always executes — whether an exception occurs or not.
●​ It's commonly used to release resources, such as closing files or connections.
Syntax:
Cla
try
{
// code that may throw exception
tik

}
catch (Exception e)
{
as

// handling
}
Sw

finally
{
// code that always runs
}
✅ Code Example:
import [Link];
public class FinallyExample
{

Contact
7972423160
public static void main(String[] args)
{
try
{
int num = 5 / 0;
}
catch (ArithmeticException e)
{

s
[Link]("Exception handled: " + e);

sse
}
finally
{
[Link]("This block always executes.");
Cla
}
}
}
✅ Output:
tik

Exception handled: [Link]: / by zero


This block always executes.
🔸 finally is reliable for cleanup tasks regardless of exceptions.
as

✅ Summary Table
Sw

Clause Purpose Always Executes?

try Wraps risky code No

catch Handles specific exceptions No

throw Manually throws an exception No

finally Executes after try/catch (for cleanup) Yes

Contact
7972423160
Q9. Describe the life cycle of thread with suitable example
A thread in Java can exist in any one of the following states at any given time. A thread lies
only in one of the shown states at any instant:
1.​ New State
2.​ Runnable State
3.​ Blocked State
4.​ Waiting State

s
5.​ Timed Waiting State

sse
6.​ Terminated State
The diagram below represents various states of a thread at any instant:
Cla
tik
as
Sw

●​ 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.

Contact
7972423160
●​ Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.
●​ Blocked: The thread will be in blocked state when it is trying to acquire a lock but
currently the lock is acquired by the other thread. The thread will move from the
blocked state to runnable state when it acquires the lock.

Example
class MyThread extends Thread
{

s
public void run()

sse
{
[Link]("Thread is running...");
}
}
Cla
public class Main
{
public static void main(String[] args)
tik

{
MyThread t = new MyThread(); // Thread is in NEW state
[Link]("Before start: " + [Link]());
as

[Link](); // Thread moves to RUNNABLE and then RUNNING


[Link]("After start: " + [Link]());
Sw

try
{
[Link](); // Wait for thread to finish
}
catch (Exception e)
{
[Link](e);
}

Contact
7972423160
[Link]("After finish: " + [Link]());
}
}
Output
Before start: NEW
After start: RUNNABLE
Thread is running...
After finish: TERMINATED

s
sse
Q10. Write a program to create a user-defined exception in Java
import [Link];
class MyException extends Exception
{
Cla
public MyException(String message)
{
super(message); // Call parent constructor
tik

}
}
public class UserDefinedExceptionExample
as

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

{
Scanner sc = new Scanner([Link]);
[Link]("Enter your age: ");
int age = [Link]();
try
{
if (age < 18)
{

Contact
7972423160
throw new MyException("You must be at least 18 years old.");
}
else
{
[Link]("You are eligible.");
}
}
catch (MyException e)

s
{

sse
[Link]("Caught Exception: " + [Link]());
}
}
}
Cla
✅ Output 1 (if age is 16):
Enter your age: 16
tik

Caught Exception: You must be at least 18 years old.


✅ Output 2 (if age is 20):
Enter your age: 20
as

You are eligible.


Sw

Q11. Thread A prints even numbers, Thread B prints odd numbers (1–50); Thread A sleeps
after 3rd number
Ans.
class EvenThread extends Thread
{
public void run()
{
int count = 0;
for (int i = 2; i <= 50; i += 2)

Contact
7972423160
{
[Link]("Even: " + i);
count++;
if (count == 3)
{
try
{
[Link]("Even thread sleeping...");

s
[Link](500);

sse
}
catch (InterruptedException e)
{
[Link](e);
Cla
}
}
}
tik

}
}
as

class OddThread extends Thread


{
Sw

public void run()


{
for (int i = 1; i <= 50; i += 2)
{
[Link]("Odd: " + i);
}
}
}

Contact
7972423160
public class EvenOddThreads
{
public static void main(String[] args)
{
EvenThread a = new EvenThread();
OddThread b = new OddThread();
[Link]();

s
[Link]();

sse
}
}
Sample Output (Order may vary due to thread scheduling):
Even: 2
Cla
Odd: 1
Odd: 3
Even: 4
tik

Odd: 5
Even: 6
Even thread sleeping...
as

Odd: 7
...
Sw

Even: 8
...

Q12. Differentiate between throw and throws


Ans.

Contact
7972423160
s
sse
Q14. Differentiate between Cla
tik
as
Sw

[Link] to accept a password and throw “Authentication Failure”


import [Link];
class AuthenticationFailureException extends Exception
{
public AuthenticationFailureException(String message)
{

Contact
7972423160
super(message);
}
}

public class PasswordCheck


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

s
Scanner sc = new Scanner([Link]);

sse
[Link]("Enter password: ");
String password = [Link]();
try
{
Cla
if (![Link]("admin123"))
{
throw new AuthenticationFailureException("Authentication Failure: Incorrect
password");
tik

}
else
as

{
[Link]("Login successful!");
Sw

}
}
catch (AuthenticationFailureException e)
{
[Link]([Link]());
}
}
}

Contact
7972423160
✅ Output:
Input: admin123
Enter password: admin123
Login successful!

Q16. Program with Two Threads – One prints odd numbers, one prints even numbers
import [Link].*;
class EvenThread extends Thread

s
{

sse
public void run()
{
for (int i = 2; i <= 20; i += 2)
{
Cla
[Link]("Even: " + i);
}
}
tik

class OddThread extends Thread


as

{
public void run()
Sw

{
for (int i = 1; i < 20; i += 2)
{
[Link]("Odd: " + i);
}
}
}
public class OddEvenThreads

Contact
7972423160
{
public static void main(String[] args)
{
EvenThread even = new EvenThread();
OddThread odd = new OddThread();
[Link]();
[Link]();
}

s
}
✅ Output (example):

sse
Odd: 1
Even: 2
Odd: 3
Cla
Even: 4
...
tik

Q17. Define NotMatchException thrown when password ≠ “MSBTE”


import [Link];
class NotMatchException extends Exception
as

{
public NotMatchException(String msg)
Sw

{
super(msg);
}
}

public class PasswordValidation


{
public static void main(String[] args)

Contact
7972423160
{
Scanner sc = new Scanner([Link]);
[Link]("Enter password: ");
String input = [Link]();

try
{
if (![Link]("MSBTE"))

s
{

sse
throw new NotMatchException("Password does not match 'MSBTE'");
}
else
{
Cla
[Link]("Password matched successfully!");
}
}
tik

catch (NotMatchException e)
{
[Link]("Error: " + [Link]());
as

}
}
Sw

✅ Output:
Enter password: MSBTE
Password matched successfully!

Contact
7972423160
Q18. Explain Thread Synchronization in java.
Thread synchronization is a mechanism that ensures that two or more threads do not access
shared resources or data concurrently in a way that could cause inconsistent or incorrect
results. It is used to control the access of multiple threads to shared resources, ensuring that
only one thread can access the resource at a time, thus avoiding race conditions.
In a multi-threaded environment, multiple threads can execute simultaneously, and if
multiple threads access shared resources (like variables, objects, files, etc.) without
synchronization, it may result in inconsistent or erroneous outcomes. Synchronization helps
prevent these issues by making sure that only one thread can execute a critical section of
code at a time.

s
Why is Synchronization Important?

sse
Consider this scenario:
●​ Suppose two threads try to update the same variable (e.g., a bank account balance)
at the same time without synchronization. One thread might update the balance
based on an outdated value, leading to a race condition where the final result is
Cla
incorrect.
●​ Synchronization ensures that only one thread can perform these operations at a
time, maintaining the integrity of the data.
tik

Types of Synchronization in Java:


There are two types of thread synchronization in Java:
as

1.​ Method Level Synchronization: Synchronize an entire method so that only one thread
can execute it at a time.
2.​ Block Level Synchronization: Synchronize only a part (block) of the method to make
Sw

sure that only one thread can execute that block at a time.

Q19. Explain throws in java


Ans.
The throws keyword in Java is used to declare exceptions that a method might throw during
execution.​
It informs the caller of the method that it should handle the specified exception(s).
USE:
1.​ To avoid handling exceptions inside the method using try-catch.

Contact
7972423160
2.​ To delegate the responsibility of exception handling to the calling method.
3.​ To make the program cleaner and more modular.
4.​ It’s mostly used for checked exceptions, but can also be used for unchecked ones.

Working
●​ When a method contains code that may throw an exception, and it doesn’t handle it
itself, it must declare that exception using throws.
●​ The calling method must then either handle the exception using try-catch or further
declare it with throws.

s
Syntax:

sse
returnType methodName(parameters) throws ExceptionType1, ExceptionType2, ...
{
// method body
}
Cla
Example:
tik

import [Link];
public class ThrowsExample {
public static int divide(int a, int b) throws ArithmeticException
as

{
return a / b;
Sw

}
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter numerator: ");
int num = [Link]();
[Link]("Enter denominator: ");
int den = [Link]();

Contact
7972423160
try
{
int result = divide(num, den);
[Link]("Result = " + result);
}
catch (ArithmeticException e)
{
[Link]("Error: Division by zero is not allowed!");

s
}

sse
}
}

Output:
Cla
Enter numerator: 10
Enter denominator: 2
Result = 5
tik
as
Sw

Contact
7972423160

You might also like