In short
Java is a class-based, statically typed, object-oriented language whose source compiles to platform-neutral bytecode run by the Java Virtual Machine — "write once, run anywhere". It is the default teaching and placement language in most Indian universities after C, and the production language of Indian banking, telecom and services IT: TCS, Infosys, Wipro, Cognizant, Accenture, HCL, Capgemini, Zoho, Flipkart, PhonePe, Paytm and almost every Spring Boot backend hiring in India. University papers examine OOP in Java, exception handling, multithreading, collections and JDBC; GATE CS does not test Java — its programming section is set in C — but TCS NQT, Infosys InfyTQ, Wipro NTH and all product-company rounds test it directly. Interviews concentrate on the JVM, String behaviour, collections internals, equals/hashCode, concurrency and Java 8 streams.
Explained
Platform, JVM and program structure
- JDK > JRE > JVM. JDK = compiler (
javac), tools and JRE; JRE = JVM + standard class libraries; JVM = the engine that executes bytecode. Only the JVM is platform-specific — that is what makes the bytecode portable. - Compile and run:
javac Hello.java→Hello.class(bytecode) →java Helloloads, verifies, links and executes it. From Java 11 a single file can run directly:java Hello.java. - JVM runtime areas: *method area* (class metadata, static fields), *heap* (all objects, shared), *stack* (one per thread, holds frames and local variables), *PC register*, *native method stack*.
- JIT compiler inside the JVM converts hot bytecode to native code at runtime, so long-running Java approaches C-like speed; startup remains slower.
- Entry point:
public static void main(String[] args)—staticso the JVM calls it without creating an object,String[]for command-line arguments. - Rules: one
publicclass per file, named exactly as the file;packagefirst, thenimports, then types. Default package is discouraged. - Current practice: Java 8 is still common in Indian service-company projects; Java 17, 21 and 25 are the long-term-support releases, with 17 and 21 standard in newer Spring Boot work. Release cadence and LTS choices change, so confirm the version a project targets.
Data types, operators and control flow
- Eight primitives:
byte(1 B),short(2 B),int(4 B),long(8 B),float(4 B),double(8 B),char(2 B, UTF-16),boolean(size JVM-dependent). Sizes are fixed by the specification — unlike C, they do not vary by machine. - No unsigned types (except
char); ranges are two's complement and therefore asymmetric — one extra negative value — e.g.intis −2³¹ to 2³¹−1. - Reference types: classes, interfaces, arrays, enums. A reference variable holds an address; the object lives on the heap. Uninitialised fields default to 0 /
false/null; local variables have no default and must be assigned before use. - Widening is automatic (
int → long → float → double); narrowing needs a cast and may lose data.byte b = 5;is allowed (compile-time constant),byte b = i;is not. - Wrapper classes
Integer,Double… wrap primitives; autoboxing/unboxing converts automatically. TheIntegercache holds −128 to 127, so==on boxed values outside that range isfalseeven whenequalsistrue. - Operators: arithmetic, relational, logical (
&&,||short-circuit), bitwise (&,|,^,~), shifts<<,>>(signed),>>>(unsigned right shift — Java-specific), ternary?:,instanceof. - Control flow:
if/else,switch(int, char, String, enum; from Java 14 also arrow-form switch expressions),for, enhancedfor-each,while,do-while,break,continue, labelled break. - Arrays are objects:
int[] a = new int[5];hasa.length(a field, not a method), bounds-checked at runtime withArrayIndexOutOfBoundsException.
Classes, objects and OOP as Java implements it
- Class members: fields, methods, constructors, initialiser blocks, nested classes.
newallocates on the heap and runs the constructor. - Constructors have the class name, no return type; a default no-arg constructor is supplied only if you write none.
this(...)chains constructors,super(...)calls the parent's — either must be the first statement. - Four access levels:
private(class only), default/package-private (same package),protected(package + subclasses),public(everywhere). - **
static:** belongs to the class, one copy shared; static methods cannot usethisor instance members. Static blocks run once at class loading. - **
final:** final variable = constant (must be assigned once), final method = cannot be overridden, final class = cannot be extended (e.g.String, wrapper classes). - Inheritance uses
extends; Java allows single class inheritance only (no multiple inheritance of state) but a class mayimplementmany interfaces — this avoids the diamond problem. - Overloading (compile-time polymorphism): same name, different parameter list, resolved by the compiler. Overriding (runtime polymorphism): same signature in a subclass, resolved by the JVM via dynamic method dispatch. Rules: cannot reduce visibility, cannot throw broader checked exceptions, return type may be covariant.
- Abstract class vs interface: an abstract class may hold state, constructors and concrete methods; an interface declares a contract. Since Java 8 interfaces may have
defaultandstaticmethods, and since Java 9privatemethods; fields in an interface are implicitlypublic static final. - **
Objectmethods** every class inherits:toString(),equals(),hashCode(),getClass(),clone(),finalize()(deprecated),wait/notify/notifyAll. - Records (Java 16+) give immutable data carriers in one line:
record Point(int x, int y) {}auto-generates constructor, accessors,equals,hashCode,toString.
Strings, memory and garbage collection
- **
Stringis immutable and final.** Every "modification" creates a new object — the basis of thread safety, hashing and the string pool. - String pool: literals are interned in the heap's string pool, so
"abc" == "abc"istrue, whilenew String("abc") == "abc"isfalse. Always compare content with.equals(). - **
StringBuilder(not synchronised, fast) andStringBuffer** (synchronised, slower) are mutable; useStringBuilderfor loops — concatenating with+inside a loop is O(n²) in work. - Memory model: primitives and references that are local live on the stack; all objects and their fields live on the heap (young generation: Eden + two survivor spaces; old/tenured generation; Metaspace for class metadata since Java 8).
- Garbage collection reclaims objects with no reachable reference, automatically — no
free()as in C.System.gc()is only a request.finalize()is deprecated; use try-with-resources orCleaner. - Collectors: Serial, Parallel, CMS (removed), G1 GC (default since Java 9), ZGC and Shenandoah for low pause times.
- Memory leaks still happen in Java — static collections that keep growing, unclosed resources, listeners never deregistered.
- Pass by value always. For objects the *reference value* is copied, so a method can mutate the object but cannot make the caller's variable point elsewhere.
Exceptions, collections and generics
- Hierarchy:
Throwable→Error(JVM-level:OutOfMemoryError,StackOverflowError) andException→RuntimeException(unchecked) plus checked exceptions. Checked exceptions must be caught or declared withthrows;throwraises one. (Deeper treatment belongs to exception handling as a topic — here, know the hierarchy and the checked/unchecked split.) - Collections framework (
java.util):Collection→List,Set,Queue;Mapis separate.ArrayList— resizable array, O(1) random access, O(n) middle insert, grows ~50%.LinkedList— doubly linked, O(1) insert/delete at a known node, O(n) access; also aDeque.HashSet/LinkedHashSet/TreeSet— no duplicates; unordered / insertion-ordered / sorted (O(log n), red-black tree).HashMap— key-value, buckets byhash(key); collisions form a linked list that becomes a balanced tree past 8 nodes (Java 8+); default capacity 16, load factor 0.75, rehashes at 12 entries. Allows onenullkey.LinkedHashMap(insertion/access order),TreeMap(sorted, no null key),Hashtable(legacy, synchronised, no nulls),ConcurrentHashMap(thread-safe, segment/bucket-level locking).PriorityQueue(binary heap),ArrayDeque(fast stack/queue, preferred over legacyStack).
- **
equalsandhashCodecontract:** equal objects must have equal hash codes; unequal hash codes imply unequal objects. Override both together or hash-based collections will lose your objects. - Comparable vs Comparator:
Comparable.compareTodefines the natural order inside the class;Comparator.comparedefines an external, pluggable order (Comparator.comparing(Employee::getSalary)). - Generics give compile-time type safety and remove casts; implemented by type erasure, so generic type information is not available at runtime and you cannot write
new T[]. Wildcards:? extends T(read),? super T(write) — the PECS rule. - Iterator vs ListIterator:
Iteratorgoes forward and canremove(); modifying a collection directly while iterating throwsConcurrentModificationException(fail-fast).
Threads, functional features and common libraries
- Thread creation:
extends Thread,implements Runnable(preferred — leaves inheritance free),Callable<V>withExecutorServicefor a return value viaFuture. - Lifecycle: NEW → RUNNABLE (actually running whenever the scheduler picks it —
Thread.Statehas no separate RUNNING value) → (BLOCKED / WAITING / TIMED_WAITING) → TERMINATED.start()creates a new thread and callsrun(); callingrun()directly just executes in the current thread. - Synchronisation:
synchronizedmethods/blocks take an object's monitor;volatileguarantees visibility (not atomicity);java.util.concurrentgivesReentrantLock,AtomicInteger,CountDownLatch,ConcurrentHashMap, thread pools viaExecutors. - Deadlock needs mutual exclusion, hold-and-wait, no preemption and circular wait; avoid by fixed lock ordering or timed locks.
- Java 8 functional features: lambda
(a, b) -> a + b, functional interfaces (Predicate,Function,Consumer,Supplier,@FunctionalInterface), method referencesString::toUpperCase,Optionalto avoidNullPointerException. - Streams: a pipeline of source → intermediate (lazy:
filter,map,sorted,distinct,limit) → terminal (collect,forEach,reduce,count,anyMatch). Streams do not store data and cannot be reused;parallelStream()uses the common ForkJoin pool. - Other staples:
java.io/java.niostreams and files,JDBC(DriverManager,Connection,PreparedStatement,ResultSet) for databases,java.time(LocalDate,LocalDateTime) replacing the oldDate/Calendar. - Build and ecosystem in Indian jobs: Maven or Gradle, JUnit 5, Spring/Spring Boot, Hibernate/JPA, REST APIs, Git — the stack named in most Java job descriptions here.
Key points
- Bytecode - platform-neutral
.classoutput ofjavac; only the JVM is platform-specific. - JDK / JRE / JVM - development kit ⊃ runtime environment ⊃ virtual machine.
- Primitives (8) - byte, short, int, long, float, double, char, boolean; fixed sizes, no unsigned.
- Pass by value - Java copies the value; for objects the copied value is the reference.
- String immutability - every change makes a new object; literals are pooled and compared with
.equals(). - StringBuilder vs StringBuffer - mutable; StringBuffer is synchronised, StringBuilder faster and single-threaded.
- **
static** - one copy per class, nothis, accessible without an object. - **
final** - constant variable, non-overridable method, non-extendable class. - Overloading vs overriding - compile-time (signature) vs runtime (dynamic dispatch).
- No multiple class inheritance - but multiple interfaces;
defaultmethods since Java 8. - Checked vs unchecked - checked must be handled or declared;
RuntimeExceptionandErrorneed not be. - HashMap internals - array of buckets, hash + equals, load factor 0.75, treeify after 8 collisions in a bucket.
- equals/hashCode contract - override both or hash collections misbehave.
- ArrayList vs LinkedList - fast random access vs fast structural change.
- Generics erasure - type checks at compile time only; no generic type to test at runtime.
- Garbage collection - automatic reclamation of unreachable objects; G1 is the default collector.
- **
start()≠run()** -start()spawns a thread;run()is an ordinary call. - Streams and lambdas - declarative data processing; intermediate operations are lazy.
Formulas and examples
byte (8 bits): −128 to 127; int (32 bits): −2,147,483,648 to 2,147,483,647HashMap resize threshold = capacity × load factor (default 16 × 0.75 = 12 entries)ArrayList growth (Java 8+): newCapacity = oldCapacity + (oldCapacity >> 1) ≈ 1.5 × oldBucket index in
HashMap = (n − 1) & hash, where n = table length (a power of 2)Default
hashCode of a String: s[0]×31n−1 + s[1]×31n−2 + … + s[n−1]Amortised cost: ArrayList add = O(1) amortised, get = O(1); LinkedList add at ends = O(1), get(i) = O(n)
Example 1 — String hashCode, computed fully. For "Ab": n = 2, 'A' = 65, 'b' = 98. hash = 65 × 31¹ + 98 × 31⁰ = 2015 + 98 = 2113. For "BC": 'B' = 66, 'C' = 67 → 66 × 31 + 67 = 2046 + 67 = 2113. Same hash, different strings — a genuine collision, which is exactly why HashMap also calls equals() after matching the hash.
Example 2 — HashMap resize count. A HashMap is created with the defaults and 30 distinct keys are inserted.
- Start: capacity 16, threshold = 16 × 0.75 = 12 → at the 13th insert it resizes to 32, threshold = 24.
- At the 25th insert it resizes to 64, threshold = 48.
- 30 entries end in a table of capacity 64, after 2 resizes. Pre-sizing with
new HashMap<>(64)avoids both rehashes.
**Example 3 — Integer caching and ==.**
Integer a = 127, b = 127; // from cache
Integer c = 128, d = 128; // new objects
System.out.println(a == b); // true
System.out.println(c == d); // false
System.out.println(c.equals(d)); // true
int e = 128;
System.out.println(c == e); // true (c is unboxed, value compared)
The cache covers −128 to 127 by default; the upper bound can be raised with -XX:AutoBoxCacheMax.
Example 4 — Pass by value with an object.
static void change(StringBuilder sb, String s) {
sb.append(" World"); // mutates the shared object
s = s + " World"; // rebinds the local copy only
}
public static void main(String[] a) {
StringBuilder sb = new StringBuilder("Hello");
String s = "Hello";
change(sb, s);
System.out.println(sb + " | " + s); // Hello World | Hello
}
Example 5 — Streams over a payroll list. Employees with salaries ₹35,000, ₹52,000, ₹78,000, ₹41,000 and ₹95,000 per month; find the total of those above ₹50,000.
List<Integer> sal = List.of(35000, 52000, 78000, 41000, 95000);
int total = sal.stream().filter(x -> x > 50000).mapToInt(Integer::intValue).sum();
double avg = sal.stream().mapToInt(Integer::intValue).average().orElse(0);
Filtered: 52,000 + 78,000 + 95,000 = ₹2,25,000. Average of all five = 301,000 / 5 = ₹60,200.
| Feature | C++ | Java |
|---|---|---|
| Compilation | To native machine code | To bytecode, run by the JVM |
| Memory | Manual new/delete | Automatic garbage collection |
| Pointers | Full pointer arithmetic | References only, no arithmetic |
| Multiple inheritance | Supported (classes) | Interfaces only |
| Operator overloading | Supported | Not supported (except + for String) |
| Global functions | Allowed | Everything inside a class |
| Collection | Order | Duplicates | Null | Access / insert |
|---|---|---|---|---|
| ArrayList | Insertion | Yes | Yes | get O(1), insert mid O(n) |
| LinkedList | Insertion | Yes | Yes | get O(n), ends O(1) |
| HashSet | None | No | One null | O(1) average |
| TreeSet | Sorted | No | No null | O(log n) |
| HashMap | None | Keys unique | 1 null key | O(1) average |
| TreeMap | Sorted by key | Keys unique | No null key | O(log n) |
Where it is used
- Indian IT services: TCS, Infosys, Wipro, HCLTech, Cognizant, Tech Mahindra, LTIMindtree and Accenture staff most enterprise projects in Java/Spring Boot; Java is the single most common skill in their fresher job descriptions.
- Banking and payments: core banking (Finacle from Infosys, Flexcube from Oracle), UPI and switch layers at NPCI-connected banks, PhonePe, Paytm, Razorpay backends and trading systems at NSE/BSE member firms.
- Android: Java (alongside Kotlin) for app development; Android SDK APIs are Java-shaped.
- Big data and streaming: Hadoop, Spark, Kafka, Elasticsearch and Cassandra are written in Java/Scala and run on the JVM, so JVM tuning is part of data-engineering roles.
- Government and public-sector systems: many state e-governance portals, UIDAI-linked services and PSU applications run Java EE / Spring on Linux.
- Job roles: Java backend developer, full-stack (Java + React/Angular), Android developer, QA automation (Selenium + Java + TestNG), support/maintenance engineer.
Interview questions
- Q: Is Java fully object-oriented? A: No — it has eight primitive types that are not objects, and it supports static members; it is object-oriented but not "pure" like Smalltalk.
- Q: Is Java pass by value or pass by reference? A: Always pass by value; for objects the value copied is the reference, so the method can change the object's state but not the caller's variable binding.
- Q: Why is
Stringimmutable? A: For security (class loading, network parameters), safe sharing across threads, caching of the hash code, and the string pool — an immutable object can be shared without risk. - Q: What is the difference between
==and.equals()? A:==compares references for objects (values for primitives);.equals()compares content as defined by the class. - Q: What happens if you override
equals()but nothashCode()? A: Equal objects may fall into different buckets, soHashMap/HashSetlookups fail — the object seems to disappear from the collection. - Q: How does
HashMapwork internally? A: The key's hash is spread and indexed as(n−1) & hashinto a bucket array; collisions form a linked list that converts to a balanced tree beyond eight nodes; the table doubles when size exceeds capacity × 0.75. - Q: Difference between an abstract class and an interface? A: An abstract class can hold state, constructors and concrete methods and allows single inheritance; an interface is a contract, supports multiple implementation, and since Java 8 can carry
defaultandstaticmethods. - Q:
ArrayListvsLinkedList— which would you choose? A:ArrayListfor frequent random access and iteration (contiguous memory, cache-friendly);LinkedListonly for heavy insertion/deletion at the ends — in practiceArrayDequeusually beats it. - Q: Difference between
start()andrun()? A:start()asks the JVM to create a new thread that then callsrun(); callingrun()directly executes the code on the current thread with no concurrency. - Q: What does
volatileguarantee? A: Visibility and ordering — reads/writes go to main memory — but not atomicity;count++on a volatile variable is still unsafe. - Q: What is type erasure? A: The compiler checks generic types then removes them, replacing them with
Objector the bound, so generics have no runtime representation — hence nonew T[]and noinstanceof List<String>. - Q: Can you have a memory leak in Java despite garbage collection? A: Yes — objects still referenced by a long-lived static collection, cache, or unremoved listener are reachable, so the collector will never free them.
Common mistakes
- Comparing strings with
==instead of.equals(), and assuming the result is the same for literals andnew String(...). - Overriding
equals()withouthashCode(), then wondering whyHashSetholds duplicates. - Believing Java is pass by reference because a mutated object visibly changed in the caller.
- Building strings with
+inside loops instead ofStringBuilder, turning an O(n) job into O(n²). - Calling
run()instead ofstart(), or expectingsynchronizedon different objects to exclude each other. - Removing elements with
list.remove()inside a for-each loop —ConcurrentModificationException; useIterator.remove()orremoveIf(). - Mixing up
length(array field),length()(String method) andsize()(collection method) in exams.
Related topics
Object-oriented programming concepts · Exception handling and debugging · C++ essentials · Functional programming basics · Compilation, linking and memory layout · Python essentials