The document provides a comprehensive overview of Java programming concepts, including polymorphism, inheritance, encapsulation, abstraction, and exception handling. It explains various features such as method overloading, the significance of the 'this' keyword, and the structure of Java programs. Additionally, it discusses Java security, portability, and the differences between JDK, JRE, and JVM, along with examples and code snippets to illustrate the concepts.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0 ratings0% found this document useful (0 votes)
3 views35 pages
Java Solutions
The document provides a comprehensive overview of Java programming concepts, including polymorphism, inheritance, encapsulation, abstraction, and exception handling. It explains various features such as method overloading, the significance of the 'this' keyword, and the structure of Java programs. Additionally, it discusses Java security, portability, and the differences between JDK, JRE, and JVM, along with examples and code snippets to illustrate the concepts.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Q1. What do you mean by the term Polymorphism? Explain with a suitable
example.
Ans:- Polymorphism is one of the important features of Object-Oriented Programming
(OOP). The word Polymorphism means "many forms”. In Java, the same method name can
be used for different purposes by changing its parameters.
Types of Polymorphism in Java:
1. Compile-time Polymorphism (Method Overloading)
2. Run-time Polymorphism (Method Overriding)
Eg:-
class Addition {
int add(int a, int b) {
return a+b;
}
int add(int a, int b, int c) {
returna+b+c;
t
t
class Demo {
public static void main(String[] args) {
Addition obj = new Addition();
[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
}
}
Output :-
30
60
Q2. Describe Static polymorphism or Method Overloading technique with the
help of a simple Java program.
Ans:- Static Polymorphism is a type of polymorphism in which the method to be called is
decided at compile time. It is achieved through Method Overloading.
Method Overloading means defining multiple methods with the same name in a class but
with different parameter lists .
Eg:-class Display {
void show() {
[Link]("No argument method");
}
void show(int a) {
[Link]("Integer argument: " + a);
t
void show(String name) {
[Link]("String argument: " + name);
t
}
public class OverloadingDemo {
public static void main(String[] args) {
Display obj = new Display();
[Link]();
[Link](10);
[Link]("Anuyj");
}
}
Output
No argument method
Integer argument: 10
String argument: Anuj
Q3. Describe different type of inheritance in Java with the help of suitable
diagrams.
Ans:- Inheritance is an OOP feature that allows one class to acquire the properties and
methods of another class.
Types of Inheritance in Java
1. Single Inheritance
Achild class inherits from one parent class.
A
|
B
2. Multilevel Inheritance
Aclass inherits from another class, which itself inherits from another class.
A
|
B
I
Cc3. Hierarchical Inheritance
Multiple child classes inherit from the same parent class.
A
JIN
BCD
4. Multiple Inheritance
‘A class inherits from more than one parent class.
AB
\/
c
5. Hybrid Inheritance
It is a combination of two or more types of inheritance.
A
/\
BC
V/
D
Q 4. Why Java does not support multiple inheritance? Justify your answer.
Ans:- Multiple Inheritance is a feature in which a class inherits properties and methods
from more than one parent class.
A B
\/
c
java does not support multiple inheritance through classes because it can create ambiguity,
known as the Diamond Problem.
Eg:- class A {
void show() {
[Link]("Class A");
}
}
class B{
void show() {
[Link]("Class B"
}
}
class C extends A, B {
}If we call:
C obj = new C();
[Link]();
The compiler cannot decide whether to execute show() from class A or class B. This creates
ambiguity and confusion. That’s why java does not support multiple inheritance.
Instead of multiple inheritance through classes, Java uses Interfaces. A class can implement
multiple interfaces without ambiguity.
Q5. With relevant examples describe abstraction and encapsulation. Write a
java program that uses an abstraction and encapsulation.
Ans:- Abstraction
Abstraction is the process of hiding implementation details and showing only the essential
features of an object.
Eg:- When we drive a car, we use the steering, wheel, brake, and accelerator without
knowing the internal working of the engine.
Encapsulation
Encapsulation is the process of binding data and methods into a single unit (class) and
restricting direct access to data using private access modifiers.
Eg:- A student's marks are kept private and cannot be changed directly by anyone. The
marks can only be accessed or modified through methods such as setMarks() and
getMarks().
Java Program Using Abstraction and Encapsulation
abstract class Animal { // Abstraction
abstract void sound();
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
class Student { // Encapsulation
private String name;
public void setName(String name) {
[Link] = name;
}
public String getName() {
return name;}
}
public class Demo {
public static void main(String[] args) {
// Abstraction
Animal a = new Dog();
[Link]();
// Encapsulation
Student s = new Student();
[Link]("Anuj");
[Link]("Student Name: " + [Link]());
}
}
Output
Dog barks
Student Name: Anuj
Q6. Create a simple Java program to implement basic Calculator operations.
Ans:-
import [Link];
public class BasicCalculator {
public static void main(String[] args) {
double num1, num2;
Scanner sc = new Scanner([Link]);
[Link]("Enter the number
num1 = [Link]();
num2 = [Link]();
[Link]("Enter the operator (+, -, *, /):");
char operator = [Link]().charAt(0);
double result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*":
result = num1 * num2;
break;break;
default:
[Link]("Invalid operator.");
return;
}
[Link]("The final result:");
[Link](num1 + "'" + operator +
+num2+"="+ result);
}
}
Output:
Enter the numbers:
2
2
Enter the operator (+,-,*,/)
+
The final result:
2.0+2.0=4.0
Q7. Write a java program using array to perform sum and average of all
values in an array.
Ans:-
public class ArraySumAverage {
public static void main(String[] args) {
int arr[] = {10, 20, 30, 40, 50};
int sum = 0;
double average;
for(int i = 0; i < [Link]; i++) {
sum = sum + arr[i];
}
average = (double) sum / [Link];
[Link]("Sum =" + sum);
[Link]("Average = " + average);Q 8. How can we overload the constructor? Explain by using multilevel
inheritance.
Ans:- Constructor overloading is a feature in Java where a class contains more than one
constructor with the same name but different parameter lists.
Example Using Multilevel Inheritance:
class Person {
Person() {
[Link]("Person Constructor");
}
Person(String name) {
[Link]("Person Name: " + name);
}
}
class Student extends Person {
Student() {
super("Anuj");
[Link]("Student Constructo!
}
}
class Monitor extends Student {
Monitor() {
[Link]("Monitor Constructor");
}
}
public class Test {
public static void main(String[] args) {
Monitor m = new Monitor();
}
}
Output:
Person Name: Anuj
Student Constructor
Monitor ConstructorQ 9. Explain Java security, Portability?
Ans:- Java Security:
Java provides a secure environment for developing and running applications. It protects
systems from unauthorized access and malicious code.
Features of Java Security
1. Bytecode Verification — Checks code before execution to ensure it is safe.
2. Exception Handling — Helps manage runtime errors safely.
3. Access Modifiers — private, protected, and public control access to data and methods
Java Portabili
Portability means a Java program can run on different platforms without modification. Java
follows the principle:
“Write Once, Run Anywhere"
How Java Achieves Portability
1. Java source code is compiled into bytecode.
2. Bytecode runs on the Java Virtual Machine (JVM).
3. Since JVM is available for different operating systems, the same program can run
anywhere.
Q10. What is the Structure of Java? Explain type of programs in Java.
Ans:- Basic structure of java:
class Hello {
public static void main(Stringl] args) {
[Link]("Hello World");
}
}
Types of Programs in Java
1. Application Program
+ Execution starts from the main() method.
Example:
class Test {
public static void main(String[] args) {
[Link]("Java Application");
}
i2. Applet Program
+ It does not use the main() method.
« Uses methods like init(), start(), and paint().
Example:
import [Link];
import [Link];
public class MyApplet extends Applet {
public void paint(Graphics g) {
[Link]("Hello Applet", 50, 50);
}
}
Q11. Discuss about the super keyword in java with example.
Ans:- The super keyword in Java is used to refer to the immediate parent class object. It is
mainly used to access parent class variables, methods, and constructors.
Eg:-
class Animal {
Animal() {
[Link]("Animal Constructor");
}
}
class Dog extends Animal {
Dog() {
super();
[Link]("Dog Constructor");
}
}
public class Test {
public static void main(String[] args) {
Dog d = new Dog();
}
}
Output:
Animal Constructor
Dog ConstructorQ 12. Write the difference between Method Overriding and Method
Overloading.
Ans:-
Method Overloading Method Overriding
Occurs in the same class. Occurs in parent and child classes.
Methods have the same name but different Methods have the same name and same
parameters. parameters.
Achieves Compile-time Polymorphism. Achieves Run-time Polymorphism.
Inheritance is not required. Inheritance is required.
Method call is resolved at compile time. Method call is resolved at runtime.
Q 13. What is the difference between JDK, JRE, and JVM? Explain their roles.
Ans:- JDK (Java Development Kit)
JDK is a software package used to develop, compile, and run Java programs.
Role:
+ Provides tools for Java development.
+ Contains JRE and development tools such as the Java compiler (javac).
JRE (Java Runtime Environment)
JRE is a software package used to run Java applications.
Role:
+ Provides the environment required to execute Java programs.
« Contains JVM and supporting libraries.
JVM (Java Virtual Machine)
JVM is a virtual machine that executes Java bytecode.
Role:
+ Converts bytecode into machine code.
« Makes Java platform independent.Q 14. Define a class and object in Java. Explain with suitable examples.
Ans:- Class:
Aclass is a blueprint or template used to create objects. It contains data members
(variables) and methods (functions).
Object:
An object is an instance of a class. It represents a real-world entity and is used to access the
members of the class.
Eg:-
class Student {
String name = "Anuj";
void display() {
[Link]("Name: "+ name);
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student(); // Object creation
[Link]();
}
}
OUTPUT:
Name: Anuj
Q15. Explain the concept of encapsulation. How is it achieved in Java?
Ans:- Encapsulation is the process of wrapping data and methods into a single unit called a
class. It also restricts direct access to data and provides controlled access through methods.
Encapsulation is achieved by:
1. Declaring variables as private.
2. Providing public getter and setter methods to access and modify the data.
Eg:-
class Employee {
private int salary;
public void setSalary(int salary) {
[Link] = salary;
}
public int getSalary() {
return salary;}
}
public class Test {
public static void main(String[] args) {
Employee e = new Employee();
[Link](30000);
[Link]("Salary = " + [Link]());
}
}
Output
Salary = 30000
Q 18. What is the significance of using “this” keyword? Explain with example
programs.
Ans:- The ‘this’ keyword in Java refers to the current object of a class. It is used to
distinguish between instance variables and local variables.
Significance / Uses of this Keyword
1. Refers to the current object.
2. Resolves difference between instance variables and local variables.
3. Can be used to call current class constructors.
4. Can be passed as an argument to methods.
Eg:-
class Student {
int rollNo;
Student(int rollNo) {
[Link] = rollNo;
}
void display() {
[Link]("Roll No: " + [Link]);
}
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student(101);
[Link]();
}
}Q19. Why do we use “static” and “public” keywords in the following
statement —“public static void main(String args[ ] )” ?
Ans:- Why is public Used?
The public keyword is an access modifier that makes the main() method accessible from
anywhere. Since the Java Virtual Machine (JVM) is responsible for starting the execution of a
program, it must be able to access and invoke the main() method. If the main() method is
not declared as public, the JVM will not be able to call it, and the program will not execute.
Why is static Used?
The static keyword indicates that the main() method belongs to the class rather than to any
object of the class. Therefore, the JVM can call the main() method directly without creating
an object of the class.
Q20. Why Java is called Architecture neutral language?
Ans:- Java is called an Architecture Neutral Language because Java programs are not
dependent on any specific hardware or processor architecture. The same Java program can
run on different systems without modification.
Reasons Why Java is Architecture Neutral
« Java generates platform-independent bytecode.
+ Bytecode can run on any machine having a JVM.
« Noneed to rewrite or recompile the program for different processors.
+ Supports the principle "Write Once, Run Anywhere ."
Q. How can you create your own package in Java and add multiple classes
inside that package and Explain with a suitable example program.
Ans:- Steps to Create a User-Defined Package
1. Create a package using the ‘package’ keyword.
2. Add one or more classes inside the package.
3. Compile the package classes.
4. Import the package in another program using the ‘import’ statement.
Package Class 1: [Link]
package mypack;
public class Addition {
public void add(int a, int b) {
[Link]("Sum =" + (a + b));
}
tPackage Class 2: [Link]
package mypack;
public class Subtraction {
public void sub(int a, int b) {
[Link]("Difference = " + (a - b));
}
}
Main Program
import [Link];
import [Link];
public class Test {
public static void main(String[] args) {
Addition a = new Addition();
Subtraction s = new Subtraction();
[Link](20, 10);
[Link](20, 10);
}
}
Output
Sum = 30
Difference = 10
Q. Explain multiple catch blocks in Java.
Ans:- Multiple catch blocks in Java are used when a program may throw different types of
exceptions. We can use more than one catch block with a single try block to handle
different exceptions separately.
Syntax:-
try{
// code that may cause exceptions
}
catch(ExceptionTypel e) {
// handling code
}
catch(ExceptionType2 e) {
// handling code
}
catch(ExceptionType3 e) {
// handling code
}Q. Explain exception handling mechanism in Java with all keywords (try, catch,
throw, throws, finally) and program.
Ans:- Exception Handling is a mechanism in Java used to handle runtime errors so that the
normal flow of the program is not interrupted.
Keywords Used in Exception Handling
1. try
The try block contains the code that may generate an exception.
2. catch
The catch block handles the exception generated in the try block.
3. throw
The throw keyword is used to explicitly throw an exception.
4. throws
The throws keyword declares exceptions that may occur in a method.
5. finally
The finally block always executes whether an exception occurs or not.
Eg:-
class ExceptionDemo {
static void checkAge(int age) throws ArithmeticException {
iflage < 18) {
throw new ArithmeticException("Not Eligible for Voting");
}
else {
[Link]("Eligible for Voting");
}
}
public static void main(String[] args) {
try{
checkAge(15);
}
catch(ArithmeticException e) {
[Link]("Exception Caught: " + [Link]());
}
finally {
[Link]("Finally Block Executed");
}
}
i
Output
Exception Caught: Not Eligible for Voting
Finally Block ExecutedQ. Explain exception handling in detail with user-defined exception with
suitable example.
Ans:- Exception Handling is a mechanism used to handle runtime errors and maintain the
normal flow of a program.
Java handles exceptions using:
+ try
«catch
«throw
«_throws
+ finally
User-Defined Exception:-
Java allows programmers to create their own exceptions. Such exceptions are called User-
Defined Exceptions or Custom Exceptions.A user-defined exception is created by extending
the Exception class.
Eg:-
class AgeException extends Exception {
AgeException(String message) {
super(message);
}
}
public class Voting {
Static void checkAge(int age) throws AgeException {
if(age < 18) {
throw new AgeException("Age must be 18 or above");
}
else {
[Link]("Eligible for Voting");
}
}
public static void main(String[] args) {
try{
checkAge(16);
}
catch(AgeException e) {
[Link]("Exception Caught: " + [Link]());
}
}
}
Output : - Exception Caught: Age must be 18 or aboveQ. Explain thread creation in Java using Thread class and using Runnable
interface
Ans:- 1. Thread Creation Using Thread Class
In this method, a class extends the Thread class and overrides the run() method. The thread
starts when the start() method is called.
Program
class MyThread extends Thread {
public void run() {
[Link]("Thread is running"); Output:-
} Thread is running
public static void main(String[] args) {
MyThread t = new MyThread();
tstart();
}
}
2. Thread Creation Using Runnable Interface
In this method, a class implements the Runnable interface and provides the implementation
of the run() method.
Program
class MyRunnable implements Runnable {
public void run() {
[Link]("Thread is running");
}
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
tstart();
}
Output:-
Thread is running
}Q. Explain exception handling in Java with try, catch, finally with suitable
program.
Ans:- Exception Handling is a mechanism in Java used to handle runtime errors and
maintain the normal flow of a program.
Keywords Used
1. try
The try block contains the code that may generate an exception.
2. catch
The catch block handles the exception generated in the try block.
3. finally
The finally block always executes whether an exception occurs or not.
Program
public class ExceptionDemo {
public static void main(String[] args) {
try{
inta= 10/0;
[Link](a);
}
catch (ArithmeticException e) {
[Link]("Exception Caught: Division by Zero");
}
finally {
[Link]("Finally Block Executed");
}
}
}
Output
Exception Caught: Division by Zero
Finally Block ExecutedQ. Design a Java program demonstrating inheritance, abstract class, interface,
and String handling together.
Ans:-
// Interface
interface Display {
void show();
}
// Abstract Class
abstract class Person {
String name;
Person(String name) {
[Link] = name;
abstract void details();
}
//\nheritance
class Student extends Person implements Display {
Student(String name) {
super(name);
}
void details() {
[Link]("Student Name: " + name);
}
public void show() {
[Link]("Name in Uppercase: " + [Link]());
}
}
public class Demo {
public static void main(String[] args) {
Student s = new Student("Anuj");
[Link](); // Abstract class method
[Link](); _// Interface method
// String Handling
[Link]("Length of Name: " + [Link]());
}
}
Output
Student Name: Anuj
Name in Uppercase: ANUJ
Length of Name: 4Q. Explain packages in Java including creation, importing, and access control in
detail.
Ans:- A Package in Java is a collection of related classes, interfaces, and sub-packages.
Packages are used to organize Java programs and avoid naming conflicts.
Creating a Package
A package is created using the package keyword at the beginning of the Java file.
Example
package mypack;
public class Addition {
public void add(int a, int b) {
[Link]("Sum =" + (a + b));
}
}
Importing a Package
To use classes of a package in another program, we use the import keyword.
Example
import [Link];
public class Test {
public static void main(String[] args) {
Addition obj = new Addition();
[Link](10, 20);
}
t
Access Control in Packages
Access Modifier Same Class Same Package Different Package
private Yes No No
default Yes Yes No
protected Yes Yes Yes (through inheritance)
public Yes Yes YesQ. Explain interface in Java and how multiple inheritance is achieved using it.
Ans:- An interface is a blueprint of a class that contains method declarations but not their
implementation. The implementation of these methods is provided by the class that
implements the interface.
Multiple Inheritance Using Interface
Java does not support multiple inheritance through classes because it can create ambiguity
(Diamond Problem). However, Java achieves multiple inheritance through interfaces.
Example
interface Father {
void showFather();
}
interface Mother {
void showMother();
}
class Child implements Father, Mother {
public void showFather() {
[Link]("Father's Method");
}
public void showMother() {
[Link]("Mother's Method");
}
t
public class Test {
public static void main(String[] args) {
Child c = new Child();
[Link]();
[Link]();
}
}
Output
Father's Method
Mother's MethodQ. Explain dynamic method dispatch and runtime polymorphism in detail.
Ans:-
Runtime Polymorphism is the process
in which a call to an overridden
method is resolved at runtime rather
than at compile time. It is achieved
through method overriding.
Dynamic Method Dispatch is the
mechanism by which a call to an
overridden method is resolved at
runtime. Java uses dynamic method
dispatch to implement runtime
polymorphism.
class Animal {
void sound() {
[Link]("Animal makes.
sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
[Link]();
}
}
Ans:- String Class
Q. Explain String and StringBuffer classes with all important methods.
StringBuffer Class
The String class in Java is used to create
and manipulate sequences of characters.
String objects are immutable, which
means their values cannot be changed
after creation.
The StringBuffer class is used to create
mutable strings. Unlike String objects,
creation. Eg:- StringBuffer sb = new
StringBuffer("Java");
Eg:- String str = "Hello";
Important Methods of String Class
Eg:- StringBuffer sb = new StringBuffer("Java");
Important Methods of StringBuffer Class
StringBuffer objects can be modified after
1. length() 1. append()
Returns the length of the string. Adds text at the end.
2. charAt() 2. insert() _ _
Returns the character at a specified index. ESL at a specified position.
3, toUpperCase() Replaces characters between indexes.
Converts the string to uppercase. 4. delete()
4. toLlowerCase() Deletes characters from a string.
Converts the string to lowercase. 5. reverse()
5. equals() Reverses the string.
Compares two strings.Q. Describe different type of inheritance in Java with the help of suitable
diagrams and Write a program showing multilevel inheritance.
Ans:-
Types of Inheritance in Java
1. Single Inheritance 2. Multilevel Inheritance
| A class inherits from another class, and that class
A child class inherits from only one parent | | further inherits from another class.
class. A
7 |
| B
: |
Cc
3. Hierarchical Inheritance 4. Multiple Inheritance
Multiple child classes inherit from a single Aclass inherits from more than one parent class.
parent class. A B
A \/
JIN c
BCD
5. Hybrid Inheritance
Acombination of two or more types of
inheritance.
A
/\
BC class Monitor extends Student {
\V/ void displayMonitor() {
EEE EE EEE EERE EEE EEE EEEEE} [Link]("| am a Monitor");
Java Program Showing Multilevel Inheritance }
class Person { }
void displayPerson() { Public class Test {
[Link]("I am a Person"); palate sialic pod in rial | TES
} Monitor m = new Monitor();
} [Link]();
class Student extends Person { [Link]();
void displayStudent() { [Link]();
[Link]("| am a Student"); } }
} } Output
!am a Person
lam a Student
am a MonitorQ. Explain class relationships: association, aggregation, and instantiation.
Ans:- 1. Association
Association is a relationship where one class uses or interacts with another class.
Program
class Student {
String name = "Anuj";
}
class Teacher {
void teach(Student s) {
t
}
[Link]("Teaching " + [Link]);
2. Aggregation
3. Instantiation
Aggregation is a special type of
reference to another class.
association where one class contains a
Example
Instantiation is the process of creating an object
from a class using the ‘new’ keyword.
Example
class Teacher {
String name;
Teacher(String name) {
[Link] = name;
}
}
class Department {
Teacher t;
Department(Teacher t) {
this.t = t;
}
void display() {
[Link]([Link]);
t
}
class Student {
void display() {
[Link]("Student Object
Created");
}
}
public class Test {
public static void main(String[] args) {
Student s = new Student(); // Instantiation
[Link]();
}
}
Output
Student Object CreatedQ. Explain constructor overloading and method overloading with programs.
Ans:- Constructor Overloading
Constructor Overloading is a feature
in which a class contains more than
one constructor with the same name
but different parameter lists.
Method Overloading
Method Overloading is a feature in which
multiple methods have the same name but
different parameter lists within the same
class.
[Link]("Default Constructor");
}
Student(String name) {
[Link]("Student Name: " +
name);
}
}
public class Test {
public static void main(Stringl] args) {
Student s1 = new Student();
Student s2 = new Student("Ani
}
Program Program
class Student { class Addition {
Student() { void add(int a, int b) {
[Link]("Sum =" + (a +b);
}
void add{int a, int b, int c) {
[Link]("Sum =" + (a +b +c));
}
}
public class Test {
public static void main(String[] args) {
Addition obj = new Addition();
[Link](10, 20);
[Link](10, 20, 30);
} }
}
Output
Default Constructor
Student Name: Anuj Output
Sum = 30
Sum = 60Q. Explain data types, operators, and control statements in Java.
Ans:- 1. Data Types in Java
A Data Type specifies the type of data that a variable can store.
Types of Data Types
(A) Primitive Data Types :- byte, short, char, Boolean, int, float, long, double
(B) Non-Primitive Data Types:- String , Array , Class , Interface
2. Operators in Java
Operators are special symbols used to perform operations on variables and values.
Types of Operators
(A) Arithmetic Operators:- +,-,* ,/,%
(B) Relational Operators:-
(C) Logical Operators:- &&, ||, !
>, <,>5, <=
(E) Increment/Decrement Operators:- ++, --
3. Control Statements in Java
Control statements control the flow of execution in a program.
Types of Control Statements
(A) Conditional Statements:- if statement, if-else statement, switch statement
(B) Looping Statements:- for loop, while loop, do-while loop
(C) Jump statements:- break, continue, return
Q. Explain class, object, and constructor in detail.
Ans:- 1, Class
A Class is a blueprint or template used to create objects. It contains variables and methods
that define the properties and behavior of an object.
Syntax
class ClassName {
// variables
// methods
i2. Object
An Object is an instance of a class. It represents a real-world entity and is used to access the
members of a class.
Syntax
ClassName objectName = new ClassName();
3. Constructor
A Constructor is a special method that is automatically called when an object is created. It is
used to initialize the object.
Types of Constructors
(A) Default Constructor:- A constructor with no parameters.
(B) Parameterized Constructor:- A constructor that accepts parameters.
Q. What is inter-thread communication?
Ans:- Inter-Thread Communication is a mechanism in Java that allows threads to
communicate and coordinate with each other. It is used when one thread needs to wait for
another thread to complete a task before proceeding.
Java provides the following methods for inter-thread communication:
« wait()
+ notify()
« notifyAll()
Q. Difference between throw and throws.
throw throws
re = Used to declare exceptions that a method may
Used to explicitly throw an exception.
throw.
Followed by an exception object. Followed by exception class names.
Used inside a method body. Used in the method declaration.
Throws one exception at a time. Can declare multiple exceptions.
Transfers control to the nearest catch _ Informs the compiler and caller about possible
block. exceptions.Q. Define deadlock.
Ans:- A Deadlock is a situation in multithreading where two or more threads are waiting
indefinitely for each other to release resources, and none of them can proceed further.
In other words:
A deadlock occurs when two or more threads block each other permanently by waiting for
resources held by one another.
Q. Define thread life cycle.
Ans:- The lifecycle of a thread in Java defines the various states a thread goes through from
its creation to termination. Understanding these states helps in managing thread behavior
and synchronization in multithreaded applications.
States of a Thread
1. New (Born State), 2. Runnable State, 3. Running State, 4. Blocked / Waiting State,
5. Terminated (Dead State)
Q. What is a thread in Java?
Ans:- A Thread is the smallest unit of execution within a process. It is a lightweight process
that allows a program to perform multiple tasks simultaneously.
In Java, threads are used to achieve multithreading, which improves the performance and
responsiveness of applications.
Simple Program
class MyThread extends Thread {
public void run() {
[Link]("Thread is running");
}
public static void main(String[] args) {
MyThread t = new MyThread();
tstart();
}
}
Output
Thread is runningQ. What is exception handling in Java?
Ans:- Exception Handling is a mechanism in Java used to handle runtime errors so that the
normal flow of the program is not interrupted.
Example
public class Test {
public static void main(String[] args) {
try{
int a= 10/0;
[Link](a);
catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}
}
}
Output
Cannot divide by zero
Q. Explain importance of reusability in OOP.
Ans:- Reusability is one of the main features of Object-Oriented Programming (OOP). It
allows existing classes, methods, and code to be used again in new programs without
rewriting them.
Importance of Reusability in OOP
1, Reduces code duplication by reusing existing code.
2. Saves development time and effort.
3. Improves code maintainability.
4. Increases programmer productivity.
5.
. Makes programs more reliable and less error-prone.Q. Explain package creation and access control in Java.
Ans:- A Package is a collection of related classes and interfaces. It is used to organize Java
programs, avoid naming conflicts, and improve code reusability.
Creating a Package
A package is created using the package keyword at the beginning of the Java file.
package mypack;
public class Student {
public void display() {
[Link]("Welcome to Package");
}
}
Access Control in Java
Access Control determines the accessibility of classes, variables, methods, and constructors.
Java provides access control through access modifiers.
Types of Access Modifiers
1. Private (private): Accessible only within the same class.
2. Default (No Modifier): Accessible within the same package only.
3. Protected (protected): Accessible within the same package and in
subclasses of other packages.
4. Public (public): Accessible from anywhere in the program.
Q. Explain Scanner class for input.
Ans:-The Scanner class is used to take input from the user during program execution. It is
available in the [Link] package.
Before using the Scanner class, we must import it:- import [Link];
Example Program
import [Link]; Sample Output
public class InputDemo { Enter your age: 20
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your age: ");
int age = [Link]();
[Link]("Age: " + age);Q. Difference between abstract class and interface.
Ans:-
Abstract Class
An abstract class is declared using the
abstract keyword.
Methods can be private, protected, or
public
Acclass can extend only one abstract class.
Constructors are allowed.
Supports single inheritance
Can have final methods
Interface
An interface is declared using the
interface keyword.
Methods are public by default
Aclass can implement multiple
interfaces.
Constructors are not allowed.
Supports multiple inheritance
Cannot have final methods
Q. Difference between String and StringBuffer.
Ans:-
String
String objects are immutable
Any modification creates a new object.
Slower when frequent changes are
required.
Stored as fixed text.
Uses the String class.
Less memory efficient for repeated
changes.
StringBuffer
StringBuffer objects are mutable
Modifications are made to the same object.
Faster for frequent modifications.
Can be modified dynamically.
Uses the StringBuffer class.
More memory efficient for repeated
changes.Q. What is an interface in Java?
Ans:-
An Interface in Java is a blueprint of a
class that contains method
declarations but not their
implementation. The class that
implements the interface provides the
implementation of these methods.
Q. Define dynamic method dispatch.
Ans:-
interface Animal {
void sound();
t
class Dog implements Animal {
public void sound() {
[Link]("Dog Barks");
}
}
public class Test {
public static void main(String[] args)
{
Dog d = new Dog();
[Link]();
}
}
Output
Dog Barks
class Animal {
void sound() {
[Link]("Animal Sound");
Dynamic Method Dispatch is the
mechanism by which a call to an
overridden method is resolved at
runtime rather than at compile
time.
t
}
class Dog extends Animal {
void sound() {
[Link]("Dog Barks");
t
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
[Link]();
}
tQ. What is the final keyword in Java?
Ans:- The final keyword in Java is used to restrict modification. It can be applied to variables,
methods, and classes.
+ Final variable cannot be changed once assigned
«__Final method cannot be overridden
«Final class cannot be inherited
Q. Define superclass and subclass in Java.
Ans:- A Superclass (also called a Parent Class or Base Class) is the class whose properties
and methods are inherited by another class.
Example
class Animal {
void eat() {
[Link]("Animal Eats Food");
}
}
A Subclass (also called a Child Class or Derived Class) is the class that inherits the properties
and methods of another class using the extends keyword.
Example
class Dog extends Animal {
void bark() {
[Link]("Dog Barks");
}
}
Here, Dog is the Subclass because it inherits from Animal.
Q. Explain different access specifiers in Java.
Ans:- Access Specifiers (Access Modifiers) in Java are keywords used to control the
accessibility of classes, variables, methods, and constructors.
Java provides four types of access specifiers:
1, Private (private):- Accessible only within the same class.
2. Default (No Modifier):- Accessible only within the same package.
3. Protected (protected): Accessible within the same package.
4, Public (public):~ Accessible from anywhere in the program.Q. What is garbage collection?
Ans:- Garbage Collection is the process of automatically removing unused objects from
memory to free up space. It is performed by the Garbage Collector, which is a part of the
Java Virtual Machine (JVM).
Q. What is inheritance in Java?
Ans:- Inheritance is an Object-Oriented Programming (OOP) feature that allows one class to
acquire the properties and methods of another class.
Example
class Animal {
void eat() {
[Link]("Animal Eats Food");
}
}
class Dog extends Animal {
void bark() {
[Link]("Dog Barks");
}
}
public class Test {
public static void main(String] args) {
Dog d = new Dog();
[Link](); // Inherited method
[Link]();
}
}
Output
Animal Eats Food
Dog Barks
Q. Define static keyword in Java.
Ans:- The static keyword in Java is used for memory management and belongs to the class
rather than any specific instance.
Uses of static Keyword
1. To create class-level variables.
2. To create methods that can be called without objects.
3. To share common data among all objects.
4. To save memory.Q. Explain encapsulation with example.
Ans:- Encapsulation is the process of wrapping data (variables) and methods (functions) into
a single unit called a class. It also restricts direct access to data and provides controlled
access through methods.
Example Program
class Student {
private int marks; // private data member
public void setMarks(int marks) {
[Link] = marks;
}
public int getMarks() {
return marks;
}
public class Test {
public static void main(String[] args) {
Student s = new Student();
[Link](90);
[Link]("Marks =" + [Link]());
}
}
Output
Marks = 90
Q. What is a class and object in Java?
Ans:- A Class is a blueprint or template used to create objects. It contains variables and
methods that define the properties and behavior of objects.
An Object is an instance of a class. It is used to access the variables and methods of a class.
class Student { publicclassTest{
String name = "Anuj"; public static void main(String|] args) {
void display() { Student s = new Student();
[Link]("Name: " + name); [Link]();
} }
} }