Java Practice Questions Answers - 1

Java Programming FAQ

Essential Concepts and Interview Questions

Core Java OOP JVM
1

Explain the role of the Java Virtual Machine (JVM)

Runs Anywhere

JVM helps Java programs run on any computer. It's like a magic translator that makes sure your Java code speaks the language of different machines.

Reads Special Code

When you write Java, the computer doesn't understand it directly. JVM reads a special kind of code called bytecode, which is like a universal language for Java programs.

Takes Care of Memory

JVM is like a tidy-up helper. It cleans up unused stuff (memory) in your program, so your computer doesn't get cluttered and slow. It's like having a virtual janitor for your Java applications.

2

Differentiate between JDK and JRE

JRE (Java Runtime Environment)

JRE is like a runner; it lets you run Java programs on your computer. If you want to play a game or use an app built in Java, you need JRE.

JDK (Java Development Kit)

JDK is like a creator and runner. It not only lets you run Java programs but also helps you create them. If you want to build your own games or apps in Java, you need JDK.

JDK's Purpose

JDK is for people who want to make cool Java stuff. It's a toolbox with extra tools for creating, testing, and fixing Java programs. If you just want to play Java games, JRE is enough. If you want to make games, get JDK.

3

Define Java Runtime Environment (JRE)

JRE is a Helper

JRE is like a helpful friend for your computer. It's a bunch of tools that your computer needs to understand and run Java programs.

Runs Java Stuff

If you want to play a game or use an app that's made in Java, you need JRE. It's the reason your computer knows what to do with those Java programs.

No Making, Just Running

JRE doesn't help you make new Java things; it's just there to make sure the ones already made can run smoothly on your computer. It's like the audience for Java shows, making sure they enjoy the performance without worrying about how it was created.

4

What is Garbage Collection in Java?

Garbage Collection in Java is a process that automatically identifies and removes unused or unnecessary objects in a program's memory. It helps in managing the dynamic allocation and deallocation of memory, ensuring efficient use of resources.

Contribution to Memory Management

Automatic Cleanup: Garbage Collection automatically identifies objects that are no longer needed in a program, such as variables or data that are not being used. It then frees up the memory occupied by these objects, preventing memory leaks and improving the overall performance of the program.

Prevention of Memory Leaks: Memory leaks occur when a program allocates memory for objects but fails to release it after they are no longer in use. Garbage Collection actively addresses this issue by reclaiming memory from objects that are no longer referenced, ensuring efficient utilization of the available memory.

Simplified Memory Management: Garbage Collection simplifies memory management for developers. They don't have to manually allocate and deallocate memory for objects, reducing the risk of errors and making it easier to write reliable and robust Java programs. This automated process contributes to the stability and scalability of Java applications.

5

Primitive Data Types in Java

int (Integer)

Used to store whole numbers without decimal points.
int age = 25;

double (Double)

Used to store numbers with decimal points. More precise than float.
double price = 19.99;

boolean (Boolean)

Stores true or false values. Useful for decisions.
boolean isJavaFun = true;

char (Character)

Stores a single character in single quotes.
char grade = 'A';

byte

Used for small whole numbers. Saves memory.
byte books = 5;

short

Similar to int, for larger whole numbers.
short population = 5000;

long

Used for very large whole numbers.
long bigNumber = 1234567890L;

float

Stores decimal numbers, less precise than double.
float pi = 3.14f;

6

Define identifiers in Java

Identifiers in Java are names given to variables, methods, classes, or other program elements. They help in uniquely identifying and referring to different parts of a Java program.

Valid Identifiers

Can start with a letter (a-z, A-Z) or underscore (_), followed by letters, digits, or underscores.

  • totalAmount
  • _count
  • first_name

Invalid Identifiers

Cannot start with digit, contain special characters (except _), or be Java keywords.

  • 3rdPlace (starts with digit)
  • total@count (special character)
  • class (Java keyword)

Good Practice

Use meaningful and descriptive names to enhance code readability:

  • numberOfStudents
  • calculateTotal
  • userInput
7

Constants vs Variables in Java

Variables

Definition: Storage locations where you can store and manipulate data.

Mutability: Values can be changed during execution.

Example:
int age = 25;
age = 26; // Valid

Constants

Definition: Identifiers with values that remain unchanged.

Immutability: Values cannot be altered after assignment.

Example:
final double PI = 3.14;
// PI = 3.15; // Compile error

8

Declare and initialize a one-dimensional array

Syntax: dataType[] arrayName = {element1, element2, ..., elementN};

Examples:

Integer Array:

int[] numbers = {1, 2, 3, 4, 5};

Double Array:

double[] prices = {2.99, 4.95, 7.50, 1.99};

String Array:

String[] names = {"Alice", "Bob", "Charlie"};
9

'==' vs 'equals()' in Java

== Operator

Comparison Focus: Compares memory addresses (object references)

Usage:

int a = 5;
int b = 5;
boolean result = (a == b); // true

equals() Method

Comparison Focus: Compares content/values of objects

Usage:

String str1 = new String("Hello");
String str2 = new String("Hello");
boolean result = str1.equals(str2); // true

Summary: == checks memory addresses for equality, while equals() is designed for content-based comparison and can be customized in classes.

10

"if-else" statement example

Check if a number is even or odd:

public class EvenOddChecker {
    public static void main(String[] args) {
        int number = 7;
        
        if (number % 2 == 0) {
            System.out.println(number + " is even.");
        } else {
            System.out.println(number + " is odd.");
        }
    }
}
12

"switch" statement example

import java.util.Scanner;

public class DayOfWeekPrinter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number (1-7): ");
        int dayNumber = scanner.nextInt();

        switch (dayNumber) {
            case 1: System.out.println("It's Monday!"); break;
            case 2: System.out.println("It's Tuesday!"); break;
            case 3: System.out.println("It's Wednesday!"); break;
            case 4: System.out.println("It's Thursday!"); break;
            case 5: System.out.println("It's Friday!"); break;
            case 6: System.out.println("It's Saturday!"); break;
            case 7: System.out.println("It's Sunday!"); break;
            default: System.out.println("Invalid input");
        }
        scanner.close();
    }
}
13

"for" loop example

Print first 5 natural numbers:

public class PrintNaturalNumbers {
    public static void main(String[] args) {
        System.out.println("First 5 Natural Numbers:");
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}
14

"while" loop factorial program

import java.util.Scanner;

public class FactorialCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();
        
        long factorial = 1;
        int i = 1;
        
        while (i <= number) {
            factorial *= i;
            i++;
        }
        
        System.out.println("Factorial: " + factorial);
        scanner.close();
    }
}
15

"while" vs "do-while" loops

while Loop

  • Checks condition before execution
  • May not execute at all if condition is false
while (condition) {
    // loop body
}

do-while Loop

  • Checks condition after execution
  • Executes at least once even if condition is false
do {
    // loop body
} while (condition);
16

Find array length in Java

Use the length property:

public class ArrayLengthExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int length = numbers.length;
        System.out.println("Array length: " + length);
    }
}
17

POP vs OOP

Procedure-Oriented Programming (POP)

  • Focus: Procedures/functions that operate on data
  • Data Handling: Data and functions are separate
  • Reusability: Achieved through functions
  • Extensibility: Requires modifying functions

Object-Oriented Programming (OOP)

  • Focus: Objects encapsulating data and behavior
  • Data Handling: Data and methods encapsulated together
  • Reusability: Through inheritance and polymorphism
  • Extensibility: Create new classes without modifying existing
18

Inheritance in Java

Basic Concept

Allows a subclass to inherit properties and behaviors from a superclass. The subclass can reuse and extend functionalities.

Promotes Code Reuse

Subclasses inherit attributes and methods without rewriting them.

// Superclass
class Vehicle {
    void start() {
        System.out.println("Vehicle starting");
    }
}

// Subclass
class Car extends Vehicle {
    // Inherits start() method
    void drive() {
        System.out.println("Car driving");
    }
}
19

Creating objects in Java

Process

  1. Define a class blueprint
  2. Create instance using new keyword
  3. Access properties and methods
class Dog {
    String breed;
    int age;
    
    void bark() {
        System.out.println("Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        // Object creation
        Dog myDog = new Dog();
        myDog.breed = "Labrador";
        myDog.age = 3;
        myDog.bark(); // Outputs "Woof!"
    }
}
20

Access Modifiers in Java

public

Broadest visibility. Accessible from any class.

private

Restricted to same class. Encapsulates implementation.

protected

Access within same package and subclasses.

default

Package-private. Accessible only within same package.

21

"static" keyword in Java

Purpose: Declares members that belong to the class rather than instances. Only one copy exists, shared by all instances.

Static Variable Example

public class Example {
    static int count = 0;
    
    public static void main(String[] args) {
        Example obj1 = new Example();
        Example obj2 = new Example();
        obj1.count = 5;
        System.out.println(obj2.count); // Outputs 5
    }
}

Static Method Example

public class MathUtil {
    static int square(int num) {
        return num * num;
    }
    
    public static void main(String[] args) {
        int result = MathUtil.square(5); // 25
    }
}
22

"this" keyword in Java

Definition: Refers to the current instance of the class.

Significance: Differentiates instance variables from local variables with same names.

public class Student {
    String name; // Instance variable
    
    public void setName(String name) { // Local variable
        // Use "this" to refer to instance variable
        this.name = name;
    }
}
23

Method overloading in Java

Definition: Multiple methods with same name but different parameters.

public class Calculator {
    // Add two integers
    int add(int a, int b) {
        return a + b;
    }
    
    // Add three integers (overloaded)
    int add(int a, int b, int c) {
        return a + b + c;
    }
    
    // Add two doubles (overloaded)
    double add(double a, double b) {
        return a + b;
    }
}
24

Types of inheritance in Java

Single Inheritance

Class inherits from one superclass

class A {}
class B extends A {}

Multiple Inheritance

Achieved through interfaces

interface A {}
interface B {}
class C implements A, B {}

Multilevel Inheritance

Chain of inheritance

class A {}
class B extends A {}
class C extends B {}

Hierarchical Inheritance

Multiple classes inherit from one superclass

class A {}
class B extends A {}
class C extends A {}
25

Method overriding in Java

Definition: Subclass provides specific implementation for a method already defined in its superclass.

class Animal {
    void makeSound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        myDog.makeSound(); // Outputs "Woof!"
    }
}
26

Interface in Java

Definition: Collection of abstract methods that define a contract for implementing classes.

interface Shape {
    double calculateArea(); // Abstract method
    void display(); // Abstract method
}

class Circle implements Shape {
    private double radius;
    
    Circle(double radius) {
        this.radius = radius;
    }
    
    @Override
    public double calculateArea() {
        return Math.PI * radius * radius;
    }
    
    @Override
    public void display() {
        System.out.println("Circle with radius: " + radius);
    }
}
27

Implementing an interface

  1. Declaration: Define interface with abstract methods
  2. Implementation: Use implements keyword in class
  3. Override Methods: Provide concrete implementations for all interface methods
28

Abstract vs Final classes

Abstract Classes

  • Can be extended
  • May contain abstract methods
  • Can be modified by subclasses

Final Classes

  • Cannot be extended
  • Cannot have abstract methods
  • Implementation is immutable
29

Package in Java

Definition: Mechanism for organizing related classes/interfaces into a single unit.

  • Organization: Groups related classes, avoids naming conflicts
  • Access Control: Controls visibility of classes (default vs public)
30

Compile and execute package program

Compile

javac -d . filename.java

Execute

java packageName.className
31

Exceptions in Java

Definition: Objects representing errors during program execution.

Role: Handle runtime errors gracefully, prevent abrupt termination, and separate error handling from main logic.

32

try...catch statement

Basic Structure:

try {
    // Code that may throw exception
} catch (ExceptionType e) {
    // Handle exception
} finally {
    // Always executes
}

Example:

public class Example {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            System.out.println("Finally block executed");
        }
    }
}
33

Multiple catch blocks

Handle different exception types separately:

try {
    // Code that may throw exceptions
} catch (IOException e) {
    System.out.println("IO error");
} catch (SQLException e) {
    System.out.println("Database error");
} catch (Exception e) {
    System.out.println("General error");
}
34

"throw" vs "throws"

throw

Explicitly throw an exception within method

throw new Exception("Error message");

throws

Declare exceptions a method may throw

void myMethod() throws IOException, SQLException {
    // method body
}
35

"finally" clause

Purpose: Define code that always executes, regardless of exceptions.

Use Cases: Cleanup tasks, releasing resources (files, DB connections).

Guaranteed Execution: Runs even if exception occurs or not.

36

Thread in Java

Definition: Smallest unit of execution within a process. Lightweight, independent path that runs concurrently.

  • Concurrency: Enables parallel execution of tasks
  • Creation: Extend Thread class or implement Runnable interface

Java Programming FAQ | Complete Reference Guide

Post a Comment

0 Comments