History and key features of Java

Java was not designed in a vacuum. Every famous “feature of Java” is an answer to a real problem that programmers faced in the 1990s. In this lesson you'll follow Java from a small team's experiment in 1991 to Java 25, learn each feature with the problem it solves, and watch the JVM catch a bug that C would miss.

Module 1 · Introduction to Java⏱ 18 minBeginnerNo install needed8 practice problems
1 The story

The viva question Riya couldn't explain

Lab viva day. The external examiner asked Riya, “List the features of Java.” She rattled off the list she had memorised: simple, object-oriented, robust, secure… Then came the follow-up: “Why is Java called robust?” Silence. After the viva she finds Arjun Sir in the staff room.

Many different chips TV boxes, phones, PCs: each needed its own build *p = 99; Memory bugs C/C++ pointer mistakes caused crashes and leaks The internet arrives code downloaded from strangers must be safe Java's design answers ✓ Portable bytecode + JVM ✓ Robust: no raw pointers ✓ Secure: verified code ✓ Network-ready libraries myphatshala.in
Riya

Sir, I knew all eleven words! But when he asked why Java is robust, I had nothing. They're just buzzwords to me.

Arjun Sir

That's because you learnt the answers without the questions. In 1991 programmers had three big headaches: too many different chips, programs crashing from memory bugs, and code starting to travel over networks. Each Java feature is a cure for one of those.

Riya

So “robust” isn't just a fancy word for “strong”?

Arjun Sir

Not at all. It means the JVM catches your mistakes before they silently damage memory. Let's start with where Java came from, then I'll show you the JVM catching a real bug.

2 Definition

Java's history and features in one place

Formal definition (write this in exams)

Java was developed by James Gosling and his team at Sun Microsystems, starting in 1991 as the Green Project. It was first called Oak, renamed Java in 1995, and released as JDK 1.0 in January 1996. Its key features, often called the Java buzzwords, are: simple, object-oriented, distributed, robust, secure, architecture-neutral, portable, interpreted, high-performance, multithreaded and dynamic.

In simple words

A small team at Sun wanted one language that could run on all kinds of gadgets safely. They took the good parts of C and C++, removed the dangerous parts, and added a translator (the JVM) on every machine. The “features of Java” are simply the list of promises that design gives you.

Words you'll meet in this lesson

Green ProjectSun's 1991 research project that created Java, led by James Gosling.
BuzzwordsThe official list of Java's features, from Sun's original Java white paper.
PointerA variable holding a raw memory address. C uses them freely; Java hides them.
Garbage collector (GC)Part of the JVM that frees memory you no longer use, automatically.
ThreadOne path of execution. Several threads let a program do many jobs at once.
LTSLong-Term Support: a Java version that gets updates for many years. Companies prefer these.

Java's history at a glance

StartedJune 1991, the Green Project at Sun Microsystems
TeamJames Gosling (called the “father of Java”), Mike Sheridan and Patrick Naughton
First nameOak, after an oak tree outside Gosling's office. Renamed because the name Oak was already taken as a trademark.
Why “Java”Named after Java coffee, which comes from the island of Java in Indonesia
Announced23 May 1995, at the SunWorld conference
First releaseJDK 1.0, 23 January 1996
Open-sourcedSun began releasing Java as open source (OpenJDK) in 2006–2007
Owner todayOracle, which completed its purchase of Sun Microsystems in January 2010
Release patternSince Java 10 (2018): a new version every March and September. LTS versions: 8, 11, 17, 21, 25

Exam tip: The white paper lists 11 buzzwords. Many Indian textbooks and university papers list 12 features by adding platform independent as a separate point. Write 12 to be safe, and for each one add one line on how Java achieves it. That line is what earns the marks.

3 Types and ways to use it

The 12 features of Java, grouped by the problem they solve

Learning twelve words in a row is hard. Learning four problems is easy, and each problem brings its features with it.

Problem: too many machines

Platform independent, architecture neutral, portable. Compile once to bytecode, and the JVM on each machine runs it.

Runs anywhere

Problem: crashes and attacks

Robust and secure. No raw pointers, automatic memory cleanup, checked array access and verified bytecode.

Safe by design

Problem: speed

Interpreted, high performance and multithreaded. The JVM interprets bytecode, its JIT compiles busy code to machine code, and threads do many jobs at once.

Fast enough for banks

Problem: building big systems

Simple, object-oriented, distributed and dynamic. Familiar syntax, code organised as objects, built-in networking, and classes loaded when needed.

Teams and networks

Every feature: what it means and how Java achieves it

FeatureWhat it meansHow Java does it
1. SimpleEasy to learn if you know C/C++Same C-style syntax, but removed explicit pointers, operator overloading, multiple inheritance of classes and manual free(). (goto is a reserved word but unused.)
2. Object-orientedPrograms are built from objects that hold data and behaviourAll code lives inside classes. Supports encapsulation, inheritance, polymorphism and abstraction (Module 5).
3. Platform independentThe same compiled program runs on any OSjavac produces bytecode, not machine code. Any machine with a JVM runs it.
4. Architecture neutralCompiled code is not tied to any CPU typeBytecode instructions are for the JVM, not for Intel, AMD or ARM chips.
5. PortableResults are the same everywhereSizes are fixed by the language: an int is always 32 bits and a char 16 bits on every machine. In C, sizes can vary by compiler and machine.
6. RobustPrograms don't silently corrupt memory or leak itStrong type checking, no pointer arithmetic, array bounds checks, garbage collection and exception handling.
7. SecureUntrusted code can't easily harm your machineNo raw memory access, the bytecode verifier checks every class before it runs, and the class loader keeps classes separated.
8. InterpretedBytecode is executed by the JVMThe JVM's interpreter runs bytecode one instruction at a time, so there's no separate build per machine.
9. High performanceFast, despite the extra JVM layerThe JIT (just-in-time) compiler turns frequently used bytecode into native machine code while the program runs.
10. MultithreadedCan do many tasks at the same timeThreads are built into the language and libraries (Thread, and virtual threads since Java 21).
11. DistributedPrograms can work across a networkBuilt-in networking (java.net, HTTP client) and RMI let programs on different computers talk.
12. DynamicCan adapt while runningClasses are loaded only when first needed, and new classes (plugins) can be loaded at run time.

Memory trick: “Simple Objects Pass All Papers; Robust Secure Indians Have Many Distributed Dreams.” The first letters follow the table order.

4 Step by step

How Java grew: from Oak to Java 25

Each step shows what changed for programmers, and what changed behind the screen inside the JDK and JVM.

  1. 1991: The Green Project creates Oak

    James Gosling, Mike Sheridan and Patrick Naughton start a secret project at Sun to build software for smart consumer devices. Gosling designs a new language for it, called Oak.

    Consumer devices used many different chips. Rewriting C++ code for each chip was slow and error-prone, so Oak was compiled to an intermediate code that a small interpreter on each device could run. This is the seed of today's bytecode and JVM.
  2. 1992: The first demo device

    The team shows a handheld controller prototype called *7 (“Star Seven”), running Oak. The device never became a product.

    The demo proved the idea worked: one program, an interpreter on the device, and no rebuilding for its chip.
  3. 1995: Renamed Java, aimed at the internet

    The consumer-device market didn't take off, but the World Wide Web did. The language is renamed Java and announced on 23 May 1995, along with a web browser that could run small Java programs called applets.

    Applets meant running code downloaded from unknown websites. That's why the bytecode verifier and the sandbox were built in from the start. Browser applets were dropped years later, but the safety design stayed.
  4. 1996–2000: JDK 1.0, then “Java 2”

    JDK 1.0 ships in January 1996. J2SE 1.2 (1998) is branded “Java 2” and adds the Collections framework and Swing for desktop windows. J2SE 1.3 (2000) makes HotSpot the default JVM.

    Early JVMs mostly interpreted bytecode, so Java was called slow. JIT compilers became standard around Java 2, and HotSpot finds the “hot” (busy) methods and compiles them to machine code. That's how “interpreted” and “high performance” can both be true.
  5. 2004: Java 5, the big language upgrade

    Generics, the enhanced for-each loop, autoboxing, enums and annotations. The version name jumps from 1.4 to 5.0.

    Generics are checked by javac and then erased from the bytecode (called type erasure). So new code still ran on the same kind of JVM, and old programs kept working.
  6. 2006–2010: Open source, then Oracle

    Sun releases Java's source code as OpenJDK (2006–2007). Oracle buys Sun and takes over Java in January 2010.

    OpenJDK is now the shared source code that almost every JDK is built from, including Oracle JDK, Eclipse Temurin and Amazon Corretto. That's why they all behave the same.
  7. 2014: Java 8, lambdas and streams

    Java 8 adds lambda expressions, the Stream API and a new date-and-time library. It became one of the most widely used Java versions ever.

    Lambdas are compiled using a bytecode instruction called invokedynamic, which lets the JVM decide at run time how to build the lambda object. This is the “dynamic” feature at work.
  8. 2017–2018: Modules and a faster release train

    Java 9 adds the module system and JShell, an interactive Java prompt. From Java 10 (March 2018), a new version comes every six months. Java 11 (September 2018) is an LTS release.

    The JDK itself was split into modules, such as java.base, so smaller runtimes can be built that contain only the modules an application needs.
  9. 2021–2025: Modern Java LTS versions

    Java 17 (2021), Java 21 (2023, with virtual threads) and Java 25 (2025, with a simpler main method for beginners). LTS versions now come every two years.

    Virtual threads are lightweight threads managed by the JVM rather than the operating system. One server can run millions of them, which makes “multithreaded” much cheaper than before.
5 See it happen

“Robust and secure” in action: one bug, two languages

Riya stores 3 marks in an array, then makes a classic mistake: she writes to position 3, which doesn't exist (positions are 0, 1 and 2). Press Play to see what C does with this bug and what Java does.

Writing past the end of an array 6 steps
What you see Main.java int[] marks = {78, 85, 92}; marks[3] = 99; // oops! System.out.println("Saved"); 78 85 92 99? [0][1][2][3] ✗ Only 3 boxes exist. Box [3] is not part of the array. The same bug in C int marks[3] = {78, 85, 92}; int total = 0; marks[3] = 99; printf("Saved"); $ ./marks Saved No error message! The bug is hidden. It may cause wrong results or a crash much later, far from this line. Now in Java > java Main Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 at Main.main(Main.java:4) Stopped immediately, at the exact line “Saved” is never printed, because the program does not continue with bad data. try { marks[3] = 99; } catch (ArrayIndexOutOf... e) { System.out.println("Caught: " + e...); } > java Main Caught: Index 3 out of bounds for length 3 Program still running! The program catches the problem and carries on marks = null; // done with the array System.out.println("Done"); Done Nothing special on screen… and Riya never wrote any free() code. Look at the right side → Robust and secure Mistake reported at the exact line Neighbouring memory never touched Program can catch it and continue Unused memory cleaned automatically myphatshala.in
Behind the screen STACK HEAP main() frame marks→ int[] object length = 3stored inside 78 85 92 A Java array is an object in the heap. It always remembers its own length. The variable marks holds only a reference (→). C: raw memory, side by side 78marks[0] 85marks[1] 92marks[2] 99 ?!next in memory C simply calculates an address: start of marks + 3 × 4 bytes and writes 99 there. It never checks the size. Whatever sits next to the array (another variable, or nothing valid) gets overwritten. iastore store 99 at index 3 Is 3 < length 3 ? JVM checks every time No Stop! Create an ArrayIndexOutOf… exception object Nothing is written 78, 85, 92 and neighbours stay safe No catch block → JVM prints the error, with the line number, and stops this thread. STACK HEAP main() frame marks→ e→ int[] {78, 85, 92} ArrayIndexOutOf…Exception message: "Index 3 out of…" javac wrote an exception table into Main.class: if this error happens inside try, jump to the catch block. The JVM jumps there and e points to the error. STACK HEAP main() frame marksnull int[] {78, 85, 92} nobody points here Garbage collector The array is now unreachable. The GC frees its memory automatically, later. No free(), no forgotten memory, no leaks of this kind. javac: type checks before runningint x = "hello" is rejected Bytecode verifier: checks every classtampered .class files are refused JVM checks: array bounds, null, castsno raw pointers, no address arithmetic Garbage collector: frees memoryno manual free() Exceptions: errors you can catchtry / catch / finally myphatshala.in

Java vs C vs C++: which features each one has

FeatureCC++Java
Object-orientedNo (procedural)Yes (optional)Yes (all code inside classes)
Explicit pointersYesYesNo (references only)
Memory cleanupManual free()Manual delete or smart pointersAutomatic garbage collector
Array bounds checkedNoNo (for plain arrays)Yes, always
Compiled program runs on another OSOnly after recompilingOnly after recompilingYes, same bytecode
Multiple inheritance of classesNot applicableYesNo (uses interfaces instead)
Built-in threadsThrough libraries (optional since C11)Since C++11Since Java 1.0
6 Real-world use

Java's features at work in real systems

Features matter because real systems depend on them. Here's where each group of features shows up.

Watch it with an example: Tatkal booking at 10 AM

Three people book at the same second. See why multithreading (one of Java's key features) matters, and how Java stops two people getting the same seat.

Three bookings at the same second 5 steps
Animated example Asha Ravi Meena Booking server (one JVM) One thread: one request at a time Asha 1s Ravi 1s Meena 1s Meena waits 3 seconds. Three threads work together thread 1: Asha thread 2: Ravi thread 3: Meena seats left 2 0 synchronized update Asha ✓ Ravi ✓ Meena: waitlist myphatshala.in
same .jar

1. Build on a laptop, run on a server (platform independent)

Developers often write and test on Windows or Mac laptops, while the application runs in production on Linux servers or in the cloud. The same compiled .jar file goes to both, with no rebuild for the server.

Developer laptop→same .jar file→Linux server / cloud

2. Ticket booking at peak time (multithreaded)

When a booking window opens, thousands of people try to book at once. A Java backend handles each request on its own thread, and carefully controls the step that reserves a seat so two people can't get the same one.

Many users→One thread per request→Seat locked safely→Ticket
up for months

3. Servers that run for months (robust)

Payment and banking services run day and night. Because the garbage collector frees unused memory and bad array access is stopped at once, slow memory leaks and silent memory corruption, two common causes of long-running crashes in C programs, are far less likely.

Millions of requests→GC cleans up continuously→Service stays up

4. Bank cards and SIM cards (secure)

The chip in many bank and SIM cards runs Java Card. Applets on the chip are kept separate from each other by a firewall, so one applet can't read another's secret keys.

Card tapped→Isolated Java Card applet→Keys never leave the chip

5. Services talking over a network (distributed)

Large apps are often split into small services: one for login, one for payments, one for notifications. Java's built-in networking and HTTP client let these services call each other across machines.

Order service→HTTP call over network→Payment service

6. Plugins and mods (dynamic)

IDEs such as IntelliJ IDEA and Eclipse let you install plugins without reinstalling the editor. Java game mods work in a similar way. The JVM loads the new classes while the program is running.

Install plugin→Class loader loads new .class files→New feature appears
20142025

7. Old code still running (backward compatibility)

Many organisations have Java code written a decade or more ago. Because Java takes backward compatibility seriously, much of it runs on new JVMs with few or no changes, and gets the newer JVM's speed improvements for free.

Code compiled for Java 8→Runs on a Java 21 or 25 JVM→Faster GC and JIT

Examples are simplified to show where each feature fits. Each company's exact technology choices vary.

7 Run the code

See three features with your own eyes

This program shows platform independence and robustness in a few lines. Read the notes, then try the challenges in the live editor.

public class Main {
    public static void main(String[] args) {
        // Platform independent: the same code asks "where am I?"
        System.out.println("Running on: " + System.getProperty("os.name"));
        System.out.println("Java version: " + Runtime.version().feature());

        // Robust: Java checks every array index
        int[] marks = {78, 85, 92};
        try {
            System.out.println(marks[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Caught: " + e.getMessage());
        }
        System.out.println("Program still running!");
    }
}
Running on: Linux Java version: 21 Caught: Index 3 out of bounds for length 3 Program still running!

The first two lines depend on the machine. On a Windows laptop you might see Running on: Windows 11, and the version number is whatever JDK is installed. The same Main.class works on both.

  • System.getProperty("os.name")Asks the JVM which operating system it's running on. The code doesn't change, only the answer does.
  • Runtime.version().feature()Returns the main Java version number, such as 17, 21 or 25.
  • int[] marks = {78, 85, 92};An array of 3 whole numbers at positions 0, 1 and 2. Arrays get their own lesson in Module 4.
  • try { … }“Try this code, and watch for errors.” Exceptions are covered fully in Module 7.
  • catch (ArrayIndexOutOfBoundsException e)“If this kind of error happens, run this block instead of crashing.” e holds the details.
  • e.getMessage()The error's message: Index 3 out of bounds for length 3.
8 Line by line

Watch the JVM catch the bug

Step through the program and watch the stack (methods and their variables) and the heap (objects). You'll see the array, the exception object and the garbage collector's moment.

Worked examples: real problems, solved and traced in memory

Three programs that show Java's famous features at work: robust (errors are caught, not crashes), strongly typed (sizes of numbers are fixed on every machine) and automatic memory management (unused objects are cleaned up for you).

Example 1Cinema · bookings

A wrong seat number doesn't crash the kiosk

Problem statement

A cinema kiosk stores the prices of 3 seat classes in an array. A customer asks for class number 5, which doesn't exist. The kiosk must show a friendly message instead of crashing. Java's exception handling makes this possible.

Input
prices {150, 220, 350}; customer asks for class index 5
Expected output
Sorry, seat class 5 does not exist.
Kiosk still running. Classes available: 3

Approach

  1. Store the prices in an array.
  2. Read the requested price inside try.
  3. If the index is outside the array, Java throws ArrayIndexOutOfBoundsException; catch it and print a message.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 2Retail · revenue

Yearly revenue that's too big for an int

Problem statement

A retail chain earns about Rs 9,50,00,000 a day. Compute the yearly revenue. An int is exactly 32 bits on every computer (a Java feature), so its limit is the same everywhere: it overflows. Use long.

Input
daily revenue 95000000, 365 days
Expected output
int result:  315261632
long result: 34675000000
int limit:   2147483647

Approach

  1. Multiply with int and see the wrong (overflowed) answer.
  2. Multiply with long (64 bits) for the right answer.
  3. Print Integer.MAX_VALUE to see the limit.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 3Memory · garbage collection

Old messages are cleaned up automatically

Problem statement

A notice board app keeps one current message in a variable. Each time the message changes, the old String is no longer used. Java's garbage collector frees such objects automatically; you never call free() or delete.

Input
three notices in a row
Expected output
Canteen opens at 8
Canteen opens at 9 today
No notice. Is it null? true

Approach

  1. Assign a first notice to notice.
  2. Assign a new String twice; the older objects lose their reference.
  3. Watch the heap: unreachable objects are eligible for garbage collection.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

9 Quiz and revision

Check yourself

Quick revision

Lesson 1.2 in one screen

  • 1991 Green Project at Sun (Gosling, Sheridan, Naughton) → language called Oak.
  • 1995 renamed Java and announced (23 May) · 1996 JDK 1.0 · 2004 Java 5 (generics) · 2010 Oracle buys Sun · 2014 Java 8 (lambdas, streams).
  • Since 2018: a new version every 6 months. LTS: 8, 11, 17, 21, 25.
  • 12 features: simple, object-oriented, platform independent, architecture neutral, portable, robust, secure, interpreted, high performance, multithreaded, distributed, dynamic.
  • Robust = strong typing + no pointer arithmetic + bounds checks + GC + exceptions.
  • Secure = no raw memory access + bytecode verifier + class loader separation.
  • Interpreted and high performance together = interpreter + JIT compiler.

Interview and viva questions

Why is Java called robust?

Because it stops many errors early instead of letting them silently damage memory. javac does strong type checking, there's no pointer arithmetic, the JVM checks every array index, the garbage collector manages memory, and exception handling lets programs recover from errors.

Why doesn't Java support pointers?

Pointers let a program read or write any memory address, which causes crashes and security holes. Java uses references instead: they point to objects, but you can't do arithmetic on them or turn a number into one. The JVM manages the real addresses, and can even move objects around during garbage collection.

What's the difference between platform independent, architecture neutral and portable?

Architecture neutral: bytecode isn't tied to any CPU. Platform independent: the compiled program runs on any OS that has a JVM. Portable: it behaves the same everywhere too, because things like data-type sizes are fixed by the language. The first two are about running. Portable is about getting the same result.

Is Java 100% object-oriented?

No. It has 8 primitive types (byte, short, int, long, float, double, char, boolean) that are not objects, and static members belong to the class rather than any object. Wrapper classes such as Integer exist when you need an object version.

My textbook mentions the Security Manager. Is it still part of Java?

No longer in practice. The Security Manager was deprecated in Java 17 and permanently disabled in Java 24. Today Java's security rests on the bytecode verifier, the lack of raw memory access, the class loaders, and secure libraries for cryptography and TLS. For exams, mention the verifier and class loader first.

Which Java version should I learn in 2026?

Learn on a recent LTS version: Java 21 or Java 25. Everything in this course works on Java 21. Many companies still run Java 8, 11 or 17, but the basics are the same, so what you learn carries over.

Practice problems

Small programs that touch Java's features: safe error handling, fixed-size types and strings. Every output is fixed. The last three are business tasks.

P1Easy

Java's age

Java was released in 1995. Print how old Java is in 2026.

Input
1995, 2026
Expected output
Java is 31 years old
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int born = 1995;
        int now = 2026;
        System.out.println("Java is " + (now - born) + " years old");
    }
}
Java is 31 years old

How it works: brackets make the subtraction happen before joining with text.

P2Easy

Limits of int and long

Print the largest values an int and a long can hold.

Input
(none)
Expected output
int max:  2147483647
long max: 9223372036854775807
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        System.out.println("int max:  " + Integer.MAX_VALUE);
        System.out.println("long max: " + Long.MAX_VALUE);
    }
}
int max: 2147483647 long max: 9223372036854775807

How it works: these limits are the same on every computer, which is part of Java's portability.

P3Easy

Catch a division by zero

Divide 100 by 0 inside try/catch and print a friendly message.

Input
100 / 0
Expected output
Cannot divide by zero
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        try {
            System.out.println(100 / 0);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        }
    }
}
Cannot divide by zero

How it works: Java turns the error into an exception object you can catch, instead of crashing the whole program.

P4Medium

Overflow you can see

Add 1 to Integer.MAX_VALUE and print the result.

Input
2147483647 + 1
Expected output
-2147483648
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int big = Integer.MAX_VALUE;
        big = big + 1;
        System.out.println(big);
    }
}
-2147483648

How it works: an int wraps around to its minimum value. Use long when values can get this large.

P5Medium

Length of a message

Print the number of characters in "Write once, run anywhere".

Input
the slogan
Expected output
24
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        String slogan = "Write once, run anywhere";
        System.out.println(slogan.length());
    }
}
24

How it works: spaces and commas count as characters.

P6Business problem

Safe price lookup

Prices of 4 products are in an array. Look up product 2, then product 9 safely.

Input
{99, 149, 249, 399}; indexes 2 and 9
Expected output
Product 2: Rs 249
Product not found
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int[] prices = {99, 149, 249, 399};
        try {
            System.out.println("Product 2: Rs " + prices[2]);
            System.out.println("Product 9: Rs " + prices[9]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Product not found");
        }
    }
}
Product 2: Rs 249 Product not found

How it works: the first line prints; the second throws, so the rest of the try is skipped and the catch runs.

P7Business problem

Population in long

India's population is about 1,45,00,00,000. Store it and print it divided across 28 states (whole number).

Input
1450000000, 28
Expected output
Average per state: 51785714
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        long population = 1450000000L;
        System.out.println("Average per state: " + population / 28);
    }
}
Average per state: 51785714

How it works: 1,450,000,000 fits in an int, but just barely; using long with the L suffix leaves room for growth. (Approximate figure.)

P8Business problem

Monthly salary bill

A company has 1,200 employees with an average salary of Rs 45,000. Print the monthly and yearly salary bill using long.

Input
1200, 45000
Expected output
Monthly: Rs 54000000
Yearly:  Rs 648000000
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        long monthly = 1200L * 45000;
        long yearly = monthly * 12;
        System.out.println("Monthly: Rs " + monthly);
        System.out.println("Yearly:  Rs " + yearly);
    }
}
Monthly: Rs 54000000 Yearly: Rs 648000000

How it works: the yearly total, 64,80,00,000, still fits in an int, but bigger companies would overflow. Payroll code always uses long (or BigDecimal) for money totals.

Real-world scenario questions (asked in company interviews)

In company interviews, Java's features come up as real situations, not definitions. Each scenario below tests one feature from this lesson. Decide your answer first, then open the model answer.

Bank / insurance · legacy system1–3 years

Moving a ten-year-old app from Java 8 to Java 21

Your company runs a claims-processing application on Java 8. Management wants to move it to Java 21 for security updates and better performance. Your manager asks: “Java is backward compatible, so this is just a version change, right? How would you plan it?”

The interviewer is checking: do you know that “backward compatible” doesn't mean “zero changes”, and can you plan a safe upgrade?

Show a strong answer

Most Java 8 code runs on Java 21 unchanged, but a few things commonly break, so I'd plan it as a small project:

  1. Removed modules: Java 11 removed the bundled Java EE and CORBA modules, such as JAXB and JAX-WS. If the app uses them, we add them back as normal library dependencies.
  2. JDK internals: since Java 17, code or old libraries that reach into the JDK's internal classes fail. I'd run jdeps --jdk-internals on our jars to find them.
  3. Library upgrades: update frameworks and libraries to versions that support Java 21.
  4. Test and roll out in stages: run the full test suite on Java 21, then a test environment, then production, with a way to roll back.

Avoid saying: “Just change the JDK on the server, it'll work.” That is how production outages start.

E-commerce · flash saleFresher

Two customers bought the last phone

During a flash sale, only one phone was left in stock, but two customers both got an order confirmation. The code that reserves stock looks like this: if (stock > 0) { stock--; confirmOrder(); }. Why did this happen, and how would you fix it?

The interviewer is checking: do you understand that “multithreaded” brings real risks, and do you think beyond a single server?

Show a strong answer

This is a race condition. Each customer's request runs on its own thread. Both threads read stock = 1 at almost the same moment, both pass the if check, and both confirm the order. The check and the update are two separate steps.

  • Inside one JVM, the check and the update must happen as one step, for example in a synchronized method or with AtomicInteger.
  • In real systems, the app runs on several servers, so a lock in one JVM isn't enough. I'd let the database do it atomically: UPDATE products SET stock = stock - 1 WHERE id = ? AND stock > 0, and confirm the order only if exactly one row was updated.
  • I'd also add a load test that fires many buy requests at once to prove the fix.

Avoid: “It rarely happens” or adding Thread.sleep(). Timing tricks hide race conditions; they don't fix them.

SaaS · production supportFresher

An exception in the production logs

Some customers report that their invoice page fails. The production log shows java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 at InvoiceService.java:142. Your lead asks how you'll handle it.

The interviewer is checking: your debugging approach. Do you find the root cause, or just hide the error?

Show a strong answer
  1. Read the stack trace: the type, the message (index 5 on an array of length 5) and the exact line, InvoiceService.java:142. Java's robustness gave us all of this for free.
  2. Find the pattern: which customers fail? Maybe only those with more than a certain number of invoice items.
  3. Reproduce it in a unit test using that kind of data.
  4. Fix the root cause. “Index 5 for length 5” often means an off-by-one loop such as i <= items.length instead of i < items.length, or code that assumed a fixed size.
  5. Keep the test so the bug can't come back, then deploy the fix.

Avoid: wrapping the code in try { … } catch (Exception e) { } and ignoring the error. The page stops failing, but customers silently get wrong invoices.

Any company · code reviewFresher

“Java is secure, so any jar is safe”

You need to read PDF files in your project. A teammate found a jar on an unknown website that does it, and says: “Java is a secure language, so it's fine to add.” Do you agree?

The interviewer is checking: do you know what Java's “secure” feature does and doesn't protect against?

Show a strong answer

No. Java's security features stop memory-level attacks, because there are no raw pointers and the bytecode is verified. They don't stop a library from doing harmful things with our application's permissions, such as reading files or sending data out. (The old Security Manager sandbox is permanently disabled since Java 24.)

  • Use well-known, maintained libraries from trusted repositories such as Maven Central. For PDFs, Apache PDFBox is a common choice.
  • Check the library's licence is allowed for company use.
  • Scan dependencies for known vulnerabilities with tools such as OWASP Dependency-Check or GitHub Dependabot, and keep them updated.

The Log4Shell vulnerability (2021) in Log4j, a very popular Java logging library, showed that even a trusted library can put thousands of companies at risk. Dependencies need care.

Avoid saying: “The JVM protects us from everything.”

Data / reporting teamFresher

Works on my laptop, fails on the server

Your monthly-report job runs fine on your Windows laptop. On the Linux server it fails with java.io.FileNotFoundException: Reports\march.csv (No such file or directory). The file is there, in a folder called reports. A teammate says, “Java is platform independent, so it must be a server problem.”

The interviewer is checking: do you know the difference between Java being portable and your code being portable?

Show a strong answer

The bytecode is fine. The problem is in our code's assumptions about Windows:

  • Path separator: Linux uses /, not \. On Linux, Reports\march.csv is treated as one file name containing a backslash.
  • Letter case: Linux file names are case-sensitive, so Reports and reports are different folders. Windows usually ignores the difference.
  • Fix: build paths with Path.of("reports", "march.csv"), which uses the right separator on each OS, read the base folder from configuration, and use one consistent naming style.

Avoid: blaming the server or Java. Platform independence covers bytecode and data types, not hard-coded paths.