Interview Q&A · Java · 9 questions in this topic

Java Basics: Classes, Objects & Platform — Java Interview Q&A

All Java topics

The foundational questions every Java interview opens with — what a class and object are, why main() looks the way it does, and why Java is portable. Part of Core Java Basics · 294 questions in the Java bank.

Why is Java platform independent?

Answer

Java source is compiled to a machine-independent intermediate format called bytecode, not to native machine code. Any device with a Java Virtual Machine (JVM) can execute that same bytecode, so the compiled artifact does not depend on the operating system or CPU it was built on. The trade-off is that the JVM must translate bytecode to native instructions at runtime.

Key points

  1. 1javac turns .java source into .class files containing bytecode.
  2. 2The JVM (or its Just-In-Time compiler) turns bytecode into native instructions for the host machine.
  3. 3The same .class file runs on Windows, macOS, Linux and elsewhere — "write once, run anywhere".
  4. 4Portability lives in the JVM, not in the bytecode being native code.

What is a class?

Answer

A class is a blueprint or template that defines the state (fields) and behaviour (methods) shared by a set of objects. It declares what data an object of that type holds and what operations it supports. In Java every piece of code lives inside a class, and a public class must be saved in a file named exactly after it (for example Hello.java).

Example

Example.javajava
public class Hello {
    private String name;            // state
    public void greet() {           // behaviour
        System.out.println("Hi " + name);
    }
}

What is an object?

Answer

An object is a concrete instance of a class, created with the new keyword. It has its own copy of the instance fields (its state) and can invoke the methods defined by its class (its behaviour). Objects live on the heap; the variable you use to reach one is a reference, not the object itself.

Example

Example.javajava
Hello h = new Hello(); // h is a reference; the Hello instance is the object
h.greet();

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits