ASSIGNMENT-1
JAVA
1) Why is Java referred to as a platform independent language?
Ans Java is referred to as a platform independent language because programs written in Java
can run on any operating system or hardware platform without modification. This is possible
due to the use of the Java Virtual Machine (JVM).
When a Java program is written, it is compiled by the Java compiler into an intermediate
code called bytecode, not into machine-specific code. This bytecode is not dependent on
any particular operating system. Instead, it is executed by the Java Virtual Machine (JVM).
Each operating system (such as Windows, Linux, macOS) has its own JVM implementation.
The JVM converts the bytecode into machine code suitable for that specific system at
runtime. Therefore, the same compiled Java program (.class file) can run on any system that
has a JVM installed.
This concept is popularly known as:
“Write Once, Run Anywhere (WORA)”
Thus, Java achieves platform independence by:
• Compiling source code into bytecode.
• Using JVM to execute bytecode on different platforms.
• Avoiding direct dependency on system-specific architecture.
Hence, Java is called a platform independent language because it does not require
recompilation for different operating systems.
2) What is bytecode? Explain any two tools available in jdk?
Ans Bytecode is the intermediate code generated when a Java program is compiled.
When a Java source file (.java) is compiled using the Java compiler, it is not converted
directly into machine-level code. Instead, it is converted into bytecode, which is stored in a
.class file.
Bytecode is a platform-independent code that can be executed on any system having the
Java Virtual Machine (JVM). The JVM interprets or converts this bytecode into machine-
specific instructions at runtime.
Features of Bytecode:
• It is platform independent.
• It ensures security (runs inside JVM).
• It makes Java portable.
• It enables the concept of Write Once, Run Anywhere (WORA).
Thus, bytecode acts as a bridge between Java source code and machine code.
The Java Development Kit (JDK) provides various tools used for developing, compiling,
debugging, and documenting Java programs. Two important tools are:
(i) javac (Java Compiler)
• javac is the compiler tool in JDK.
• It converts Java source code (.java file) into bytecode (.class file).
• It checks for syntax errors during compilation.
Example:
javac [Link]
This command generates [Link].
(ii) java (Java Interpreter)
• java is used to run the compiled Java program.
• It executes the bytecode using the JVM.
• It converts bytecode into machine code at runtime.
Example:
java MyProgram
This command runs the program.
3) In what ways does a switch statement differ from an if statement?
Ans
4) What is the use of the new operator? Is it necessary to be used whenever an object of the
class is created? Why?
Ans The new operator in Java is used to create objects (instances) of a class. It performs the
following functions:
• Allocates memory for the object in the heap area.
• Invokes the constructor of the class to initialize the object.
• Returns a reference to the created object.
Example:
Student s = new Student();
Here:
• new Student() creates the object.
• Memory is allocated.
• The constructor of Student is called.
• s stores the reference of the object
Is it necessary to use new whenever an object of a class is created? Why?
Yes, in most cases, the new operator is necessary when creating an object because:
• Objects require memory allocation in the heap.
• Without new, no memory is allocated for instance variables.
• The constructor will not be executed.
• Only a reference variable will be declared, not an actual object.
Example without new:
Student s;
Here, s is only a reference variable.
No object is created, and using it will cause a runtime error (NullPointerException).
Exception (Special Case)
It is not required to use new:
• When accessing static members, because static members belong to the class, not to
objects.
• When objects are created using certain factory methods (e.g., [Link]()),
internally new may be used but not directly by the programmer.
5) Explain the need for object oriented programming paradigm and also write advantages of
OOPS.
Ans The Object-Oriented Programming (OOP) paradigm was introduced to overcome the
limitations of procedural programming. In procedural programming, the focus is mainly on
functions and procedures, and data is often exposed globally, which makes large programs
difficult to manage.
As software systems became larger and more complex, there was a need for:
• Better program organization – Managing large code in a structured way.
• Data security – Protecting data from unauthorized access.
• Code reusability – Avoiding repetition of code.
• Real-world modeling – Representing real-world entities in programs.
• Ease of maintenance – Modifying and updating programs easily.
OOP solves these problems by organizing programs around objects rather than functions. An
object contains both data (attributes) and methods (functions) that operate on the data.
Languages like Java implement OOP using core concepts such as:
• Encapsulation
• Inheritance
• Polymorphism
• Abstraction
Thus, OOP provides a more secure, modular, and real-world approach to software
development.
Advantages of OOPS
Encapsulation (Data Hiding)
Data is hidden inside a class and accessed only through methods, improving security.
Inheritance (Code Reusability)
One class can inherit properties of another class, reducing code duplication.
Polymorphism (Flexibility)
A single interface can represent multiple forms, making programs more flexible and
extensible.
Abstraction (Complexity Reduction)
Only essential features are shown to the user, hiding implementation details.
Modularity
Programs are divided into small classes, making debugging and maintenance easier.
Easy Maintenance
Changes in one part of the program do not affect other parts significantly.
Real-World Mapping
OOP allows modeling real-world entities like Student, Employee, Bank Account, etc.
6) List and explain the lexical issues of java.
Ans In Java, lexical issues refer to the rules that define how a sequence of characters in a
Java program is divided into meaningful components called tokens during the lexical analysis
phase of compilation.
Lexical structure specifies the basic elements (words and symbols) that form a valid Java
program.
The main lexical issues in Java are explained below:
1) Character Set
Java uses the Unicode character set, which supports characters from different languages
across the world.
It includes:
• Letters (A–Z, a–z)
• Digits (0–9)
• Special symbols (+, –, *, /, etc.)
• Whitespace characters (space, tab, newline)
2) Tokens
Tokens are the smallest individual units in a Java program. The Java compiler breaks the
source code into tokens during lexical analysis.
Types of tokens:
a) Keywords
• Reserved words that have predefined meaning in Java.
• Examples: int, class, public, static, if, while, return.
b) Identifiers
Names given to variables, methods, classes, etc.
Example: studentName, totalMarks
c) Literals
Constant values used in a program.
Examples:
Integer literals → 10
Floating literals → 3.14
d) Operators
Symbols used to perform operations.
Examples: +, -, *, /, ==, &&
3) Comments
Comments are non-executable statements used for documentation.
Types:
Single-line → // comment
Multi-line → /* comment */
4) White Spaces
• White spaces include spaces, tabs, and newlines.
• They are used to separate tokens and improve readability.
• Java ignores extra whitespace.
7) Differentiate between JDK, JRE and JVM.
Ans
8) Describe about type conversion. Also explain how casting is used to perform type
conversion between incompatible types.
Ans In Java, type conversion refers to the process of converting a value from one data type
to another data type.
It is required when different data types are used in an expression or assignment.
Java supports two types of type conversion:
• Implicit Type Conversion (Widening)
• Explicit Type Conversion (Narrowing / Casting)
1) Implicit Type Conversion (Widening)
• Done automatically by the compiler.
• Converts a smaller data type into a larger data type.
• No data loss occurs.
Order of Widening:
byte → short → int → long → float → double
Example:
int a = 10;
double b = a; // int automatically converted to double
Here, int is converted into double automatically.
2) Explicit Type Conversion (Casting / Narrowing)
• Done manually by the programmer.
• Converts a larger data type into a smaller data type.
• May cause data loss.
• Requires casting operator (type).
Example:
• double x = 10.75;
• int y = (int) x; // Explicit casting
Here:
• double is converted into int.
• Decimal part (.75) is lost.
• (int) is called casting operator.
Type Casting Between Incompatible Types
When two data types are not automatically compatible, Java requires explicit casting.
Syntax:
datatype variable = (datatype) value;
Example 1: Primitive Type Casting
int a = 130;
byte b = (byte) a;
Since byte has a smaller range than int, explicit casting is required.
Example 2: Object Type Casting (Reference Casting)
In case of classes, casting is used in inheritance:
class Animal { }
class Dog extends Animal { }
Animal obj = new Dog(); // Upcasting (implicit)
Dog d = (Dog) obj; // Downcasting (explicit)
• Upcasting → Automatic (child to parent)
• Downcasting → Requires explicit casting
9) Explain the properties of Java language.
Ans Properties of Java Language
Java has several important properties that make it popular and widely used.
1) Simple:
Java is simple because it has a clear and easy syntax similar to C and C++. It eliminates
complex features such as pointers, operator overloading, and multiple inheritance through
classes. Automatic garbage collection also simplifies memory management.
2) Object-Oriented:
Java is a purely object-oriented language. It is based on core concepts such as encapsulation,
inheritance, polymorphism, and abstraction. Programs are designed using classes and
objects, which helps in modular and reusable code development.
3) Platform Independent:
Java is platform independent because it compiles source code into bytecode, which runs on
the Java Virtual Machine (JVM). Therefore, Java programs can run on any system that
supports JVM without modification.
4) Portable:
Java ensures portability by maintaining fixed sizes for primitive data types and by generating
machine-independent bytecode. This allows Java programs to be transferred from one
platform to another easily.
5) Secure:
Java provides a secure execution environment. It does not use pointers, includes bytecode
verification, and provides runtime security checks. These features help in protecting systems
from unauthorized access.
6) Robust:
Java is robust because it has strong memory management, automatic garbage collection,
and an effective exception handling mechanism. It performs compile-time and runtime error
checking to ensure reliability.
7) Multithreaded:
Java supports multithreading, which allows multiple tasks to run simultaneously within a
single program. This improves CPU utilization and performance.
10) Explain the scope and lifetime of variables with examples.
Ans In Java, every variable has two important properties:
• Scope → The region of the program where the variable can be accessed.
• Lifetime → The duration for which the variable exists in memory.
1) Scope of Variables
Scope refers to the part of the program where a variable is visible and can be used.
In Java, variables are mainly of three types based on scope:
(a) Local Variables
Scope:
Declared inside a method, constructor, or block. They can be accessed only within that
method or block.
Example:
void display() {
int x = 10; // Local variable
[Link](x);
}
Here, x cannot be accessed outside the display() method.
(b) Instance Variables
Scope:
Declared inside a class but outside any method. They can be accessed by all methods of the
class through an object.
Example:
class Student {
int marks; // Instance variable
}
marks can be accessed using the object of Student.
(c) Static Variables (Class Variables)
Scope:
Declared using the static keyword inside a class. They are shared among all objects of the
class.
Example:
class Student {
static String college = "ABC College";
}
college can be accessed using the class name.
2) Lifetime of Variables
Lifetime refers to the time during which a variable occupies memory.
(a) Local Variable Lifetime
• Created when the method is called.
• Destroyed when the method execution ends.
Thus, lifetime is limited to method execution.
(b) Instance Variable Lifetime
• Created when an object of the class is created using new.
• Destroyed when the object is destroyed (by garbage collection).
Thus, lifetime depends on object existence.
(c) Static Variable Lifetime
• Created when the class is loaded into memory.
• Exists until the program ends or class is unloaded.
Thus, lifetime is throughout the execution of the program.
11) Define an array. What are different types of arrays? List out the advantages of using
arrays.
Ans An array is a collection of elements of the same data type stored in contiguous memory
locations under a single variable name. Each element in an array is accessed using an index,
which usually starts from 0.
In simple words, an array allows us to store multiple values of the same type in one variable
instead of declaring separate variables for each value.
Example (Java):
Types of Arrays
Arrays can be classified based on their dimensions:
1. One-Dimensional Array (1D Array)
• Stores elements in a single row.
• Accessed using a single index.
Example:
int arr[] = new int[5];
2. Two-Dimensional Array (2D Array)
• Stores elements in tabular form (rows and columns).
• Accessed using two indices.
Example:
int matrix[][] = new int[3][3];
3. Multidimensional Array
• Array with more than two dimensions.
Example:
int arr[][][] = new int[2][3][4];
Advantages of Using Arrays
Stores Multiple Values Efficiently
Arrays allow storing multiple values of the same type using a single variable name.
Easy Access to Elements
Elements can be accessed directly using index numbers, which makes retrieval fast (constant
time access).
Better Memory Utilization
Since elements are stored in contiguous memory locations, memory is used efficiently.
Simplifies Code
Reduces the need for multiple variable declarations and makes the program more organized.
Supports Iteration
Arrays can be easily processed using loops like for, while, etc.
Useful for Implementing Other Data Structures
Arrays are used to implement structures like stacks, queues, matrices, and lists.
12) Describe the structure of a typical Java program with an example.
Ans A typical Java program follows a well-defined structure. It consists of different
components such as package declaration, import statements, class definition, variables,
methods, and the main() method.
• Package: Groups related classes and interfaces, helping organize code and prevent
naming conflicts.
• Class: Defines variables and methods, serving as a blueprint for creating objects in
Java.
• Method: A block of code that performs a specific task; the main() method acts as the
program’s entry point.
• Variable: A named memory location used to store and manipulate data during
program execution.
• Statement: An instruction that performs an action, such as computation or displaying
output.
Explanation of the Example
• The program belongs to the package [Link].
• GFG is the name of the class.
• The main() method is the entry point of the program.
• num1 and num2 are local variables declared inside the main() method.
• total is another local variable used to store the calculated result.
• [Link]() is used to display output on the screen.
• The statements inside the main() method are executed sequentially.
• Execution of the program starts from the main() method and ends when it finishes
execution.
13) A class Vehicle has fields: speed and fuelCapacity. A class ElectricCar extends Vehicle.
a) Why might inheritance be a poor design choice in this case?
b) Propose an alternative design using Java classes and explain:
• How it avoids misuse of inherited members,
• How it improves flexibility and correctness.
Ans
(a) Why might inheritance be a poor design choice?
If ElectricCar extends Vehicle, it automatically inherits all fields and behaviors of Vehicle,
including fuelCapacity.
However:
• An ElectricCar does not use fuel; it uses a battery.
• Inheriting fuelCapacity is logically incorrect.
• It violates the “is-a” relationship principle properly.
• It may lead to misuse, such as setting fuel capacity for an electric car.
• This breaks the Liskov Substitution Principle (LSP) because an ElectricCar cannot fully
behave like a normal fuel-based vehicle.
Thus, inheritance here creates incorrect modeling of real-world relationships and may
reduce correctness of the program.
(b) Alternative Design Using Java Classes
Instead of inheritance, we can use composition.
Proposed Design Using Composition
Explanation
How it avoids misuse of inherited members:
• ElectricCar does not inherit fuelCapacity.
• It only contains a Battery object.
• No unnecessary or incorrect properties are inherited.
• Prevents assigning fuel-related data to an electric car.
How it improves flexibility and correctness:
• Follows composition over inheritance principle.
• Each class has only relevant properties.
• Easy to extend (e.g., HybridCar can contain both Engine and Battery).
• Better real-world modeling.
• Improves maintainability and scalability.
• Ensures correctness of data and behavior.
14) You are designing a University Management System. A superclass Person has a
parameterized constructor. A subclass Professor adds employeeId and department.
a) Explain why the code fails to compile if super() is not explicitly called in Professor.
b) Design the correct constructor chain and justify the execution order.
Ans
(a) Why does the code fail if super() is not explicitly called?
In Java, when a subclass constructor is executed, it must call the constructor of its
superclass. If we do not explicitly call super(), the compiler automatically inserts a default
call to super() (no-argument constructor).
If the superclass Person contains only a parameterized constructor and does not have a
default constructor, then the compiler cannot find Person(). As a result, a compilation error
occurs:
Reason:
The superclass constructor must be invoked to initialize inherited data members. If no
matching constructor is available, the program fails to compile.
Thus, super() must be explicitly called with appropriate parameters.
(b) Correct Constructor Chain with Justification
Superclass: Person
Subclass: Professor
Justification of Execution Order
• When an object of Professor is created:
• The Professor constructor is called.
• The first statement super(name, age) invokes the Person constructor.
• The superclass (Person) initializes name and age.
• Control returns to the Professor constructor.
• employeeId and department are initialized.
Execution Order:
Superclass constructor → Subclass constructor.
This ensures that inherited properties are initialized before subclass-specific properties,
maintaining proper object construction.
15) You are building a Payment Gateway that supports:
• Credit Card
• UPI
• Net Banking
Each payment method needs:
• Validation logic
• Common transaction logging
Should you use an abstract class or an interface? Justify your answer with respect to:
a) Code reuse
b) Multiple inheritance
c) Future extensibility
Ans The system supports multiple payment methods such as Credit Card, UPI, and Net
Banking. Each payment method requires:
• Validation logic
• Common transaction logging
Choice: Abstract Class
An abstract class is more suitable in this case.
Justification
(a) Code Reuse
• An abstract class can contain both abstract methods and concrete methods.
• Common functionality like transaction logging can be implemented once in the
abstract class.
• All subclasses (CreditCard, UPI, NetBanking) can reuse this common code.
• This reduces duplication and improves maintainability.
Example idea:
Thus, abstract class supports better code reuse.
(b) Multiple Inheritance
• Java does not support multiple inheritance with classes.
• However, if required, payment classes can implement multiple interfaces along with
extending one abstract class.
• Using an abstract class does not completely restrict flexibility.
If we used only an interface:
• We cannot provide complete method implementation (except default methods).
• Code reuse would be limited.
(c) Future Extensibility
• New payment methods (e.g., Wallet, Cryptocurrency) can extend the abstract class.
• Only the validation logic needs to be implemented.
• Common logging remains unchanged.
• Centralized control improves scalability.
• If logging logic changes, it can be modified in one place (abstract class).
16) You are developing a reusable Math Library for multiple projects. Explain step-by-step:
a) How do you define a package?
b) How does CLASSPATH affect compilation and execution?
c) Why improper CLASSPATH settings cause ClassNotFoundException
Ans When developing a reusable Math Library, proper use of packages and CLASSPATH is
important.
(a) How to Define a Package (Step-by-Step)
• Choose a package name
Package names are usually written in lowercase.
Example: [Link]
• Declare the package at the top of the Java file
The package statement must be the first line (except comments).
package [Link];
• Save the file inside matching directory structure
The folder structure must match the package name:
• Compile the file using -d option
javac -d . [Link]
This creates the proper directory structure automatically.
• Use the package in another program
import [Link];
Thus, a package helps organize and reuse classes across projects.
(b) How CLASSPATH Affects Compilation and Execution
CLASSPATH is an environment variable that tells the Java compiler and JVM where to look
for:
• Compiled .class files
• Packages and libraries
During Compilation:
• javac checks CLASSPATH to locate referenced classes.
• If the required class is not found, compilation fails.
During Execution:
• java uses CLASSPATH to locate the main class and other dependent classes.
• If the class is not found at runtime, execution fails.
Example:
set CLASSPATH=.;C:\projects
. means current directory.
Thus, CLASSPATH acts as a search path for Java classes.
(c) Why Improper CLASSPATH Causes ClassNotFoundException
ClassNotFoundException occurs when:
• The JVM cannot find the required class file.
• The class exists, but its location is not included in CLASSPATH.
• The directory structure does not match the package name.
Reasons:
• Wrong folder structure
• CLASSPATH not set correctly
• Missing current directory (.) in CLASSPATH
Since JVM depends on CLASSPATH to locate classes, incorrect settings prevent it from
loading the class, resulting in ClassNotFoundException.
17) A Department object contains an array of Employee objects.
a) Explain why using [Link]() creates a shallow copy.
b) Describe a real application bug caused by shallow cloning and how to fix it.
Ans Assume a Department class contains an array of Employee objects.
(a) Why does [Link]() create a shallow copy?
• The clone() method defined in the Object class performs a shallow copy by default.
• It copies primitive data types directly.
• It copies object references, not the actual objects.
• In case of arrays of objects, only the array reference is copied.
• The individual Employee objects are not duplicated.
Meaning:
After cloning:
• Original and cloned Department objects will have separate outer objects.
• But both will refer to the same Employee objects in memory.
Hence, any modification made to an Employee object in one department will also reflect in
the other.
This is called shallow copying.
(b) Real Application Bug and Its Fix
Real Application Bug
Suppose:
• A company clones a Department object to create a backup.
• Later, salary of an employee in the cloned department is modified.
• Since both departments share the same Employee objects, the salary change also
affects the original department.
This leads to:
• Data inconsistency
• Incorrect payroll calculation
• Serious business errors
This happens because only references were copied, not actual objects.
How to Fix the Problem (Deep Copy)
To avoid this issue, we must perform deep cloning.
In deep cloning:
• A new Department object is created.
• A new array of Employee objects is created.
• Each Employee object is cloned individually.
Example idea:
Now:
• Both departments have separate employee objects.
• Changes in one will not affect the other.
18) What will be the output of the following code snippet?
class Test {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
for(int i = 0; i < [Link]; i++) {
if(arr[i] == 3)
continue;
if(arr[i] == 5)
break;
[Link](arr[i] + " ");
}
}
}
Ans
Step-by-step Execution:
Array: {1, 2, 3, 4, 5}
• When element is 1 → printed
• When element is 2 → printed
• When element is 3 → continue statement skips printing
• When element is 4 → printed
• When element is 5 → break statement stops the loop
Output:
124
19) What will be the output of the following code snippet?
class Test {
static int x = 0;
static int fun(int n) {
if (n == 0)
return x;
x += n;
return fun(n - 1);
}
public static void main(String[] args) {
[Link](fun(3));
}
}
Ans
Step-by-step Execution:
Initial value:
static int x = 0;
Function call:
fun(3)
Execution flow:
• fun(3) → x = 0 + 3 = 3 → calls fun(2)
• fun(2) → x = 3 + 2 = 5 → calls fun(1)
• fun(1) → x = 5 + 1 = 6 → calls fun(0)
• fun(0) → returns x (which is 6)
The value 6 is printed in main().
Output:
6
20) Consider the code snippet below and answer the questions that follow:
class Person {
String name = "Parent";
Person() {
[Link]("Person Constructor");
}
{
[Link]("Inside init block of parent");
}
void display() {
[Link]("Person display()");
}
static void show() {
[Link]("Person static show()");
}
}
class Student extends Person {
String name = "Child";
{
[Link]("Inside init block of student");
}
Student() {
[Link]("Student Constructor");
}
void display() {
[Link]("Student display()");
}
static void show() {
[Link]("Student static show()");
}
}
public class Test {
public static void main(String[] args) {
Person obj = new Student();
[Link]([Link]);
[Link]();
[Link]();
}
}
a) What will be the complete output of the program?
b) Which constructor is executed first and why?
c) Which display() method is executed and why?
d) Which show() method is executed and why?
e) What concept of polymorphism is illustrated in this program?
Ans
(a) Complete Output of the Program
Step 1: Object Creation
Person obj = new Student();
When a Student object is created:
1) Parent class initialization block executes first
Inside init block of parent
2) Parent constructor executes
Person Constructor
3) Child class initialization block executes
Inside init block of student
4) Child constructor executes
Student Constructor
Step 2: Accessing Members
[Link]([Link]);
• name is a variable.
• Variables are resolved using reference type.
• Reference type is Person.
• So, Person's name is printed.
→ Parent
[Link]();
• display() is an overridden method.
• Methods are resolved using runtime polymorphism.
• Object type is Student.
• So, Student’s display() executes.
→ Student display()
[Link]();
• show() is a static method.
• Static methods are resolved using reference type, not object type.
• Reference type is Person.
→ Person static show()
• Final Output
(b) Which constructor is executed first and why?
The Person (parent) constructor is executed first.
Reason:
When a subclass object is created, Java automatically calls the superclass constructor first
using super(). This ensures that the parent class is properly initialized before the child class.
(c) Which display() method is executed and why?
Student display() is executed.
Reason:
Method overriding follows runtime polymorphism.
The method call depends on the object type (Student), not the reference type (Person).
(d) Which show() method is executed and why?
Person static show() is executed.
Reason:
Static methods are not overridden; they are hidden.
They follow compile-time binding and depend on the reference type (Person).
(e) Concept of Polymorphism Illustrated
This program illustrates:
• Runtime Polymorphism (Method Overriding) → display()
• Compile-time Polymorphism / Method Hiding → show()
• Upcasting → Person obj = new Student();
Thus, the main concept demonstrated is Runtime Polymorphism using Method Overriding.