Unit2 - Subjective Questions
CSE310 • Practice Questions with Detailed Answers
Differentiate between the while loop and the do-while loop in Java with syntax and examples.
Difference between while and do-while loops:
| Feature | while Loop |
do-while Loop |
|---|---|---|
| Type | Entry-controlled loop. | Exit-controlled loop. |
| Condition Check | Condition is checked before the execution of the body. | Condition is checked after the execution of the body. |
| Execution Guarantee | Body may not execute at all if the condition is false initially. | Body executes at least once even if the condition is false. |
| Syntax | while(condition) { ... } |
do { ... } while(condition); |
Example:
-
While Loop:
java
int i = 10;
while(i < 5) {
System.out.println("This will not print");
} -
Do-While Loop:
java
int i = 10;
do {
System.out.println("This prints once");
} while(i < 5);
Explain the concept of the Enhanced for-loop (for-each loop) in Java. Provide its syntax and discuss its advantages and limitations.
Enhanced for-loop (for-each):
Introduced in Java 5, the for-each loop is used to traverse arrays or collections sequentially without using an index variable.
Syntax:
java
for (Type var : array) {
// statements using var
}
Example:
java
int[] numbers = {10, 20, 30};
for (int num : numbers) {
System.out.println(num);
}
Advantages:
- Readability: The code is cleaner and less error-prone (avoids
ArrayIndexOutOfBoundsException). - Simplicity: No need to manage start, end, and increment conditions manually.
Limitations:
- Forward Only: It can only iterate in the forward direction.
- Read-Only Access: You cannot modify the array/collection element itself (replacing the element) directly using the iteration variable.
- No Index: You do not have access to the index of the current element.
Define an Array in Java. Explain how to declare, instantiate, and initialize a one-dimensional array.
Definition:
An array is a collection of similar types of data elements stored at contiguous memory locations. In Java, arrays are objects.
1. Declaration:
Declares the reference variable but does not allocate memory.
- Syntax:
DataType[] arrayName; - Example:
int[] marks;
2. Instantiation:
Allocates memory for the array elements using the new keyword.
- Syntax:
arrayName = new DataType[size]; - Example:
marks = new int[5];(Allocates memory for 5 integers).
3. Initialization:
Assigns values to the array elements.
- Dynamic Initialization:
marks[0] = 95; - Literal Initialization (Combine all steps):
java
int[] marks = {95, 80, 75, 88, 92};
The memory size allocated is .
What are Multi-dimensional Arrays in Java? How are they stored in memory? Write a code snippet to print a 2D array in matrix format.
Multi-dimensional Arrays:
In Java, multi-dimensional arrays are actually "arrays of arrays". A 2D array is an array where each element is a reference to a 1D array.
Memory Storage:
Unlike languages like C/C++ where a 2D array is a contiguous block of memory, in Java, the rows can be stored in different memory locations, and they can even have different lengths (Jagged Arrays).
Code Snippet:
java
public class MatrixPrint {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Nested loops for iteration
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // New line after each row
}
}
}
Explain the concept of Variable Arguments (Varargs) in Java. How is it defined in a method signature?
Variable Arguments (Varargs):
Varargs allow a method to accept zero or multiple arguments of the same type. Internally, these arguments are treated as an array. This feature simplifies code when the number of inputs is not known beforehand.
Syntax:
Three dots (...) are used after the data type.
java
returnType methodName(DataType... args) {
// method body
}
Rules:
- There can be only one varargs parameter in a method.
- The varargs parameter must be the last parameter in the method signature.
Example:
java
void printNumbers(int... numbers) {
for (int num : numbers) {
System.out.print(num + " ");
}
}
// Usage: printNumbers(1, 2, 3, 4); or printNumbers();
What is an Enumeration (Enum) in Java? How does it differ from a standard class? Provide an example of an Enum used in a switch statement.
Enumeration (Enum):
An Enum is a special data type that enables for a variable to be a set of predefined constants. Defined using the enum keyword.
Differences from Standard Class:
- Enums implicitly extend
java.lang.Enum. - Enum constants are implicitly
public static final. - Enums cannot extend other classes (but can implement interfaces).
- Constructors in Enums are always
private.
Example:
java
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class TestEnum {
public static void main(String[] args) {
Day today = Day.MONDAY;
switch (today) {
case MONDAY:
System.out.println("Start of the work week.");
break;
case FRIDAY:
System.out.println("Weekend is near.");
break;
default:
System.out.println("Mid-week days.");
}
}
}
Define Class and Object. Explain the relationship between them and how an object is created in Java.
Class:
- A class is a blueprint or a template from which objects are created.
- It defines a set of properties (variables) and behaviors (methods) that are common to all objects of that type.
- It is a logical entity and does not consume memory until instantiated.
Object:
- An object is an instance of a class.
- It is a physical entity that occupies memory in the Heap.
- It has state (data values), behavior (functionality), and identity.
Relationship:
- Class is the definition (); Object is the realization (). Use the analogy: Class is the mold, Object is the brick created from the mold.
Object Creation:
java
ClassName objectName = new ClassName();
ClassName objectName: Declares a reference variable.new: Allocates memory dynamically.ClassName(): Initializes the object (Constructor call).
What is a Constructor? How does it differ from a regular method? Explain Default and Parameterized constructors.
Constructor:
A constructor is a special block of code that initializes a newly created object. It is called implicitly when an object is created using the new keyword.
Difference from Method:
- Name: Must be exactly the same as the class name.
- Return Type: Does not have a return type (not even
void). - Invocation: Called automatically during object creation, not explicitly called like methods.
Types of Constructors:
-
Default Constructor:
- A constructor with no parameters.
- If no constructor is defined in a class, the compiler inserts a default constructor automatically.
- Example:
public Student() { ... }
-
Parameterized Constructor:
- Accepts arguments to initialize the object with specific values.
- Example:
public Student(String name, int age) { this.name = name; ... }
Explain Method Overloading with an example. What are the rules for overloading a method?
Method Overloading:
Method overloading allows a class to have more than one method having the same name, as long as their parameter lists are different. It is a form of Compile-time Polymorphism.
Rules for Overloading:
- Change in Number of Parameters: e.g.,
add(int a, int b)vsadd(int a, int b, int c). - Change in Data Type of Parameters: e.g.,
add(int a)vsadd(double a). - Change in Order of Parameters: e.g.,
print(int a, String b)vsprint(String b, int a). - Note: Changing only the return type does not constitute overloading.
Example:
java
class Calculator {
// Overloading by number of arguments
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
// Overloading by type
double add(double a, double b) {
return a + b;
}
}
Describe the usage of the this keyword in Java with appropriate examples for each use case.
The this keyword is a reference variable that refers to the current object.
Main Uses:
-
Refer to current class instance variable:
Used to resolve ambiguity between instance variables and parameters.
java
class Student {
int id;
Student(int id) {
this.id = id; // 'this.id' is instance var, 'id' is parameter
}
} -
Invoke current class constructor (Constructor Chaining):
Must be the first statement in the constructor.
java
Student() {
this(10); // Calls parameterized constructor
} -
Invoke current class method:
java
void display() { ... }
void show() {
this.display(); // Explicitly calling method
} -
Pass as an argument in method/constructor call:
methodName(this);
What are Initializer Blocks? Distinguish between Static Initializer Blocks and Instance Initializer Blocks regarding their execution time.
Initializer Blocks:
These are blocks of code defined inside a class used to initialize data members.
1. Static Initializer Block:
- Syntax:
static { ... } - Execution: Executed once when the class is loaded into memory by the ClassLoader.
- Use: initializing static variables.
2. Instance Initializer Block:
- Syntax:
{ ... }(inside class, outside methods) - Execution: Executed every time an object of the class is created. It runs before the constructor (but after the
super()call). - Use: Sharing common initialization code across multiple constructors.
Comparison Table:
| Feature | Static Block | Instance Block |
|---|---|---|
| Keyword | static |
None |
| Execution Frequency | Once per class load | Per object creation |
| Timing | Before main/object creation | Before constructor body |
Explain Constructor Overloading. How can one constructor call another constructor within the same class?
Constructor Overloading:
Similar to method overloading, a class can have multiple constructors with different parameter lists. This allows objects to be initialized in different ways.
Calling another constructor:
We use this() to call another constructor from within a constructor. This is known as Constructor Chaining.
Rules for this():
- It must be the first statement in the constructor body.
- Recursive calls (A calls B, B calls A) are not allowed.
Example:
java
class Box {
double width, height, depth;
// Constructor 1: No arguments
Box() {
this(1.0); // Calls Constructor 2
}
// Constructor 2: One argument (Cube)
Box(double len) {
this(len, len, len); // Calls Constructor 3
}
// Constructor 3: Three arguments
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
}
Discuss the String class in Java. Why are Strings called Immutable? Explain the concept of the String Constant Pool.
String Class:
java.lang.String represents a sequence of characters. It is one of the most widely used classes in Java.
Immutability:
- Once a String object is created, its data (character sequence) cannot be changed.
- If you modify a string (e.g., concatenation), a new String object is created in memory, and the reference is updated.
- Reason: Security (parameters like passwords/URLs), Synchronization (thread-safety), and Caching (HashCode keys).
String Constant Pool (SCP):
- A special memory region in the Heap used to store String literals.
- When a string literal is created (e.g.,
String s = "Hello";), JVM checks the pool. - If "Hello" exists, the reference to the existing instance is returned. If not, a new instance is created in the pool.
- This saves significant memory by avoiding duplicates.
Compare String and StringBuilder classes. When should you use StringBuilder over String?
Comparison:
| Feature | String | StringBuilder |
|---|---|---|
| Mutability | Immutable (cannot be changed). | Mutable (can be modified). |
| Performance | Slower for frequent modifications (creates new objects). | Faster for frequent modifications. |
| Memory | Uses String Constant Pool (efficient for duplicates). | Standard Heap memory allocation. |
| Thread Safety | Thread-safe (due to immutability). | Not thread-safe. |
When to use StringBuilder:
Use StringBuilder when you need to perform many modifications to a string of characters (like concatenations, insertions, or deletions) within a loop or logic block. It prevents the creation of multiple temporary string objects, thus reducing garbage collection overhead and improving performance.
Note: StringBuffer is similar to StringBuilder but is thread-safe (synchronized).
List and explain any five important methods of the String class with examples.
1. length()
- Returns the number of characters in the string.
"Java".length()returns $4$.
2. charAt(int index)
- Returns the character at the specified index.
"Java".charAt(2)returns'v'.
3. substring(int beginIndex, int endIndex)
- Returns a new string that is a substring of this string.
"Hello".substring(0, 2)returns"He". (endIndex is exclusive).
4. equals(Object another)
- Compares the content of the string.
"Test".equals("test")returnsfalse(case-sensitive).
5. trim()
- Removes leading and trailing whitespace.
" Hi ".trim()returns"Hi".
Write a Java program to define a class Rectangle with fields length and width. Include a constructor to initialize these fields and a method area() to return the area. Instantiate the class and print the area.
java
// Define the class
class Rectangle {
// Fields
double length;
double width;
// Constructor
Rectangle(double l, double w) {
this.length = l;
this.width = w;
}
// Method to calculate area
double area() {
return length * width;
}
}
// Main class
public class Main {
public static void main(String[] args) {
// Instantiation
Rectangle rect = new Rectangle(10.5, 5.0);
// Method call and output
System.out.println("Area of Rectangle: " + rect.area());
}
}
Output:
Area of Rectangle: 52.5
How does the StringBuilder class handle capacity? Explain the append() and insert() methods.
StringBuilder Capacity:
- The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.
- The default capacity is 16 characters plus the length of the string argument.
- When capacity is exceeded, the JVM automatically increases it (usually ).
Methods:
-
append(String str):- Concatenates the specified string to the end of the current sequence.
- Example:
java
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // sb is now "Hello World"
-
insert(int offset, String str):- Inserts the string into this character sequence at the specified offset.
- Example:
java
StringBuilder sb = new StringBuilder("He World");
sb.insert(2, "llo"); // sb is now "Hello World"
What is a Jagged Array? How do you declare and initialize a jagged array in Java? Provide a diagrammatic representation description or code.
Jagged Array:
A jagged array is a multi-dimensional array where member arrays are of different sizes. In simple terms, it is an array of arrays with different row lengths.
Declaration and Initialization:
java
// Declare a 2D array with 3 rows, columns undefined
int[][] jagged = new int[3][];
// Initialize each row with different lengths
jagged[0] = new int[3]; // Row 0 has 3 cols
jagged[1] = new int[2]; // Row 1 has 2 cols
jagged[2] = new int[4]; // Row 2 has 4 cols
// Assigning values
jagged[0][0] = 10;
jagged[1][1] = 20;
Visualization:
Row 0: [ ][ ][ ]
Row 1: [ ][ ]
Row 2: [ ][ ][ ][ ]
Explain the mechanics of the for loop flow. How can you create an Infinite Loop using the for syntax?
For Loop Mechanics:
Syntax: for (initialization; condition; update) { body }
- Initialization: Executed only once at the start.
- Condition: Checked before every iteration. If true, body executes. If false, loop terminates.
- Body: The code block executes.
- Update: Executed after the body. Usually increments/decrements the counter.
- The flow repeats from step 2.
Infinite Loop:
If the condition part is omitted, it defaults to true.
java
for (;;) {
System.out.println("This runs forever");
}
Alternatively, a condition that never becomes false:
java
for(int i=0; i>=0; i++) { ... }
Discuss Anonymous Arrays in Java. When are they useful? Give an example.
Anonymous Array:
An array that is created without an explicit name (reference variable) is called an anonymous array. It is created just for the purpose of immediate usage (usually passing as an argument to a method).
Syntax:
new Type[] { value1, value2, ... }
(Note: No size is specified inside []).
Use Case:
Useful when an array is needed only once, and we don't want to clutter the code with variable declarations.
Example:
java
public class Test {
static void printArray(int[] arr) {
for(int i : arr) System.out.print(i + " ");
}
public static void main(String args[]) {
// Passing anonymous array to method
printArray(new int[]{10, 22, 44, 66});
}
}