Resources / Coding
Free to readCoding⏱ 7 min read

Java for beginners — the essentials

Java basics for service and product company interviews: syntax, OOP, collections and exceptions, with small examples.

Why Java

Java is the most asked language in Indian fresher hiring (TCS, Infosys, Wipro, Accenture, banks). It runs everywhere, it is strict (which catches mistakes early) and its OOP questions appear in almost every interview.

Your first program

📖 Class and object

Definition: A class is a user-defined blueprint that describes the data (fields/attributes) and behaviour (methods) of a type. An object is a concrete instance of a class created at run time, occupying memory and holding its own values.

How it works: Defining a class creates no data. new Order(...) allocates memory for one object, runs the constructor to initialise it, and returns a reference to it. Many objects can be created from one class, each with its own state.

Example: Order is the class; your order #4521 (Biryani, ₹250) and someone else's #4522 are two objects of it.

🧒 In simple words

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

Every Java program starts in main. The file name must match the class name (Main.java).

Variables and types

📖 Variable and data type

Definition: A variable is a name bound to a value stored in memory; a data type defines what kind of value it is and which operations are allowed on it.

How it works: Python is dynamically typed (the type belongs to the value, checked at run time) and strongly typed (it won't silently mix incompatible types like "5" + 3). Built-in types: int, float, str, bool, list, tuple, dict, set, None.

Example: age = 21 binds the name age to an int object; type(age) → <class 'int'>.

🧒 In simple words

TypeExampleNotes
intint age = 21;whole numbers
doubledouble cgpa = 8.4;decimals
booleanboolean placed = false;true / false
charchar grade = 'A';one character
StringString name = "Asha";text (a class, not a primitive)

Conditions and loops

Java
if (marks >= 60) System.out.println("Pass");
else System.out.println("Try again");

for (int i = 1; i <= 5; i++) System.out.print(i + " ");

int n = 3;
while (n > 0) { System.out.println(n); n--; }
▶ Output
(with marks = 72)
Pass
1 2 3 4 5 3
2
1

Methods

Java
static int square(int x) { return x * x; }

OOP — the four pillars (asked in every interview)

📖 Encapsulation

Definition: Encapsulation is the OOP principle of bundling an object's data (fields) and the methods that work on that data into one unit (a class), and restricting direct access to the data from outside.

How it works: Fields are declared private, so other classes can't read or change them directly. Access goes through public methods (getters/setters or business methods like withdraw()), which can validate input and keep the object in a correct state. This is also called data hiding.

Example: A bank account's balance is private; the only way to change it is deposit() or withdraw(), and withdraw() refuses to go below zero.

Java
class Account {
    private int balance;               // hidden
    public void deposit(int amt) { if (amt > 0) balance += amt; }
    public boolean withdraw(int amt) { if (amt > balance) return false; balance -= amt; return true; }
    public int getBalance() { return balance; }
}
📖 Inheritance

Definition: Inheritance is the mechanism by which one class (the child, subclass or derived class) acquires the fields and methods of another class (the parent, superclass or base class), creating an is-a relationship.

How it works: The child declares extends Parent (Java) or class Child(Parent) (Python). It reuses the parent's code, can add new members, and can override parent methods to change behaviour. Java supports single inheritance of classes (one parent) but a class can implement many interfaces. Types: single, multilevel, hierarchical (and multiple via interfaces).

Example: Car extends Vehicle — every Car is a Vehicle, so it gets start() from Vehicle and adds its own openSunroof().

📖 Polymorphism

Definition: Polymorphism (Greek: "many forms") is the ability of one interface — a method name or a reference type — to behave differently depending on the actual object or the arguments used.

How it works: Compile-time (static) polymorphism is method overloading: same method name, different parameter lists; the compiler picks the version. Run-time (dynamic) polymorphism is method overriding: a child class replaces a parent method, and the JVM decides which version to run based on the actual object type (dynamic method dispatch).

Example: A Payment reference can point to a Upi or Card object; calling pay() runs the UPI or card version automatically.

Java
Payment p = new Upi();  p.pay(500);   // UPI version
p = new Card();         p.pay(500);   // Card version
▶ Output
UPI paid 500
Card paid 500 + 2% fee
📖 Abstraction

Definition: Abstraction is the principle of exposing only the essential features of an object (what it does) while hiding the implementation details (how it does it).

How it works: In Java it's achieved with abstract classes (can have both abstract and concrete methods, constructors and state) and interfaces (a contract of methods a class promises to implement). Callers depend on the abstract type, so the implementation can change without breaking them.

Example: You call bookCab(pickup, drop); the matching of drivers, pricing and routing are hidden behind that one method.

🧒 In simple words

PillarMeaningJava example
Encapsulationhide data, expose methodsprivate fields + getters/setters
Inheritancea class reuses anotherclass Car extends Vehicle
Polymorphismone name, many formsmethod overloading / overriding
Abstractionshow what, hide howabstract classes, interfaces
Java
class Animal { void sound() { System.out.println("..."); } }
class Dog extends Animal { @Override void sound() { System.out.println("Woof"); } }

Animal a = new Dog();
a.sound();   // Woof — decided at runtime (polymorphism)
▶ Output
Woof

Collections you must know

NeedUse
ordered listArrayList<Integer>
unique itemsHashSet<String>
key → valueHashMap<String, Integer>
queueArrayDeque / LinkedList
Java
Map<String, Integer> count = new HashMap<>();
for (String w : words) count.put(w, count.getOrDefault(w, 0) + 1);
▶ Output
(words = apple, mango, apple)
{apple=2, mango=1}

Exceptions

📖 Exception handling

Definition: Exception handling is the mechanism for detecting and responding to run-time errors so a program can recover or fail gracefully instead of crashing.

How it works: Code that might fail goes in try; matching except blocks handle specific exception types; else runs if nothing failed; finally always runs (cleanup). You can raise your own exceptions with raise.

Example: Catching ZeroDivisionError when a user enters 0 as the divisor.

🧒 In simple words

Java
try {
    int x = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Can't divide by zero");
} finally {
    System.out.println("Always runs");
}
▶ Output
Can't divide by zero
Always runs

Top interview questions

  • JDK vs JRE vs JVM — JVM runs bytecode, JRE = JVM + libraries, JDK = JRE + compiler and tools.
  • == vs equals() — == compares references, equals() compares values.
  • String vs StringBuilder — String can't change (immutable); StringBuilder is faster for many edits.
  • Overloading vs overriding — same name different parameters (compile time) vs subclass replaces a method (runtime).
  • Interface vs abstract class — a class can implement many interfaces but extend only one class.
  • Why is String immutable? — security, caching (string pool) and thread safety.

Practice next

Write 30 small programs (reverse a string, palindrome, prime, factorial, matrix multiply, bubble sort), then move to our coding interview patterns plan.

Further references

🔥Join the free 30-Day Placement ChallengeOne resource and one task a day — from resume to offer.