Unit 2
2 (a) What are keywords and list out. (6 Marks)
(b) Briefly explain final keyword. (4 Marks)
✅ Answer (2a): What are keywords and list out. (6 Marks)
Definition:
In Java, keywords are reserved words that have predefined meanings and purposes in the
Java compiler. They cannot be used as variable names, identifiers, or method names because
they are part of the Java syntax.
Explanation:
● Java keywords define the structure and control flow of a Java program.
● They help the compiler understand the type of operation or declaration.
● Java has around 50 reserved keywords.
Common Java Keywords:
Category Keywords
Data Types int, float, double, char, boolean, byte, long, short
Control if, else, switch, case, default, break, continue, for, while,
Statements do
Access Modifiers public, private, protected
Class Related class, extends, implements, interface, abstract, final,
static, super, this
Exception try, catch, throw, throws, finally
Handling
Object & Memory new, return, void, instanceof
Others package, import, synchronized, volatile, transient, const,
goto (reserved but not used)
Example:
public class Example {
int a = 10; // 'int' and 'class' are keywords
}
Note: Keywords are case-sensitive and must be written in lowercase.
✅ Answer (2b): Briefly explain final keyword. (4 Marks)
Definition:
The final keyword in Java is a non-access modifier used to restrict the user. It can be
applied to variables, methods, and classes.
Usage:
Final Variable:
Once a variable is declared as final, its value cannot be changed (constant).
final int MAX = 100;
1.
Final Method:
A final method cannot be overridden by subclasses.
class Parent {
final void display() {
[Link]("This is a final method");
}
}
2.
Final Class:
A final class cannot be inherited.
final class Vehicle {}
3.
Key Point:
● The final keyword ensures security, consistency, and immutability in programs.
✅ Q3. Explain about Final Class and Methods with
Example (10 Marks)
1. Introduction
In Java, the final keyword is used as a non-access modifier to apply restrictions on classes,
methods, and variables.
When final is applied to a class or method, it prevents inheritance and method overriding,
ensuring program stability and security.
2. Final Class
A final class cannot be extended (inherited) by any other class.
It is mainly used when the class’s functionality should remain unchanged or secured from
modification.
Syntax:
final class ClassName {
// class body
}
Example:
final class Vehicle {
void display() {
[Link]("This is a vehicle.");
}
}
class Car extends Vehicle { // ❌ Error – cannot inherit final class
void show() {
[Link]("This is a car.");
}
}
Explanation:
● The class Vehicle is declared as final.
● Hence, no other class can extend Vehicle.
● If attempted, the compiler shows an error:
“Cannot inherit from final class Vehicle.”
Use Case:
Used when you want to secure core functionality that should not be changed — for example,
in utility or security classes ([Link] is a final class).
3. Final Method
A final method cannot be overridden by subclasses.
This ensures that the parent class’s implementation remains the same in all child classes.
Syntax:
class ClassName {
final void methodName() {
// method body
}
}
Example:
class Parent {
final void display() {
[Link]("This is a final method in Parent class.");
}
}
class Child extends Parent {
void display() { // ❌ Error – cannot override final method
[Link]("Trying to override.");
}
}
Explanation:
● The display() method is declared as final in the Parent class.
● The Child class cannot override it.
4. Advantages of Using final
● Prevents accidental overriding of critical methods.
● Maintains security and consistency in large applications.
● Improves performance — final methods are faster since they are not overridden.
5. Real-Life Example
In Java, many classes such as [Link] and [Link] are final, so they
cannot be extended to prevent misuse.
6. Conclusion
● final class → prevents inheritance.
● final method → prevents overriding.
● Both ensure code reliability, safety, and maintainability.
✅ Q4. Discuss about Overloaded Constructor Methods
with Example (10 Marks)
1. Introduction
In Java, constructor overloading means defining more than one constructor in the same
class with different parameter lists.
It allows an object to be created in multiple ways based on the number or type of arguments
passed.
2. Definition
Constructor Overloading is a feature in Java that allows a class to have more
than one constructor, each having a different list of parameters (different data types
or different number of arguments).
3. Purpose of Constructor Overloading
● To initialize objects in different ways.
● To provide flexibility when creating objects.
● To reuse code instead of writing multiple initialization methods.
4. Syntax
class ClassName {
ClassName() {
// no-argument constructor
}
ClassName(int a) {
// parameterized constructor
}
ClassName(int a, int b) {
// another parameterized constructor
}
}
5. Example Program
class Student {
int id;
String name;
String course;
// Constructor 1 - No arguments
Student() {
id = 0;
name = "Unknown";
course = "Not Assigned";
}
// Constructor 2 - One argument
Student(int i) {
id = i;
name = "Unnamed";
course = "Not Assigned";
}
// Constructor 3 - Two arguments
Student(int i, String n) {
id = i;
name = n;
course = "CSE";
}
void display() {
[Link]("ID: " + id + " Name: " + name + " Course:
" + course);
}
public static void main(String args[]) {
Student s1 = new Student();
Student s2 = new Student(101);
Student s3 = new Student(102, "Ram");
[Link]();
[Link]();
[Link]();
}
}
6. Output
ID: 0 Name: Unknown Course: Not Assigned
ID: 101 Name: Unnamed Course: Not Assigned
ID: 102 Name: Ram Course: CSE
7. Explanation
● In the above example, three constructors are defined in the Student class.
● Based on the arguments passed, Java automatically selects the correct constructor
at runtime.
● This feature is called Constructor Overloading.
● The compiler differentiates constructors by their parameter list (number and type).
8. Key Points
● Constructors must have different parameter lists.
● Return type is never specified for constructors.
● The compiler determines which constructor to invoke based on arguments.
● Helps in creating flexible object initialization.
9. Advantages of Constructor Overloading
● Improves readability and reusability of code.
● Enables multiple ways to initialize an object.
● Reduces the need for writing multiple initialization methods.
10. Conclusion
Constructor overloading provides flexibility in object creation and enhances code efficiency.
It is an important concept of Object-Oriented Programming that supports polymorphism.
✅ Q5. Develop a Java Program to Find Factorial of a
Given Number (10 Marks)
1. Definition
The factorial of a number is the product of all positive integers less than or equal to that
number.
It is denoted by n!
n!=n×(n−1)×(n−2)×...×1n! = n × (n - 1) × (n - 2) × ... × 1n!=n×(n−1)×(n−2)×...×1
Example:
5! = 5 × 4 × 3 × 2 × 1 = 120
2. Explanation
There are two common ways to find factorial in Java:
1. Using iteration (loops)
2. Using recursion
We’ll use both methods here.
3. Java Program Using Loop
import [Link];
public class FactorialUsingLoop {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int n = [Link]();
int fact = 1;
for (int i = 1; i <= n; i++) {
fact = fact * i; // multiplying numbers from 1 to n
}
[Link]("Factorial of " + n + " is: " + fact);
[Link]();
}
}
4. Output
Enter a number: 5
Factorial of 5 is: 120
5. Explanation of Code
Line Description
Scanner sc = new Takes user input
Scanner([Link]);
int fact = 1; Initializes factorial value
for (int i = 1; i <= n; i++) Loop runs from 1 to n
fact = fact * i; Multiplies each number in
sequence
[Link](...) Displays final result
6. Java Program Using Recursion
import [Link];
public class FactorialUsingRecursion {
static int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1); // recursive call
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int n = [Link]();
int result = factorial(n);
[Link]("Factorial of " + n + " is: " + result);
[Link]();
}
}
7. Output
Enter a number: 6
Factorial of 6 is: 720
8. Explanation
● The recursive method calls itself repeatedly until the base condition (n == 0 or n
== 1) is met.
● Each recursive call multiplies the current number with the factorial of (n-1).
9. Advantages
● Simple logic and easy to understand.
● Demonstrates both loop and recursion concepts.
● Useful in solving mathematical problems and algorithms.
10. Conclusion
The factorial program demonstrates iteration and recursion in Java.
It is a basic but powerful example to understand control flow, methods, and mathematical
operations in programming.
✅ Q6(a): Discuss about Call by Value and Call by
Reference with Example (5 Marks)
1. Introduction
In Java, when we pass arguments to a method, it can be done in two ways:
1. Call by Value
2. Call by Reference
However, Java always uses “call by value” — but when objects are passed, the reference
(address) of the object is copied, giving the effect of “call by reference”.
2. Call by Value
Definition:
A copy of the variable’s value is passed to the method.
Changes made inside the method do not affect the original value.
Example:
class CallByValueExample {
void change(int a) {
a = a + 10;
}
public static void main(String[] args) {
int x = 5;
CallByValueExample obj = new CallByValueExample();
[Link](x);
[Link]("Value of x after call: " + x);
}
}
Output:
Value of x after call: 5
Explanation:
● The value of x (5) is copied into the method parameter a.
● Modifying a doesn’t change x.
3. Call by Reference
Definition:
The reference (memory address) of an object is passed to the method.
Changes made inside the method affect the original object.
Example:
class CallByReferenceExample {
int value = 10;
void change(CallByReferenceExample obj) {
[Link] = [Link] + 5;
}
public static void main(String[] args) {
CallByReferenceExample ob = new CallByReferenceExample();
[Link]("Before change: " + [Link]);
[Link](ob);
[Link]("After change: " + [Link]);
}
}
Output:
Before change: 10
After change: 15
Explanation:
● The object reference ob is passed to the method.
● Since both refer to the same memory location, the change affects the original value.
4. Conclusion
Type What is Effect on Original Value
Passed
Call by Value Copy of data No change
Call by Address of data Changes reflect
Reference
✅ Q6(b): Write a Java Program Using Recursion Method
(5 Marks)
1. Definition
Recursion is the process in which a method calls itself directly or indirectly.
It is used to solve problems that can be divided into smaller sub-problems.
2. Example Program – Find Factorial Using Recursion
import [Link];
public class RecursionExample {
static int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1); // recursive call
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
[Link]("Factorial of " + num + " is: " +
factorial(num));
[Link]();
}
}
3. Output
Enter a number: 5
Factorial of 5 is: 120
4. Explanation
● The method factorial() calls itself recursively with a smaller value (n-1) each time.
● The recursion stops when n == 0 or n == 1.
● This demonstrates method recursion in Java.
5. Conclusion
Recursion is a powerful programming technique used in mathematical computations,
searching, and sorting algorithms.
It helps to make code simpler and logical.
✅ Q7. Explain about Method and Nested Methods with
Example (10 Marks)
1. Introduction
In Java, a method is a block of code that performs a specific task, and it runs only when called.
Methods are used to improve code reusability, readability, and modularity.
A nested method refers to calling one method inside another method.
2. What is a Method?
Definition:
A method is a collection of statements that are grouped together to perform an operation.
3. Syntax of a Method
returnType methodName(parameter list) {
// body of the method
// statements
return value;
}
Example:
int add(int a, int b) {
return a + b;
}
4. Types of Methods in Java
Type Description Example
Predefined (Built-in) Already defined in Java libraries [Link](),
[Link]()
User-defined Created by the programmer sum(), display()
5. Example Program for Methods
public class MethodExample {
// User-defined method
int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
MethodExample obj = new MethodExample();
int result = [Link](10, 20);
[Link]("Sum: " + result);
}
}
Output:
Sum: 30
6. What are Nested Methods?
Definition:
Nested methods mean one method calling another method inside the same class.
Java does not support method definitions inside another method,
but one method can call another — this is referred to as method nesting.
7. Example Program for Nested Methods
public class NestedMethodExample {
void displaySquare(int num) {
int sq = square(num); // calling another method
[Link]("Square of " + num + " is: " + sq);
}
int square(int n) {
return n * n;
}
public static void main(String[] args) {
NestedMethodExample obj = new NestedMethodExample();
[Link](6); // method calling another method
}
}
8. Output
Square of 6 is: 36
9. Explanation
● The method displaySquare() calls another method square() inside it.
● This is called a nested method call.
● Helps to reuse code, keep the program clean, and reduce redundancy.
10. Advantages of Using Methods
1. Reusability: You can call the same method multiple times.
2. Code Organization: Programs become more readable.
3. Debugging: Easier to test small parts of code.
4. Maintenance: Reduces duplication of code.
11. Conclusion
● A method is a reusable block of code that performs a task.
● Nested methods (calling one method inside another) help to make programs modular
and easier to manage.
● Methods form the core structure of object-oriented programming in Java.
✅ Q8. Discuss About Constructor with Suitable
Examples (10 Marks)
1. Introduction
In Java, a constructor is a special method used to initialize objects.
It is automatically called when an object of a class is created.
2. Definition
A constructor is a block of code that has the same name as the class and is used
to initialize the object’s data members.
3. Features of a Constructor
● Has the same name as the class.
● Does not have a return type (not even void).
● Called automatically when an object is created.
● Can be overloaded (multiple constructors in the same class).
4. Syntax
class ClassName {
ClassName() {
// constructor body
}
}
5. Types of Constructors
Type Description
1. Default Constructor Provided automatically by Java if no constructor is defined.
Initializes variables with default values.
2. No-Argument User-defined constructor without parameters.
Constructor
3. Parameterized Constructor that takes arguments to initialize fields with
Constructor specific values.
4. Copy Constructor (not Implemented by passing an object as a parameter to another
built-in) constructor.
6. Example 1 – No-Argument Constructor
class Student {
int id;
String name;
// No-argument constructor
Student() {
id = 101;
name = "Ram";
}
void display() {
[Link]("ID: " + id + ", Name: " + name);
}
public static void main(String[] args) {
Student s1 = new Student(); // constructor called
automatically
[Link]();
}
}
Output:
ID: 101, Name: Ram
7. Example 2 – Parameterized Constructor
class Employee {
int empId;
String empName;
// Parameterized constructor
Employee(int id, String name) {
empId = id;
empName = name;
}
void display() {
[Link]("Employee ID: " + empId + ", Name: " +
empName);
}
public static void main(String[] args) {
Employee e1 = new Employee(201, "Arun");
Employee e2 = new Employee(202, "Kumar");
[Link]();
[Link]();
}
}
Output:
Employee ID: 201, Name: Arun
Employee ID: 202, Name: Kumar
8. Example 3 – Copy Constructor (User-defined)
class Person {
String name;
int age;
// Parameterized constructor
Person(String n, int a) {
name = n;
age = a;
}
// Copy constructor
Person(Person p) {
name = [Link];
age = [Link];
}
void display() {
[Link]("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Person p1 = new Person("Ravi", 20);
Person p2 = new Person(p1); // calling copy constructor
[Link]();
[Link]();
}
}
Output:
Name: Ravi, Age: 20
Name: Ravi, Age: 20
9. Importance of Constructors
● Used for initializing objects automatically.
● Makes code simpler and cleaner.
● Helps to assign default or custom values to object variables.
● Supports overloading for flexible object creation.
10. Conclusion
Constructors are essential in object-oriented programming as they:
● Ensure objects start in a valid state,
● Allow automatic initialization,
● and enhance readability and reliability of programs.
✅ Q9. Demonstrate a Java Program Using final and
static (10 Marks)
1. Introduction
In Java, final and static are non-access modifiers used to control behavior of variables,
methods, and classes.
Both are powerful keywords that improve memory management, code security, and
performance.
2. final Keyword
Definition:
The final keyword is used to restrict modification.
It can be applied to variables, methods, and classes.
Usage Description
final variable Value cannot be changed
(constant).
final method Cannot be overridden by a
subclass.
final class Cannot be inherited.
Example of final:
final class University {
final int TOTAL_STUDENTS = 1000; // final variable
final void showInfo() { // final method
[Link]("Total Students: " + TOTAL_STUDENTS);
}
}
class Department extends University { // ❌ Error: cannot inherit
final class
// void showInfo() {} // ❌ Error: cannot override
final method
}
public class FinalExample {
public static void main(String[] args) {
University u = new University();
[Link]();
}
}
Output:
Total Students: 1000
3. Explanation of final
● The variable TOTAL_STUDENTS cannot be changed.
● The method showInfo() cannot be overridden.
● The class University cannot be inherited.
This provides safety and consistency to important program elements.
4. static Keyword
Definition:
The static keyword is used for class-level members that are shared among all objects.
A static member belongs to the class, not to any specific object.
Usage Description
static Shared by all objects of the class.
variable
static method Can be called without creating an
object.
static block Runs once when the class is loaded.
Example of static:
class College {
static String collegeName = "NIT"; // static variable
int rollNo;
String name;
College(int r, String n) {
rollNo = r;
name = n;
}
static void changeCollege() { // static method
collegeName = "IIT";
}
void display() {
[Link](rollNo + " " + name + " " + collegeName);
}
public static void main(String[] args) {
[Link](); // calling static method directly
College s1 = new College(101, "Ram");
College s2 = new College(102, "Sai");
[Link]();
[Link]();
}
}
Output:
101 Ram IIT
102 Sai IIT
5. Explanation of static
● collegeName is a static variable shared by all objects.
● changeCollege() is a static method, called without an object.
● Changes in static members affect all objects of the class.
6. Difference Between final and static
Basis final static
Purpose Restricts modification Shares data among all
objects
Variable Value cannot change Common to all objects
Method Cannot override Can be called without object
Class Cannot be inherited Shared at class level
Memory Object level Class level
7. Importance
● final ensures immutability and security.
● static ensures memory efficiency and reusability.
8. Conclusion
The final and static keywords are essential for optimized and secure programming.
They help developers control data access, object behavior, and memory usage effectively.
✅ Q10. Explain About Overloading and Overriding with
Example (10 Marks)
1. Introduction
In Java, both overloading and overriding are examples of polymorphism — a core concept of
Object-Oriented Programming (OOP).
They allow a method to behave differently based on context:
● Overloading → Compile-time polymorphism
● Overriding → Run-time polymorphism
2. What is Method Overloading?
Definition:
Method overloading occurs when two or more methods in the same class have the same
name but different parameter lists (different number or type of arguments).
It is an example of compile-time polymorphism.
3. Example – Method Overloading
class MathOperation {
// Method 1: add two integers
int add(int a, int b) {
return a + b;
}
// Method 2: add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Method 3: add two doubles
double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
MathOperation obj = new MathOperation();
[Link]("Sum of 2 int: " + [Link](5, 10));
[Link]("Sum of 3 int: " + [Link](5, 10, 15));
[Link]("Sum of 2 double: " + [Link](2.5, 3.5));
}
}
Output:
Sum of 2 int: 15
Sum of 3 int: 30
Sum of 2 double: 6.0
Explanation:
● The compiler decides which add() method to call based on argument type and
number.
● Hence, this is compile-time polymorphism.
4. What is Method Overriding?
Definition:
Method overriding occurs when a subclass provides a specific implementation of a method
that is already defined in its superclass.
It is an example of run-time polymorphism.
5. Rules for Method Overriding
● The method in child class must have same name, return type, and parameters.
● There must be inheritance (using extends).
● The access level cannot be more restrictive than the parent method.
● @Override annotation is used (optional but recommended).
6. Example – Method Overriding
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
public static void main(String[] args) {
Animal obj = new Dog(); // upcasting
[Link](); // calls the overridden method
}
}
Output:
Dog barks
Explanation:
● The parent class Animal has a sound() method.
● The child class Dog overrides it with a specific implementation.
● At runtime, the JVM decides which method to call — this is dynamic method dispatch.
7. Difference Between Overloading and Overriding
Feature Method Overloading Method Overriding
Definition Same method name, Same method name and parameters,
different parameters different implementation
Type of Compile-time Run-time
Polymorphism
Class Relation Within the same class Between superclass and subclass
Return Type Can be same or different Must be same
Access Modifier No restriction Cannot reduce visibility
Keyword Used None @Override (optional)
Decided By Compiler JVM (at runtime)
8. Importance
● Overloading: Increases flexibility by allowing multiple ways to call the same method.
● Overriding: Enables runtime polymorphism and custom behavior in subclasses.
9. Real-life Analogy
● Overloading: A person can “speak” in English or Tamil — same action, different
parameters.
● Overriding: A child redefines how to “speak” differently from the parent.
10. Conclusion
Both overloading and overriding improve code reusability and flexibility in Java.
● Overloading → same method, different inputs (compile-time).
● Overriding → same method, different behavior (run-time).
These are fundamental for implementing Object-Oriented Programming (OOP) concepts like
polymorphism and inheritance.