Showing 50 question(s)

Answer:

Java is a high-level, object-oriented, platform-independent programming language developed by Sun Microsystems (now Oracle). It follows the Write Once, Run Anywhere (WORA) principle.

Code Example:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

Tags:

Answer:

Java is object-oriented, platform-independent, secure, robust, multithreaded, portable, distributed, and has automatic memory management through garbage collection.

Code Example:

// Java Features
Object-Oriented
Platform Independent
Secure
Multithreaded
Robust

Tags:

Answer:

The four pillars of OOP are Encapsulation, Inheritance, Polymorphism, and Abstraction.

Code Example:

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

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Bark");
    }
}

Tags:

Answer:

JVM (Java Virtual Machine) is responsible for executing Java bytecode. It enables Java programs to run on any platform without recompilation.

Code Example:

Java Source Code
       ↓
    Compiler
       ↓
    Bytecode (.class)
       ↓
        JVM
       ↓
 Operating System

Tags:

Answer:

JDK contains development tools, JRE provides the runtime environment, and JVM executes Java bytecode.

Code Example:

JDK
 ├── JRE
 │     └── JVM
 ├── javac
 ├── jar
 └── javadoc

Tags:

Answer:

Instance variables belong to objects, local variables are declared inside methods, and static variables belong to the class and are shared by all objects.

Code Example:

class Student {

    static String college = "ABC";

    String name; // instance variable

    void display() {
        int age = 20; // local variable
    }
}

Tags:

Answer:

Java has eight primitive data types: byte, short, int, long, float, double, char, and boolean.

Code Example:

int age = 25;
double salary = 50000.50;
char grade = 'A';
boolean active = true;

Tags:

Answer:

A constructor is a special method that is automatically called when an object is created. It has the same name as the class and does not have a return type.

Code Example:

class Employee {

    Employee() {
        System.out.println("Constructor Called");
    }
}

Tags:

Answer:

Inheritance allows one class to acquire the properties and methods of another class using the extends keyword, promoting code reuse.

Code Example:

class Animal {
    void eat() {
        System.out.println("Eating...");
    }
}

class Dog extends Animal {

}

Dog d = new Dog();
d.eat();

Tags:

Answer:

Polymorphism allows the same method to behave differently based on the object. It is achieved through method overloading (compile-time) and method overriding (runtime).

Code Example:

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

class Dog extends Animal {

    @Override
    void sound() {
        System.out.println("Bark");
    }
}

Tags:

Answer:

Abstraction is the process of hiding implementation details and exposing only essential functionality. It is achieved using abstract classes and interfaces.

Code Example:

abstract class Animal {
    abstract void sound();
}

class Dog extends Animal {
    void sound() {
        System.out.println("Bark");
    }
}

Tags:

Answer:

Encapsulation is wrapping data and methods into a single unit and restricting direct access to data using private fields and public getter/setter methods.

Code Example:

class Employee {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Tags:

Answer:

An interface defines a contract that classes implement. It supports abstraction and multiple inheritance in Java.

Code Example:

interface Animal {
    void sound();
}

class Dog implements Animal {
    public void sound() {
        System.out.println("Bark");
    }
}

Tags:

Answer:

An abstract class cannot be instantiated and may contain both abstract and concrete methods.

Code Example:

abstract class Shape {
    abstract void draw();

    void display() {
        System.out.println("Shape");
    }
}

Tags:

Answer:

String is immutable. StringBuilder is mutable and not thread-safe. StringBuffer is mutable and thread-safe.

Code Example:

String s = "Java";

StringBuilder sb = new StringBuilder("Java");
sb.append(" 21");

StringBuffer sf = new StringBuffer("Java");

Tags:

Answer:

Exception handling is the mechanism of handling runtime errors using try, catch, finally, throw, and throws.

Code Example:

try {
    int a = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println(e.getMessage());
}

Tags:

Answer:

Checked exceptions are checked at compile time, whereas unchecked exceptions occur at runtime.

Code Example:

// Checked
IOException

// Unchecked
NullPointerException

Tags:

Answer:

The Java Collections Framework provides classes and interfaces for storing and manipulating groups of objects efficiently.

Code Example:

List<String> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();
Map<Integer, String> map = new HashMap<>();

Tags:

Answer:

ArrayList uses a dynamic array and provides fast random access. LinkedList uses a doubly linked list and provides faster insertion and deletion.

Code Example:

List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();

Tags:

Answer:

HashMap is not synchronized and allows one null key. Hashtable is synchronized and does not allow null keys or values.

Code Example:

Map<Integer, String> map = new HashMap<>();

Hashtable<Integer, String> table = new Hashtable<>();

Tags:

Answer:

HashSet stores elements in no particular order, while TreeSet stores elements in sorted order.

Code Example:

Set<Integer> hash = new HashSet<>();
Set<Integer> tree = new TreeSet<>();

Tags:

Answer:

Comparable is an interface used for defining the natural ordering of objects using compareTo().

Code Example:

class Student implements Comparable<Student> {

    public int compareTo(Student s) {
        return this.id - s.id;
    }
}

Tags:

Answer:

Comparator provides custom sorting logic using the compare() method.

Code Example:

Collections.sort(list,
(a, b) -> a.getName().compareTo(b.getName()));

Tags:

Answer:

Multithreading is the process of executing multiple threads simultaneously to improve application performance.

Code Example:

class MyThread extends Thread {
    public void run() {
        System.out.println("Running");
    }
}

Tags:

Answer:

Thread is a class, whereas Runnable is an interface. Implementing Runnable is preferred because Java supports single inheritance.

Code Example:

class Task implements Runnable {

    public void run() {
        System.out.println("Task");
    }
}

Tags:

Answer:

Synchronization prevents multiple threads from accessing shared resources simultaneously, avoiding inconsistent results.

Code Example:

synchronized void display() {
    System.out.println("Thread Safe");
}

Tags:

Answer:

Garbage Collection automatically removes unused objects from memory, helping prevent memory leaks.

Code Example:

System.gc(); // Request JVM to run GC

Tags:

Answer:

Lambda expressions provide a concise way to implement functional interfaces introduced in Java 8.

Code Example:

List<String> names = List.of("A", "B");

names.forEach(name -> System.out.println(name));

Tags:

Answer:

The Stream API processes collections using functional operations like filter(), map(), and reduce().

Code Example:

numbers.stream()
       .filter(n -> n > 10)
       .forEach(System.out::println);

Tags:

Answer:

Optional is a container object introduced in Java 8 to avoid NullPointerException by representing optional values.

Code Example:

Optional<String> name = Optional.of("John");

name.ifPresent(System.out::println);

Tags:

Answer:

Generics enable type safety by allowing classes, interfaces, and methods to work with different data types while avoiding explicit type casting.

Code Example:

List<String> names = new ArrayList<>();
names.add("John");

// No casting required
String name = names.get(0);

Tags:

Answer:

Serialization is the process of converting an object into a byte stream so that it can be stored or transferred over a network.

Code Example:

class Employee implements Serializable {
    private static final long serialVersionUID = 1L;
}

Tags:

Answer:

Deserialization is the process of converting a byte stream back into a Java object.

Code Example:

ObjectInputStream in =
new ObjectInputStream(new FileInputStream("emp.ser"));

Employee emp = (Employee) in.readObject();

Tags:

Answer:

The == operator compares object references, whereas equals() compares object contents if overridden.

Code Example:

String a = new String("Java");
String b = new String("Java");

System.out.println(a == b);      // false
System.out.println(a.equals(b)); // true

Tags:

Answer:

If equals() is overridden, hashCode() should also be overridden to maintain the contract required by hash-based collections like HashMap and HashSet.

Code Example:

@Override
public int hashCode() {
    return Objects.hash(id);
}

Tags:

Answer:

The final keyword is used to restrict modification. A final variable cannot be reassigned, a final method cannot be overridden, and a final class cannot be inherited.

Code Example:

final int MAX = 100;

final class Utility {

}

Tags:

Answer:

The static keyword belongs to the class rather than an object. Static members are shared by all instances.

Code Example:

class Student {

    static String college = "ABC";

    static void display() {

    }
}

Tags:

Answer:

The this keyword refers to the current object. It is used to access instance variables, invoke constructors, and pass the current object.

Code Example:

class Student {

    String name;

    Student(String name) {
        this.name = name;
    }
}

Tags:

Answer:

The super keyword refers to the parent class object. It is used to access parent class methods, variables, and constructors.

Code Example:

class Animal {

    Animal() {
        System.out.println("Animal");
    }
}

class Dog extends Animal {

    Dog() {
        super();
    }
}

Tags:

Answer:

Heap stores objects and instance variables, whereas Stack stores local variables, method calls, and references.

Code Example:

Stack
------
Method Calls
Local Variables

Heap
------
Objects
Arrays

Tags:

Answer:

Annotations provide metadata to the compiler or runtime without changing program logic.

Code Example:

@Override
public String toString() {
    return "Employee";
}

Tags:

Answer:

Reflection allows inspection and manipulation of classes, methods, fields, and constructors at runtime.

Code Example:

Class<?> cls = Class.forName("Employee");

Method[] methods = cls.getDeclaredMethods();

Tags:

Answer:

Fail-fast iterators throw ConcurrentModificationException when the collection is modified during iteration. Fail-safe iterators work on a copy and do not throw this exception.

Code Example:

Iterator<String> itr =
list.iterator();

Tags:

Answer:

ConcurrentHashMap is a thread-safe implementation of Map that allows concurrent read and write operations without locking the entire map.

Code Example:

ConcurrentHashMap<Integer, String> map =
new ConcurrentHashMap<>();

Tags:

Answer:

A Functional Interface contains exactly one abstract method and can be implemented using lambda expressions.

Code Example:

@FunctionalInterface
interface Calculator {
    int add(int a, int b);
}

Tags:

Answer:

Method references provide a shorter syntax for calling existing methods using the :: operator.

Code Example:

List<String> list =
Arrays.asList("A", "B");

list.forEach(System.out::println);

Tags:

Answer:

Default methods allow interfaces to provide method implementations without breaking existing implementations.

Code Example:

interface Vehicle {

    default void start() {
        System.out.println("Started");
    }
}

Tags:

Answer:

Make the class final, declare fields as private and final, initialize them through a constructor, and provide only getter methods.

Code Example:

public final class Employee {

    private final String name;

    public Employee(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

Tags:

Answer:

Use meaningful variable names, follow naming conventions, prefer interfaces over implementations, handle exceptions properly, write reusable methods, use generics, avoid code duplication, and write unit tests.

Code Example:

// Good Practice
List<String> employees =
new ArrayList<>();

Tags:

Answer:

Java is platform-independent, object-oriented, secure, robust, scalable, has excellent performance with the JVM, a rich ecosystem, strong community support, and is widely used in enterprise, web, mobile, and cloud applications.

Code Example:

Advantages of Java

✔ Platform Independent
✔ Object-Oriented
✔ Secure
✔ Robust
✔ Multithreading
✔ Huge Ecosystem
✔ Enterprise Ready

Tags: