Unit I: Introduction and Fundamentals of Java - Detailed Answers
Question 1: Explain the features of Java that make it platform-independent and robust. How does the Java
Java is a powerful programming language designed with several key features that make it
platform-independent and robust.
1. Features of Java:
- Platform Independence:
Java follows the "Write Once, Run Anywhere" (WORA) principle. Java programs are compiled into
bytecode, an intermediate, machine-independent code. This bytecode can run on any system with a
Java Virtual Machine (JVM), irrespective of the underlying hardware or operating system.
- Robustness:
Java emphasizes error-free programming by incorporating:
- Strong memory management through garbage collection.
- Built-in exception handling mechanisms.
- Type safety and strict compile-time checks.
- Security:
Java uses a classloader, bytecode verifier, and security manager to restrict unauthorized access
and execute programs securely.
2. Role of JVM:
The Java Virtual Machine (JVM) is the runtime environment that enables the execution of Java
bytecode. Its key components include:
- Class Loader: Loads bytecode into memory dynamically.
- Bytecode Verifier: Ensures the code adheres to Java's security and language rules.
- Interpreter/Just-In-Time (JIT) Compiler: Converts bytecode into machine code for execution.
By abstracting platform details and managing execution securely, the JVM ensures platform
independence and robust performance.
Question 2: Differentiate between the types of variables in Java (local, instance, and static) with examples.
Java variables are classified based on their scope, lifetime, and how they are declared.
1. Local Variables:
- Defined inside methods, constructors, or blocks.
- Exist only within their scope.
- Must be initialized explicitly before use.
Example:
class LocalExample {
void show() {
int localVar = 10; // Local variable
System.out.println("Local Variable: " + localVar);
2. Instance Variables:
- Declared inside a class but outside any method or constructor.
- Each object of the class gets its own copy.
- Initialized to default values if not explicitly initialized.
Example:
class InstanceExample {
int instanceVar = 20; // Instance variable
void display() {
System.out.println("Instance Variable: " + instanceVar);
3. Static Variables:
- Declared with the `static` keyword.
- Shared among all objects of the class.
- Stored in the method area of memory.
Example:
class StaticExample {
static int staticVar = 30; // Static variable
void display() {
System.out.println("Static Variable: " + staticVar);
Comparison Table:
| Feature | Local Variable | Instance Variable | Static Variable |
|--------------------|---------------------|-------------------------|------------------------|
| Scope | Method/block | Object | Class |
| Lifetime | During method call | Lifetime of object | Lifetime of program |
| Initialization | Must be initialized | Default or explicit | Default or explicit |
Question 3: Discuss the role of wrapper classes in Java. How are they used in type conversion and autobo
Wrapper classes in Java convert primitive data types into objects. Each primitive type has a
corresponding wrapper class, such as `Integer` for `int`, `Double` for `double`, etc.
1. Purpose of Wrapper Classes:
- Enable primitives to work with collections (`ArrayList`, `HashMap`, etc.).
- Provide utility methods for conversions and operations (`Integer.parseInt()`, `Double.valueOf()`,
etc.).
- Allow autoboxing and unboxing in Java.
2. Type Conversion:
Wrapper classes are essential for converting between primitives and objects.
- Primitive to Object (Boxing):
int num = 10;
Integer obj = Integer.valueOf(num); // Explicit Boxing
Integer obj2 = num; // Autoboxing
- Object to Primitive (Unboxing):
Integer obj = 25;
int num = obj.intValue(); // Explicit Unboxing
int num2 = obj; // Autoboxing
3. Autoboxing and Unboxing:
Introduced in Java 5, these features simplify type conversion.
- Autoboxing: Automatically converts primitives to objects.
- Unboxing: Automatically converts objects to primitives.
Example Program:
import java.util.ArrayList;
class WrapperExample {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10); // Primitive to object (Autoboxing)
numbers.add(20);
int num = numbers.get(0); // Object to primitive (Unboxing)
System.out.println("Number: " + num);
Question 4: What is the structure of a Java program? Illustrate with a code example demonstrating input/ou
A Java program has the following structure:
1. Structure of Java Program:
package mypackage;
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
// Program logic
}
}
2. Key Components:
- Package Declaration: Specifies the package name.
- Import Statements: Import classes for reuse (e.g., `java.util.Scanner`).
- Class Declaration: Encapsulates data and methods.
- Main Method: Entry point of the program.
3. Input/Output Example Program:
import java.util.Scanner;
public class ProgramStructure {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
Question 5: Write a program to calculate the factorial of a number using looping statements. Explain the co
Factorial of a number `n` is the product of all positive integers less than or equal to `n`.
1. Logic:
- Use a `for` loop to multiply numbers from 1 to `n`.
- Initialize the result to 1 and multiply iteratively.
2. Program:
import java.util.Scanner;
public class FactorialExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int factorial = 1;
// For loop to calculate factorial
for (int i = 1; i <= num; i++) {
factorial *= i;
System.out.println("Factorial of " + num + " is: " + factorial);
3. Control Structure Used:
- For Loop: Iterates a fixed number of times.
for (initialization; condition; update) {
// Body of the loop
In this example:
- Initialization: `int i = 1;`
- Condition: `i <= num` ensures the loop runs till `i` reaches `num`.
- Update: `i++` increments `i` after each iteration.
Output:
Enter a number: 5
Factorial of 5 is: 120