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.
Sir, I knew all eleven words! But when he asked why Java is robust, I had nothing. They're just buzzwords to me.
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.
So “robust” isn't just a fancy word for “strong”?
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.
Java's history and features in one place
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.
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
Java's history at a glance
| Started | June 1991, the Green Project at Sun Microsystems |
|---|---|
| Team | James Gosling (called the “father of Java”), Mike Sheridan and Patrick Naughton |
| First name | Oak, 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 |
| Announced | 23 May 1995, at the SunWorld conference |
| First release | JDK 1.0, 23 January 1996 |
| Open-sourced | Sun began releasing Java as open source (OpenJDK) in 2006–2007 |
| Owner today | Oracle, which completed its purchase of Sun Microsystems in January 2010 |
| Release pattern | Since 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.
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 anywhereProblem: crashes and attacks
Robust and secure. No raw pointers, automatic memory cleanup, checked array access and verified bytecode.
Safe by designProblem: 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 banksProblem: 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 networksEvery feature: what it means and how Java achieves it
| Feature | What it means | How Java does it |
|---|---|---|
| 1. Simple | Easy 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-oriented | Programs are built from objects that hold data and behaviour | All code lives inside classes. Supports encapsulation, inheritance, polymorphism and abstraction (Module 5). |
| 3. Platform independent | The same compiled program runs on any OS | javac produces bytecode, not machine code. Any machine with a JVM runs it. |
| 4. Architecture neutral | Compiled code is not tied to any CPU type | Bytecode instructions are for the JVM, not for Intel, AMD or ARM chips. |
| 5. Portable | Results are the same everywhere | Sizes 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. Robust | Programs don't silently corrupt memory or leak it | Strong type checking, no pointer arithmetic, array bounds checks, garbage collection and exception handling. |
| 7. Secure | Untrusted code can't easily harm your machine | No raw memory access, the bytecode verifier checks every class before it runs, and the class loader keeps classes separated. |
| 8. Interpreted | Bytecode is executed by the JVM | The JVM's interpreter runs bytecode one instruction at a time, so there's no separate build per machine. |
| 9. High performance | Fast, despite the extra JVM layer | The JIT (just-in-time) compiler turns frequently used bytecode into native machine code while the program runs. |
| 10. Multithreaded | Can do many tasks at the same time | Threads are built into the language and libraries (Thread, and virtual threads since Java 21). |
| 11. Distributed | Programs can work across a network | Built-in networking (java.net, HTTP client) and RMI let programs on different computers talk. |
| 12. Dynamic | Can adapt while running | Classes 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.
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.
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.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.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.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.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 byjavacand then erased from the bytecode (called type erasure). So new code still ran on the same kind of JVM, and old programs kept working.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.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 calledinvokedynamic, which lets the JVM decide at run time how to build the lambda object. This is the “dynamic” feature at work.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 asjava.base, so smaller runtimes can be built that contain only the modules an application needs.2021–2025: Modern Java LTS versions
Java 17 (2021), Java 21 (2023, with virtual threads) and Java 25 (2025, with a simpler
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.mainmethod for beginners). LTS versions now come every two years.
“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.
- Riya creates an array of 3 marks. The valid positions are 0, 1 and 2. Then she writes
marks[3] = 99by mistake. - In C, the same code usually compiles and runs without any error. The bug stays hidden and can cause trouble much later.
- In Java, the program stops at once with
ArrayIndexOutOfBoundsException, naming the exact line (line 4 of Main.java, themarks[3] = 99line). It never prints “Saved”. - With
try/catch, Riya's program handles the error and keeps running. This is exception handling, one part of being robust. - Riya sets
marks = nullwhen she's done. The screen only shows “Done”, but something important happens behind the screen. - Together, these make Java robust and secure. These are exactly the points to write when an examiner asks “why”.
- In Java, the array is an object in the heap that stores its own length (3). The variable
markson the stack only holds a reference to it. - C has no such safety net. It works out the memory address for position 3 and writes 99 there, onto whatever happens to be next in memory.
- Java's
iastoreinstruction makes the JVM check the index against the length first. 3 is not less than 3, so nothing is written and an exception object is created. - When
javaccompiled thetry/catch, it wrote an exception table into the .class file. The JVM uses it to jump to the catch block, andepoints to the exception object. - After
marks = null, nothing refers to the array. The garbage collector frees that memory on its own. Forgetting to free memory is a common bug in C. - Five safety layers together make Java robust (mistakes don't silently spread) and secure (code can't poke at raw memory).
Java vs C vs C++: which features each one has
| Feature | C | C++ | Java |
|---|---|---|---|
| Object-oriented | No (procedural) | Yes (optional) | Yes (all code inside classes) |
| Explicit pointers | Yes | Yes | No (references only) |
| Memory cleanup | Manual free() | Manual delete or smart pointers | Automatic garbage collector |
| Array bounds checked | No | No (for plain arrays) | Yes, always |
| Compiled program runs on another OS | Only after recompiling | Only after recompiling | Yes, same bytecode |
| Multiple inheritance of classes | Not applicable | Yes | No (uses interfaces instead) |
| Built-in threads | Through libraries (optional since C11) | Since C++11 | Since Java 1.0 |
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.
- 10:00:00 AM: Asha, Ravi and Meena press Book at the same moment. All three requests reach the same booking server.
- Without threads: the server handles one request, then the next. If each takes 1 second, Meena waits 3 seconds. With lakhs of users, nobody would get a ticket.
- With threads: Java lets the server run many threads inside one program. Each request gets its own thread, so all three are handled at the same time.
- Safety: only 2 seats are left. The seat-count code is marked
synchronized, so only one thread at a time can change it. No seat is sold twice. - Result: Asha and Ravi get the last two seats; Meena goes to the waitlist. Fast and correct: this is why Java's built-in multithreading is listed as a key feature. (Simplified example.)
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.
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.
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.
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.
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.
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.
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.
Examples are simplified to show where each feature fits. Each company's exact technology choices vary.
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!");
}
}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.”eholds the details.e.getMessage()The error's message:Index 3 out of bounds for length 3.
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).
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.
prices {150, 220, 350}; customer asks for class index 5Sorry, seat class 5 does not exist. Kiosk still running. Classes available: 3
Approach
- Store the prices in an array.
- Read the requested price inside
try. - If the index is outside the array, Java throws
ArrayIndexOutOfBoundsException;catchit 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.
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.
daily revenue 95000000, 365 days
int result: 315261632 long result: 34675000000 int limit: 2147483647
Approach
- Multiply with
intand see the wrong (overflowed) answer. - Multiply with
long(64 bits) for the right answer. - Print
Integer.MAX_VALUEto 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.
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.
three notices in a row
Canteen opens at 8 Canteen opens at 9 today No notice. Is it null? true
Approach
- Assign a first notice to
notice. - Assign a new String twice; the older objects lose their reference.
- 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.
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.
Java's age
Java was released in 1995. Print how old Java is in 2026.
1995, 2026
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");
}
}How it works: brackets make the subtraction happen before joining with text.
Limits of int and long
Print the largest values an int and a long can hold.
(none)
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);
}
}How it works: these limits are the same on every computer, which is part of Java's portability.
Catch a division by zero
Divide 100 by 0 inside try/catch and print a friendly message.
100 / 0
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");
}
}
}How it works: Java turns the error into an exception object you can catch, instead of crashing the whole program.
Overflow you can see
Add 1 to Integer.MAX_VALUE and print the result.
2147483647 + 1
-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);
}
}How it works: an int wraps around to its minimum value. Use long when values can get this large.
Length of a message
Print the number of characters in "Write once, run anywhere".
the slogan
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());
}
}How it works: spaces and commas count as characters.
Safe price lookup
Prices of 4 products are in an array. Look up product 2, then product 9 safely.
{99, 149, 249, 399}; indexes 2 and 9Product 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");
}
}
}How it works: the first line prints; the second throws, so the rest of the try is skipped and the catch runs.
Population in long
India's population is about 1,45,00,00,000. Store it and print it divided across 28 states (whole number).
1450000000, 28
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);
}
}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.)
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.
1200, 45000
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);
}
}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.
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:
- 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.
- JDK internals: since Java 17, code or old libraries that reach into the JDK's internal classes fail. I'd run
jdeps --jdk-internalson our jars to find them. - Library upgrades: update frameworks and libraries to versions that support Java 21.
- 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.
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
synchronizedmethod or withAtomicInteger. - 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.
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
- 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. - Find the pattern: which customers fail? Maybe only those with more than a certain number of invoice items.
- Reproduce it in a unit test using that kind of data.
- Fix the root cause. “Index 5 for length 5” often means an off-by-one loop such as
i <= items.lengthinstead ofi < items.length, or code that assumed a fixed size. - 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.
“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.”
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.csvis treated as one file name containing a backslash. - Letter case: Linux file names are case-sensitive, so
Reportsandreportsare 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.