All Importanant Java Questions
All Importanant Java Questions
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
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:
2. Identifiers – Names for variables, methods, classes (e.g., sum, main)
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
// code block
as
Example:
Sw
[Link](num);
● 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.
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 s = "Java";
as
Answer:
Bitwise Operators:
2. | – Bitwise OR
Logical Operators:
Contact
7972423160
Operate on boolean values (true/false).
2. || – Logical OR
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
[Link]();
● Object creation allocates memory and allows access to the class's functionality.
Contact
7972423160
Java is a powerful, secure, and easy-to-learn programming language. Below are four key features:
● Java is based on OOP concepts such as class, object, inheritance, and polymorphism.
2. Platform-Independent
● Java programs are compiled into bytecode that runs on any system with a Java Virtual
Machine (JVM).
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.
● 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];
[Link]("Grade: A");
Contact
7972423160
}
[Link]("Grade: B");
[Link]("Grade: C");
s
else if (marks >= 60)
sse
{
[Link]("Grade: D");
else
Cla
{
[Link]("Grade: F (Fail)");
}
tik
[Link]();
}
as
Sample Output:
Sw
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:
Syntax:
Contact
7972423160
int a = 10;
double b = a;
Example:
int x = 5;
double y = x;
s
[Link]("int value: " + x);
sse
[Link]("Converted to double: " + y);
Output:
Cla
int value: 5
Syntax:
double a = 10.5;
Sw
int b = (int) a;
Example:
double x = 9.8;
int y = (int) x;
Contact
7972423160
[Link]("Converted to int: " + y);
Output:
Converted to int: 9
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:
{
tik
{
Sw
[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
{
Cla
Scanner sc = new Scanner([Link]);
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
{
{
tik
copiedArray[i] = originalArray[i];
{
Sw
✅ Output:
Copied Array: 10 20 30 40 50
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:
s
Rules for Method Overloading:
sse
● Methods must have different parameter lists.
Example:
void display()
void display(int a)
as
void display(String s)
[Link]();
Contact
7972423160
[Link](10);
[Link]("Java");
🖥️ Output:
Display with no arguments
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.
Example:
String name;
int age;
public Student()
name = "Unknown";
age = 0;
Contact
7972423160
{
name = n;
age = a;
s
{
sse
Student s1 = new Student();
[Link]();
[Link]();
Cla
}
}
tik
🖥️ Output:
Name: Unknown, Age: 0
as
Contact
7972423160
s
sse
Cla
Q17. Explain the significance of garbage collection in Java. How does it contribute to memory
management?
tik
Definition:
● Garbage Collection in Java is a process through which unused objects are automatically
as
● Java has a built-in Garbage Collector (GC), which runs in the background and manages
memory allocation and deallocation.
Sw
o Objects that are no longer referenced by any part of the program are considered
garbage.
Contact
7972423160
Significance of Garbage Collection:
o Java's GC automates the memory management process, reducing the need for the
programmer to manually allocate and free memory.
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
{
Sw
int sum = 0;
while (temp != 0)
Contact
7972423160
{
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
Ans.
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).
Contact
7972423160
s
sse
4. Default (Package-Private)
Same
Modifier Same Class Subclass Anywhere
Package
private Yes No No No
Contact
7972423160
Same
Modifier Same Class Subclass Anywhere
Package
s
sse
Cla
Q21. Checked whether entered string is palindrome or not.
tik
import [Link];
{
Sw
Contact
7972423160
if ([Link](i) != [Link](length - i - 1))
isPalindrome = false;
break;
if (isPalindrome)
s
}
sse
else
}
Cla
[Link]();
}
tik
Output
madam is a palindrome.
as
[Link] the use of any methods of the Vector class with their syntax.
Sw
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.
1. add(E e)
Syntax:
[Link](E e);
Contact
7972423160
Example:
2. size()
Syntax:
s
Example:
sse
int size = [Link](); // Returns the size of the vector
Syntax:
Example:
Syntax:
[Link](int index);
Example:
Contact
7972423160
Example code
import [Link];
[Link](10);
[Link](20);
s
[Link](30);
sse
[Link]("Element at index 0: " + [Link](0));
}
tik
Output
Element at index 0: 10
Element at index 1: 20
as
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:
Contact
7972423160
{
● Explanation:
s
o Each argument is accessed using the array index.
sse
● Example: Running the program with command line arguments:
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:
import [Link];
class Student
s
{
sse
String name;
int age;
Student()
{
Cla
name = "Unknown";
age = 0;
}
tik
void display()
}
Sw
[Link]("Student 1 - ");
[Link]();
Output:
Contact
7972423160
Code for Parameterized Constructor
import [Link];
class Student
String name;
int age;
s
[Link] = name;
sse
[Link] = age;
void display()
{
Cla
[Link]("Name: " + name + ", Age: " + age);
}
tik
[Link]("Student 2 - ");
[Link]();
Sw
Output:
Q25.. Explain Vector with the help of an example. Explain any 4 methods of the Vector class.
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].*;
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
s
[Link]("Vector elements: " + vector);
sse
[Link]("Element at index 1: " + [Link](1));
}
tik
1. add(E e)
o Syntax: [Link](element);
2. size()
Sw
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.
● 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:
{
as
{
Sw
Output:
2. charAt() Method
The charAt() method returns the character at a specified index in the string.
Contact
7972423160
Syntax:
Example:
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.
Syntax:
Example:
Contact
7972423160
[Link]("Substring from index 7: " + [Link](7));
Output:
4. toLowerCase() Method
s
Syntax:
sse
String toLowerCase()
Example:
{
tik
}
as
Output:
Sw
5. toUpperCase() Method
Syntax:
String toUpperCase()
Example:
Contact
7972423160
{
Output:
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
Output:
Contact
7972423160
str1 equals str3: false
s
// 1. length()
sse
[Link]("Length: " + [Link]());
// 2. charAt()
Cla
[Link]("Character at index 7: " + [Link](7));
// 3. substring()
// 4. toLowerCase()
as
// 5. toUpperCase()
// 6. equals()
// 7. trim()
Contact
7972423160
}
Output:
Length: 17
Character at index 7: W
s
str equals 'Hello, World!': true
sse
str equals 'hello, world!': false
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
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:
Contact
7972423160
Example:
[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:
Example:
Sw
[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:
{
Cla
public static void main(String[] args)
[Link](5, 11);
[Link](sb);
}
as
Output:
Sw
Hello
4. reverse() Method
Syntax:
StringBuffer reverse()
Example:
Contact
7972423160
public class StringBufferExample
[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:
Contact
7972423160
Output:
Capacity: 21
6. toString() Method
Syntax:
String toString()
Example:
s
public class StringBufferExample
sse
{
{
Cla
StringBuffer sb = new StringBuffer("Hello");
}
tik
Output:
as
Hello
Sw
7. deleteCharAt() Method
Syntax:
Example:
Contact
7972423160
public static void main(String[] args)
[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:
Example:
[Link](sb);
Output:
Hello Java
9. charAt() Method
Contact
7972423160
The charAt() method returns the character at a specified index in the StringBuffer.
Syntax:
Example:
s
{
sse
StringBuffer sb = new StringBuffer("Hello");
[Link](ch); // Output: e
}
Cla
}
Output:
tik
Syntax:
Example:
Contact
7972423160
StringBuffer sb = new StringBuffer("Hello");
Output:
Jello
s
Full Example of All Methods
sse
public class StringBufferExample
{
Cla
// Create a StringBuffer object
[Link](" World");
[Link]();
Contact
7972423160
[Link]("Reversed: " + sb);
s
// 7. deleteCharAt() - Deletes a character at specific index
sse
[Link](0); // Deletes the first character
[Link](0, 2, "Hi");
char ch = [Link](1);
[Link](1, 'y');
[Link](50);
Output:
Contact
7972423160
Appended: Hello World
Capacity: 21
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
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
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
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
Contact
7972423160
}
}
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
{
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]();
}
}
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
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
}
2. To prevent method overriding
Sw
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
}
// 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
}
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.
Contact
7972423160
Example:
class Animal
{
void sound()
{
[Link]("Animal makes sound");
}
s
}
sse
class Dog extends Animal
{
void sound()
{
Cla
[Link]("Dog barks");
}
}
tik
{
[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.
● 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
void speed()
Sw
Contact
7972423160
}
Output:
Vehicle is running
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
}
as
void bark()
[Link]("Dog barks");
void weep()
Contact
7972423160
{
[Link]("Puppy weeps");
[Link]();
[Link]();
[Link]();
s
}
sse
}
Output:
Dog barks
Cla
Puppy weeps
3. Hierarchical Inheritance
tik
Theory:
● In hierarchical inheritance, multiple child classes inherit from a single parent class.
🔹 Code:
Sw
import [Link].*;
import [Link].*;
class Animal
void eat()
[Link]("Animal eats");
Contact
7972423160
}
void bark()
[Link]("Dog barks");
s
{
sse
void meow()
[Link]("Cat meows");
}
Cla
public static void main(String[] args) {
[Link]();
tik
[Link]();
[Link]();
as
[Link]();
}
Sw
🔹 Output:
Animal eats
Dog barks
Animal eats
Cat meows
🔹 Theory:
Contact
7972423160
● Java does not support multiple class inheritance (to avoid ambiguity).
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
[Link]("Printing Report");
Sw
[Link]("Showing 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.
Code:
Cla
import [Link].*;
import [Link].*;
interface A
tik
void methodA();
}
as
interface B extends A
{
Sw
void methodB();
class C
void methodC()
Contact
7972423160
public class D extends C implements B
s
}
sse
public static void main(String[] args)
[Link]();
Cla
[Link]();
[Link]();
}
tik
🔹 Output:
Method A from interface A
as
Method of Class C
Sw
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.
class Animal
Contact
7972423160
{
void sound()
void sound()
s
{
sse
[Link]("Dog barks");
}
Cla
class Cat extends Animal
void sound()
tik
[Link]("Cat meows");
}
as
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.
s
● This is used for abstraction and multiple inheritance in Java.
sse
🔹 Code
import [Link];
interface Shape
Cla
{
void area();
}
tik
{
as
{
Sw
double l = [Link]();
double b = [Link]();
Contact
7972423160
class Circle implements Shape
double r = [Link]();
s
}
sse
public class AreaInterface
{
Cla
Rectangle r = new Rectangle();
[Link]();
[Link]();
🔹 Output (Sample)
as
Enter length: 5
Sw
Enter breadth: 3
Enter radius: 2
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
s
1. Create a package folder:
Example: myPackage
sse
2. Create class in the package:
// File: myPackage/[Link]
package myPackage;
Cla
public class Message
{
tik
}
as
// File: [Link]
Sw
import [Link];
[Link]();
Contact
7972423160
🔹 Output
Hello from myPackage!
s
sse
Cla
tik
● 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.
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.
Import [Link].*;
Contact
7972423160
Import [Link].*;
class Animal
void sound()
s
class Dog extends Animal
sse
{
void sound()
[Link]("Dog barks");
Cla
}
void sound()
{
as
[Link]("Cat meows");
}
Sw
[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);
}
Cla
class InterestCalculator implements Interest {
{
tik
}
as
{
Sw
double time = 2;
Contact
7972423160
[Link](principal, time);
[Link](principal, time);
✅ Output
Simple Interest: 500.0
s
sse
Cla
tik
Ans.
interface Exam
as
}
Sw
class Student
int roll_no;
String s_name;
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
}
{
Cla
Result(int roll_no, String s_name, int m1, int m2, int m3)
}
tik
void display()
Contact
7972423160
{
[Link]();
Output
s
Academic Marks: 240
sse
Sports Marks: 20
interface Salary
Contact
7972423160
{
String name;
int age;
[Link] = name;
[Link] = age;
void display()
s
{
sse
[Link]("Name: " + name);
}
Cla
}
{
tik
[Link]();
}
Sw
Output
Name: Neeta
Age: 25
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:
● 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.
void eat()
as
void sound()
[Link]("Dog barks");
Contact
7972423160
class Cat extends Animal
void sound()
[Link]("Cat meows");
s
public static void main(String[] args)
sse
{
// Animal a = new Animal(); // This will throw an error because Animal is abstract
[Link]();
[Link]();
tik
[Link]();
[Link]();
}
as
✅ Output:
Sw
Dog barks
Cat meows
Contact
7972423160
Unit 3- Exception Handling and Multithreading
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
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
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
Contact
7972423160
[Link](Thread.MAX_PRIORITY); // Setting maximum priority
[Link](Thread.MIN_PRIORITY); // Setting minimum priority
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
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
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.
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
✅ Summary Table
Sw
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
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
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
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
...
Contact
7972423160
s
sse
Q14. Differentiate between Cla
tik
as
Sw
Contact
7972423160
super(message);
}
}
s
Scanner sc = new Scanner([Link]);
sse
[Link]("Enter password: ");
String password = [Link]();
try
{
Cla
if ()
{
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
{
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
{
public NotMatchException(String msg)
Sw
{
super(msg);
}
}
Contact
7972423160
{
Scanner sc = new Scanner([Link]);
[Link]("Enter password: ");
String input = [Link]();
try
{
if ()
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
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.
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