Unit1 - Subjective Questions
CSE310 • Practice Questions with Detailed Answers
Explain the key features of Java that make it a popular programming language.
Java is a widely used programming language due to the following key features:
- Simple: Java eliminates complex features of C++ like pointers, operator overloading, and multiple inheritance, making it easier to learn.
- Object-Oriented: Java is purely object-oriented (almost), meaning everything is modeled as an object with data and behavior.
- Platform Independent: Java follows the WORA (Write Once, Run Anywhere) philosophy. Compiled Java code (bytecode) can run on any machine that has a JVM.
- Secure: Java runs inside a virtual machine sandbox and lacks explicit pointers, reducing security risks like buffer overflows.
- Robust: Java emphasizes early error checking, has strong memory management, and automatic garbage collection.
- Multi-threaded: It supports concurrent execution of two or more parts of a program for maximum CPU utilization.
- Distributed: Java is designed for the distributed environment of the internet, supporting protocols like TCP/IP and HTTP.
Differentiate between JDK, JRE, and JVM. Explain their relationship.
1. JVM (Java Virtual Machine):
It is an abstract machine that provides a runtime environment in which Java bytecode can be executed. It performs three main tasks: loading code, verifying code, and executing code.
2. JRE (Java Runtime Environment):
It is a set of software tools which are used for developing Java applications. It acts as the implementation of the JVM. It physically exists. It contains a set of libraries + other files that the JVM uses at runtime.
3. JDK (Java Development Kit):
It is a software development environment used to develop Java applications and applets. It physically exists. It contains JRE + development tools (javac, java, javadoc, etc.).
Relationship Equation:
Dissect the signature of the main method in Java: public static void main(String args[]).
Every word in the main method signature has a specific meaning:
- public: It is an access modifier. It dictates that the method is accessible everywhere. The JVM needs to call this method from outside the class, so it must be public.
- static: It is a keyword. It allows the main method to be called without creating an instance (object) of the class. Since the JVM starts the program, no object exists yet, so the entry point must be static.
- void: It is the return type. The main method does not return any value to the JVM.
- main: It is the name of the method. The JVM looks for this specific name as the starting point of the program.
- String args[]: It is the parameter passed to the main method. It accepts command-line arguments as an array of String objects.
Explain the concept of Type Conversion in Java. Differentiate between Implicit and Explicit type casting with examples.
Type conversion is the process of converting one data type into another. In Java, it is classified into two types:
1. Widening Casting (Implicit):
It happens automatically when passing a smaller size type to a larger size type.
- Order:
- Example:
java
int myInt = 9;
double myDouble = myInt; // Automatic casting: 9.0
2. Narrowing Casting (Explicit):
It must be done manually by placing the type in parentheses in front of the value. It is required when converting a larger type to a smaller size type, as data loss may occur.
- Example:
java
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: 9 (fractional part lost)
What are the primitive data types available in Java? List them with their sizes.
Java defines 8 primitive data types used to store simple values:
| Type | Classification | Size | Description |
|---|---|---|---|
| byte | Integer | 1 byte (8 bits) | Stores whole numbers from -128 to 127 |
| short | Integer | 2 bytes | Stores whole numbers from -32,768 to 32,767 |
| int | Integer | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647 |
| long | Integer | 8 bytes | Stores large whole numbers |
| float | Floating Point | 4 bytes | Stores fractional numbers (6-7 decimal digits) |
| double | Floating Point | 8 bytes | Stores fractional numbers (15 decimal digits) |
| boolean | Logic | 1 bit* | Stores true or false |
| char | Text | 2 bytes | Stores a single character/letter (Unicode) |
Define Identifiers in Java. What are the rules and conventions for defining valid identifiers?
Identifiers are names given to various program elements such as variables, methods, classes, and packages.
Rules for Valid Identifiers:
- Allowed Characters: Can contain letters (A-Z, a-z), digits (0-9), underscores (
_), and dollar signs ($). - Start: Must start with a letter,
$, or_. It cannot start with a digit. - Keywords: Java reserved keywords (e.g.,
class,void,int) cannot be used as identifiers. - Case Sensitivity: Identifiers are case-sensitive (
myVarandmyvarare different). - No Spaces: Spaces are not allowed.
Examples:
- Valid:
_value,$salary,student1,calculateSum - Invalid:
123name(starts with digit),class(keyword),my var(contains space)
Explain the Bit-wise operators in Java with suitable examples.
Bit-wise operators perform operations on individual bits of integer data types. Assuming () and ():
- Bitwise AND (
&): Returns 1 if both bits are 1.- (Decimal 1)
- Bitwise OR (
|): Returns 1 if at least one bit is 1.- (Decimal 7)
- Bitwise XOR (
^): Returns 1 if bits are different.- (Decimal 6)
- Bitwise Complement (
~): Inverts all bits.- (Decimal -6)
- Left Shift (
<<): Shifts bits to the left, filling with 0.- (Decimal 10)
- Right Shift (
>>): Shifts bits to the right, preserving sign.- (Decimal 2)
What is the static keyword? Explain its usage with variables and methods.
The static keyword in Java is used for memory management mainly. It applies to variables, methods, blocks, and nested classes. It indicates that the member belongs to the class rather than a specific instance of the class.
1. Static Variables (Class Variables):
- Declared with the
statickeyword. - Only one copy of the variable is created in memory, regardless of how many objects are created.
- Shared among all objects.
- Example:
static int count = 0;(Used for counters).
2. Static Methods:
- Can be called without creating an object of the class.
- Can only access static data members and change them.
- Cannot use
thisorsuperkeywords. - Example:
Math.sqrt()orpublic static void main(...).
Compare the different Access Modifiers available in Java.
Access modifiers determine the scope (visibility) of a class, constructor, variable, method, or data member. Java provides four types:
| Modifier | Class | Package | Subclass (diff pkg) | World (diff pkg) |
|---|---|---|---|---|
| public | Yes | Yes | Yes | Yes |
| protected | Yes | Yes | Yes | No |
| Default (no keyword) | Yes | Yes | No | No |
| private | Yes | No | No | No |
- private: Most restrictive. Accessible only within the class.
- default: Accessible only within the same package.
- protected: Accessible within the package and outside the package strictly through inheritance (child classes).
- public: Accessible from anywhere.
Describe the syntax and working of the switch-case statement. What is the role of the break keyword?
Syntax:
java
switch(expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// code block
}
Working:
- The
expressionis evaluated once. - The value is compared with the values of each
case. - If a match is found, the associated block of code is executed.
Role of break:
- When Java reaches a
breakkeyword, it breaks out of the switch block. - It stops the execution of more code and case testing inside the block.
- Without
break, fall-through occurs, meaning the program continues to execute the next case statements even if the case value doesn't match, until a break or end of switch is reached.
What are Wrapper Classes? Explain the concepts of Autoboxing and Unboxing.
Wrapper Classes provide a way to use primitive data types (int, boolean, etc.) as Objects. This is necessary because Java Collection frameworks work with Objects, not primitives.
Examples:
intIntegercharCharacter
Autoboxing:
The automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.
- Example:
Integer a = 5;(Convertingint5 toIntegerobject automatically).
Unboxing:
The reverse process where the Java compiler automatically converts an Object of a wrapper class to its corresponding primitive type.
- Example:
Integer a = new Integer(5); int b = a;(ConvertingIntegerobject toint).
Explain the Ternary Operator with syntax and an example. How is it different from if-else?
The Ternary Operator (also known as the conditional operator) is the only operator in Java that takes three operands. It is used as a shorthand for if-else statements.
Syntax:
Example:
java
int a = 10, b = 20;
int max = (a > b) ? a : b;
// If a > b, max = a, otherwise max = b
Difference from if-else:
- Conciseness: Ternary is a one-liner, whereas
if-elsetakes multiple lines. - Return Value: The ternary operator returns a value that must be used (assigned or printed), whereas
if-elseis a control flow statement that doesn't return a value but executes blocks of code.
What are Command-Line Arguments? Write a Java program to print all arguments passed via the command line.
Command-Line Arguments are arguments passed to a program at the time of running it. These arguments are stored as strings in the String args[] array passed to the main() method.
Java Program:
java
public class CommandLineExample {
public static void main(String[] args) {
System.out.println("Arguments passed: " + args.length);
// Loop through the arguments
for (int i = 0; i < args.length; i++) {
System.out.println("Arg " + i + ": " + args[i]);
}
}
}
Execution:
java CommandLineExample Hello World 123
Output:
Arg 0: Hello
Arg 1: World
Arg 2: 123
Explain Operator Precedence and Associativity in Java. Calculate the value of x in: int x = 5 + 10 * 3 / 2;
Operator Precedence: Determines the order in which operators are evaluated. Operators with higher precedence are evaluated first.
Associativity: Determines the order in which operators of the same precedence are evaluated (usually Left-to-Right, but Assignment is Right-to-Left).
Calculation:
Expression:
- Precedence:
*and/have higher precedence than+. They are equal in precedence. - Associativity:
*and/are evaluated Left-to-Right. - First, .
- Expression becomes:
- Next, (Integer division).
- Expression becomes:
- Finally, .
Result:
Discuss the difference between the Short-circuit logical operators (&&, ||) and standard logical operators (&, |).
The primary difference lies in how they evaluate the second operand.
Short-Circuit Operators (&&, ||):
&&(Logical AND): If the first condition isfalse, the result is known to befalse. The second condition is not evaluated (short-circuited).||(Logical OR): If the first condition istrue, the result is known to betrue. The second condition is not evaluated.- Usage: More efficient, commonly used in boolean logic (if statements).
Standard/Bitwise Operators (&, |) used as Logical:
&: Both conditions are always evaluated, even if the first isfalse.|: Both conditions are always evaluated, even if the first istrue.- Usage: Used when side effects in the second condition are required (e.g.,
(x > 0) & (y++ > 5)ensuresyis incremented).
What is Java Bytecode? How does it contribute to platform independence?
Java Bytecode is the instruction set for the Java Virtual Machine (JVM). When a Java program (.java) is compiled by the javac compiler, it is translated into bytecode (.class file) rather than machine code specific to the computer's processor.
Contribution to Platform Independence:
- Bytecode is machine-neutral. It doesn't contain instructions for an Intel, ARM, or AMD processor specifically.
- Any device with a JVM installed can interpret or compile (via JIT) this bytecode into the native machine code of that specific device.
- This allows the developer to compile the code once on Windows, for example, and run the resulting
.classfile on Linux or macOS without recompilation. This enables the "Write Once, Run Anywhere" feature.
Write a simple Java Class structure illustrating fields, methods, and object creation.
java
// Class Declaration
class Student {
// Fields (Instance Variables)
int id;
String name;
// Method to insert records
void insertRecord(int i, String n) {
id = i;
name = n;
}
// Method to display information
void display() {
System.out.println(id + " " + name);
}
}
// Main Class
public class TestStudent {
public static void main(String args[]) {
// Object Creation (using 'new' keyword)
Student s1 = new Student();
// Accessing methods
s1.insertRecord(101, "Alice");
s1.display();
}
}
This illustrates a class Student with data members (id, name), member functions (insertRecord, display), and the instantiation of the class in the main method.
Explain the scope and lifetime of variables: Local, Instance, and Static.
1. Local Variables:
- Declaration: Inside a method, constructor, or block.
- Scope: Only within the method/block where declared.
- Lifetime: Created when the block is entered, destroyed when the block is exited. No default value (must be initialized).
2. Instance Variables (Non-Static Fields):
- Declaration: Inside a class but outside methods.
- Scope: Throughout the class (except in static context without object ref).
- Lifetime: Created when an object is created (
new). Destroyed when the object is garbage collected. Has default values (e.g., 0, null).
3. Static Variables (Class Variables):
- Declaration: Inside a class with the
statickeyword. - Scope: Throughout the class.
- Lifetime: Created when the class is loaded by the JVM. Destroyed when the program stops or class is unloaded. Shared across all instances.
How does the Just-In-Time (JIT) compiler improve the performance of Java applications?
The JIT (Just-In-Time) compiler is a component of the JRE (specifically part of the JVM).
- Interpretation vs. Compilation: Standard interpretation of bytecode is slow because the JVM interprets one instruction at a time.
- JIT Action: The JIT compiler interacts with the JVM at runtime and compiles sequences of bytecode into native machine code (hardware-specific code) "just in time" for execution.
- Optimization: It identifies "hotspots" (code that runs frequently) and compiles them into native code. Subsequent calls to that method use the compiled native code directly, skipping the slow interpretation process.
- Result: This hybrid approach (Interpretation + JIT Compilation) significantly boosts execution speed closer to that of compiled languages like C++.
Write a Java program to find the largest of three numbers using Nested If-Else statements.
java
public class LargestNumber {
public static void main(String[] args) {
int n1 = 10, n2 = 25, n3 = 15;
if (n1 >= n2) {
if (n1 >= n3) {
System.out.println(n1 + " is the largest number.");
} else {
System.out.println(n3 + " is the largest number.");
}
} else {
if (n2 >= n3) {
System.out.println(n2 + " is the largest number.");
} else {
System.out.println(n3 + " is the largest number.");
}
}
}
}
Logic: The outer if checks if n1 is greater than n2. If true, the inner if compares n1 with n3. If the outer if is false (n2 is greater), the inner else block compares n2 with n3.