Java NotesRohit’s interview study guide
Chapter 02

Types, Variables and Strings

Static types and var, the eight primitives and their wrapper classes, how Java numbers overflow, divide and round (and why money is BigDecimal), why strings are compared with equals, the operators and control flow that differ from JavaScript, and arrays. Every example was run with Java 25 (Eclipse Temurin 25.0.5.1).

Try it yourself. As in chapter 01: for each example, make an empty folder, save every code box in it under the name in its caption, and type the $ lines of the Terminal box in that folder. Most examples are compact source files (Java 25), so java File.java is all you need. A run that ends in an exception or a compiler error is shown on purpose; the text says so.

7 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#Static types and var

Added

In TypeScript, types are a layer on top of JavaScript: the compiler checks them, then erases them, and at run time every value is just a JavaScript value. In Java, types are the language itself. Every variable, field, parameter and return value has a type the compiler knows, and every object also carries its class at run time. There is no "turn the checker off" switch, no any, and a cast is checked by the JVM when it runs, not just believed.

var (Java 10) doesn't change any of that. It only means "compiler, work out the type from the right-hand side". var count = 10; declares an int, exactly as if you'd written int count = 10;, and from then on count can only hold ints. That's the same as TypeScript's let count = 10 inferring number. What Java has no equivalent of is the escape hatch: TypeScript's any turns checking off, while Java's closest thing, Object, forces you to cast back before you can use the value.

The mental model: a Java variable is a box with a label printed on it at compile time. var lets the compiler print the label for you; it never makes the label erasable.

Infer.java
void main() {
    var count = 10;                       // int
    var price = 19.99;                    // double
    var name = "Rohit";                   // String
    var tags = new ArrayList<String>();   // ArrayList<String>
    tags.add("java");

    count = count + 5;
    IO.println(count + " " + price + " " + name.toUpperCase() + " " + tags);

    Object anything = name;               // you can store anything in an Object…
    String back = (String) anything;      // …but you must cast to use it again
    IO.println(back.length());
}
Broken.java
void main() {
    var count = 10;
    count = "ten";
}
Terminal
$ java Infer.java
15 19.99 ROHIT [java]
5
$ java Broken.java
Broken.java:3: error: incompatible types: String cannot be converted to int
    count = "ten";
            ^
1 error
error: compilation failed
What’s happening
  1. Each var gets its type from its initialiser: 10 is an int literal, 19.99 a double, "Rohit" a String, and new ArrayList<String>() an ArrayList<String>. The compiled bytecode is identical to writing the types out.
  2. count = count + 5 is fine (an int stays an int), so the first line prints 15 19.99 ROHIT [java]. name.toUpperCase() compiles because the compiler knows name is a String.
  3. Object anything = name works because every class extends Object. But anything.length() wouldn't compile: the label on the box says Object, and Object has no length(). The cast (String) anything changes the label back, and the JVM checks at run time that the object really is a String. It is, so back.length() prints 5.
  4. Broken.java tries to put a String into the int box. The compiler refuses with "incompatible types: String cannot be converted to int" and nothing runs. In JavaScript, let count = 10; count = "ten"; is fine; in TypeScript it's the same error as here, but TypeScript would still emit the JavaScript if you let it.
  5. So var is about less typing, not less typing-safety: the type is still fixed, just inferred.
AdvancedGotcha: var with the diamond infers Object
AdvancedCasts are checked at run time

A TypeScript as is a promise to the compiler and costs nothing at run time; if you lie, the code carries on with the wrong value. A Java cast is checked by the JVM, and a wrong one fails on the spot with ClassCastException.

Cast.java
void main() {
    Object value = 42;
    IO.println(value.getClass().getName());
    String text = (String) value;
    IO.println("never printed: " + text);
}
Terminal
$ java Cast.java
java.lang.Integer
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
	at Cast.main(Cast.java:4)
What’s happening
  1. Object value = 42 stores an Integer object (the int is boxed; see the next topic). The variable's compile-time type is Object, but the object itself still knows its class: getClass().getName() prints java.lang.Integer.
  2. (String) value compiles, because an Object might be a String. At run time the JVM checks the real class, finds an Integer, and throws ClassCastException with a message naming both classes. The program stops there, as it's meant to on this page.
  3. The TypeScript equivalent, const text = value as string, would compile and then text.length would quietly be undefined. Java's types survive to run time, which is also why instanceof works on any class (chapter 05). The one exception is generic type arguments, which are erased (chapter 04).
AdvancedWhere var is allowed

var is for local variables with an initialiser (and the variables of for loops and try-with-resources). It isn't allowed on fields, method parameters or return types, and it can't infer from null or from a lambda on its own. Each of these is a compile error:

Limits.java
void main() {
    var later;
    var nothing = null;
    var square = (int x) -> x * x;
}
Field.java
var total = 0;

void main() {
    IO.println(total);
}
Terminal
$ java Limits.java
Limits.java:2: error: cannot infer type for local variable later
    var later;
        ^
  (cannot use 'var' on variable without initializer)
Limits.java:3: error: cannot infer type for local variable nothing
    var nothing = null;
        ^
  (variable initializer is 'null')
Limits.java:4: error: cannot infer type for local variable square
    var square = (int x) -> x * x;
        ^
  (lambda expression needs an explicit target-type)
3 errors
error: compilation failed
$ java Field.java
Field.java:1: error: 'var' is not allowed here
var total = 0;
^
1 error
error: compilation failed
What’s happening
  1. var later; has no initialiser, so there's nothing to infer from.
  2. var nothing = null; fails because null has no useful type of its own.
  3. var square = (int x) -> x * x; fails because a lambda needs a target type, a functional interface such as IntUnaryOperator (chapter 08), and var doesn't provide one.
  4. The compiler reports all three, each with its own message, and nothing runs.
  5. In Field.java, var total = 0; sits outside main, so in a compact source file it's a field of the implicit class, and fields must have a declared type: "'var' is not allowed here". These limits are deliberate: var saves you repeating a type that's obvious from the same line, and nothing else.

#Primitives and wrapper classes

Added

Java has eight primitive types, which hold a plain value, and everything else is an object reached through a reference. JavaScript has primitives too (number, string, boolean, bigint…), but Java's are more numerous because Java lets you choose the size of a number.

PrimitiveSizeRange or valuesDefault (fields, arrays)Wrapper classNearest JS
byte8 bits−128 to 1270Bytean element of an Int8Array
short16 bits−32,768 to 32,7670Shortan element of an Int16Array
int32 bitsabout ±2.1 billion0Integernumber used as a whole number
long64 bitsabout ±9.2 × 10¹⁸0LLongbigint (but fixed size)
float32 bitsabout 7 significant digits0.0fFloat–
double64 bitsabout 15–16 significant digits0.0Doublenumber (exactly the same format)
char16 bitsone UTF-16 code unit'\u0000'Charactera one-character string, roughly
boolean–true, falsefalseBooleanboolean

Each primitive has a wrapper class: an object that holds one value. You need wrappers because collections and generics only hold objects (List<int> doesn't compile; List<Integer> does, see chapter 04), and because a wrapper can be null while a primitive can't. Since Java 5, the compiler converts between them for you: autoboxing (int → Integer, by calling Integer.valueOf) and unboxing (Integer → int, by calling intValue()).

The mental model: a primitive variable holds the value itself; an object variable holds an arrow to an object. And == compares what's in the variable: two values for primitives, but two arrows for objects. That's where the classic trap lives.

Cache.java
void main() {
    int a = 127, b = 127;
    IO.println("int 127 == int 127:         " + (a == b));

    Integer c = 127, d = 127;
    IO.println("Integer 127 == Integer 127: " + (c == d));

    Integer e = 128, f = 128;
    IO.println("Integer 128 == Integer 128: " + (e == f));
    IO.println("Integer 128 equals 128:     " + e.equals(f));

    int g = 128;
    IO.println("Integer 128 == int 128:     " + (e == g));
}
Terminal
$ java Cache.java
int 127 == int 127:         true
Integer 127 == Integer 127: true
Integer 128 == Integer 128: false
Integer 128 equals 128:     true
Integer 128 == int 128:     true
What’s happening
  1. a == b compares two int values: 127 == 127 is true. Primitives always compare by value.
  2. Integer c = 127 is autoboxed to Integer c = Integer.valueOf(127). valueOf keeps a cache of Integer objects for −128 to 127 (the Java Language Specification requires that range, and the JDK's Integer.java implements it as IntegerCache). So c and d are arrows to the same cached object, and c == d is true.
  3. 128 is outside the cache, so each valueOf(128) creates a new object. e == f compares two different arrows and is false, even though both objects hold 128.
  4. e.equals(f) compares the values inside the objects: true. For objects, equals asks "same value?" and == asks "same object?"
  5. e == g mixes an Integer and an int. Java then unboxes e and compares two ints, so it's true.
  6. This is why code that compares Integers with == passes every test with small numbers (ids 1, 2, 3…) and breaks in production when an id passes 127. Compare wrappers with equals (or Objects.equals when either may be null), or unbox to int first.
Which element goes?
Remove.java
void main() {
    var byIndex = new ArrayList<Integer>(List.of(10, 20, 1));
    byIndex.remove(1);
    IO.println(byIndex);

    var byValue = new ArrayList<Integer>(List.of(10, 20, 1));
    byValue.remove(Integer.valueOf(1));
    IO.println(byValue);
}
Show answer
Terminal
$ java Remove.java
[10, 1]
[10, 20]
What’s happening
  1. List has two remove methods: remove(int index) and remove(Object o). Overload resolution prefers a method that needs no boxing, so remove(1) with an int argument picks remove(int index).
  2. Index 1 holds 20, so the first list becomes [10, 1].
  3. remove(Integer.valueOf(1)) passes an object, so it calls remove(Object o), which removes the first element equal to 1: the second list becomes [10, 20].
  4. JavaScript has no overloading, so this trap doesn't exist there. In Java, when a List<Integer> is involved, be explicit about which remove you mean.
AdvancedUnboxing null

A wrapper can be null; a primitive can't. Unboxing a null (often without noticing that an unboxing happens) throws NullPointerException. The usual source is a Map<String, Integer> lookup that misses.

Stock.java
void main() {
    Map<String, Integer> stock = new HashMap<>();
    stock.put("keyboard", 12);

    int keyboards = stock.get("keyboard");
    IO.println("keyboards: " + keyboards);

    int safe = stock.getOrDefault("mouse", 0);
    IO.println("mice (getOrDefault): " + safe);

    int mice = stock.get("mouse");
    IO.println("mice: " + mice);
}
Terminal
$ java Stock.java
keyboards: 12
mice (getOrDefault): 0
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null
	at Stock.main(Stock.java:11)
What’s happening
  1. stock.get("keyboard") returns the Integer 12, and assigning it to an int unboxes it (the compiler inserts .intValue()). It prints keyboards: 12.
  2. getOrDefault("mouse", 0) returns 0 when the key is missing, so there's nothing to unbox wrongly: mice (getOrDefault): 0.
  3. stock.get("mouse") returns null, and the hidden .intValue() is called on null. The program fails with NullPointerException, and the message (helpful NPE messages, Java 14+) says exactly what happened: it couldn't invoke Integer.intValue() because the return value of Map.get(Object) is null. The last line never runs.
  4. Nothing on line 11 shows the intValue() call that fails; that's what makes this trap nasty. When a wrapper meets a primitive (assignment, arithmetic, == with an int), think "this might unbox null".
AdvancedThe cache is an implementation detail

Only −128 to 127 is guaranteed. The upper end can be raised with a JVM option, which shows the == result above was never something to rely on:

Terminal
$ java -XX:AutoBoxCacheMax=1000 Cache.java
int 127 == int 127:         true
Integer 127 == Integer 127: true
Integer 128 == Integer 128: true
Integer 128 equals 128:     true
Integer 128 == int 128:     true
What’s happening
  1. The same Cache.java, run with -XX:AutoBoxCacheMax=1000, makes Integer.valueOf cache up to 1000.
  2. Now Integer 128 == Integer 128 is true: the same code gives a different answer depending on a JVM flag. Code that's correct never depends on it, because it uses equals.
  3. Long, Short, Byte and Character have similar caches for small values; Double and Float have none.

#Numbers: overflow, division and BigDecimal

Added

JavaScript has one number type for almost everything: number, a 64-bit floating-point value (plus BigInt for big whole numbers). Java makes you pick, and each choice has rules JavaScript never taught you:

  • int and long overflow by wrapping around. One past Integer.MAX_VALUE is Integer.MIN_VALUE, silently, like a car's odometer rolling over. JavaScript never wraps; it loses precision instead once whole numbers pass Number.MAX_SAFE_INTEGER (2⁵³ − 1).
  • Dividing two integers gives an integer. 7 / 2 is 3 in Java, 3.5 in JavaScript. The result is truncated towards zero.
  • double is exactly JavaScript's number, so it has the same rounding surprises: 0.1 + 0.2 is 0.30000000000000004 in both. You met this in chapter 01, where a cart total printed as 69.49000000000001 (Programs with several files).
  • BigDecimal is exact decimal arithmetic, for money and anything else where 0.1 must mean exactly one tenth. JavaScript has no built-in equivalent, which is why Node code stores cents in integers or reaches for a library.

The mental model: an int is a fixed-size counter, a double is a binary approximation, and a BigDecimal is a decimal number written out digit by digit. Pick by what the number means, not by habit.

Numbers.java
void main() {
    int max = Integer.MAX_VALUE;
    IO.println("max:       " + max);
    IO.println("max + 1:   " + (max + 1));
    IO.println("max + 1L:  " + (max + 1L));

    IO.println("7 / 2:     " + (7 / 2));
    IO.println("7 / 2.0:   " + (7 / 2.0));
    IO.println("-7 / 2:    " + (-7 / 2));
    IO.println("-7 % 2:    " + (-7 % 2));
    IO.println("floorDiv:  " + Math.floorDiv(-7, 2));

    IO.println("0.1 + 0.2: " + (0.1 + 0.2));
    IO.println("exact:     " + new BigDecimal("0.1").add(new BigDecimal("0.2")));
    IO.println("1.0 / 0:   " + (1.0 / 0));
    IO.println("0.0 / 0:   " + (0.0 / 0));
}
Terminal
$ java Numbers.java
max:       2147483647
max + 1:   -2147483648
max + 1L:  2147483648
7 / 2:     3
7 / 2.0:   3.5
-7 / 2:    -3
-7 % 2:    -1
floorDiv:  -4
0.1 + 0.2: 0.30000000000000004
exact:     0.3
1.0 / 0:   Infinity
0.0 / 0:   NaN
What’s happening
  1. Integer.MAX_VALUE is 2,147,483,647 (2³¹ − 1). Adding 1 doesn't fail and doesn't grow: the 32-bit pattern rolls over to the most negative int, −2,147,483,648. No error, no warning.
  2. max + 1L is different: 1L is a long literal, so Java widens max to long before adding, and the answer 2,147,483,648 fits. In a mixed expression, the narrower operand is widened to the wider type first.
  3. 7 / 2 divides two ints, so the result is the int 3; the .5 is dropped, not rounded. Make either side a double (2.0) and you get 3.5.
  4. -7 / 2 is −3, not −4: Java truncates towards zero. The remainder -7 % 2 takes the sign of the left operand, −1 (JavaScript's % does the same). When you want floor behaviour, for example to bucket negative timestamps, Math.floorDiv gives −4 (and Math.floorMod the matching positive remainder).
  5. 0.1 + 0.2 prints 0.30000000000000004, character for character what Node prints, because both use IEEE 754 64-bit doubles. The same sum with BigDecimal, built from strings, is exactly 0.3; BigDecimal for money below shows how to use it properly.
  6. Floating-point division by zero doesn't throw: 1.0 / 0 is Infinity and 0.0 / 0 is NaN, as in JavaScript. Integer division by zero is different, as the next example shows.
Microseconds in a day
Micros.java
void main() {
    long microsPerDay = 24 * 60 * 60 * 1000 * 1000;
    long fixed = 24L * 60 * 60 * 1000 * 1000;
    IO.println(microsPerDay);
    IO.println(fixed);
}
Show answer
Terminal
$ java Micros.java
500654080
86400000000
What’s happening
  1. The right-hand side of the first line is evaluated before it's assigned, and every literal in it is an int, so the whole multiplication is done in 32-bit int arithmetic.
  2. The real answer, 86,400,000,000, is far past Integer.MAX_VALUE, so the product wraps and leaves 500,654,080. Only then is that wrong int widened to long. Declaring the variable long doesn't help.
  3. In the second line, 24L is a long, so each multiplication is done in long arithmetic and the result is the correct 86,400,000,000.
  4. The fix is to make the first operand a long. This exact bug is a classic interview puzzle and a real production bug in time calculations. java.time.Duration (for example Duration.ofDays(1).toNanos() / 1000) avoids writing the arithmetic yourself.
AdvancedMaking overflow and division by zero loud

When a wrong answer is worse than an exception, the Math.*Exact methods (Java 8) throw instead of wrapping. Integer division by zero always throws. And BigInteger is Java's BigInt: whole numbers of any size.

Exact.java
import java.math.BigInteger;

void main() {
    try {
        IO.println(Math.addExact(Integer.MAX_VALUE, 1));
    } catch (ArithmeticException e) {
        IO.println("addExact: " + e.getMessage());
    }

    int zero = 0;
    try {
        IO.println(10 / zero);
    } catch (ArithmeticException e) {
        IO.println("10 / 0: " + e.getMessage());
    }

    IO.println("(int) 3.99    = " + (int) 3.99);
    IO.println("(int) -3.99   = " + (int) -3.99);
    IO.println("(byte) 200    = " + (byte) 200);
    IO.println("(int) 1e20    = " + (int) 1e20);
    IO.println("round(2.5)    = " + Math.round(2.5));
    IO.println("round(-2.5)   = " + Math.round(-2.5));

    IO.println("2^100 = " + BigInteger.TWO.pow(100));
}
Terminal
$ java Exact.java
addExact: integer overflow
10 / 0: / by zero
(int) 3.99    = 3
(int) -3.99   = -3
(byte) 200    = -56
(int) 1e20    = 2147483647
round(2.5)    = 3
round(-2.5)   = -2
2^100 = 1267650600228229401496703205376
What’s happening
  1. Math.addExact(Integer.MAX_VALUE, 1) would overflow, so it throws ArithmeticException with the message integer overflow. There are subtractExact, multiplyExact, negateExact and toIntExact too. Use them for quantities, money in cents and ids, where wrapping would silently corrupt data.
  2. 10 / zero with ints throws ArithmeticException: / by zero. (Compare 1.0 / 0, which was Infinity.) The check happens at run time, every time an integer is divided.
  3. Casting a double to int truncates towards zero: 3.99 becomes 3 and −3.99 becomes −3.
  4. Casting to a smaller integer type keeps only the low bits: 200 doesn't fit in a byte (max 127), and its 8 bits read as −56. A double too big for an int saturates instead: (int) 1e20 is Integer.MAX_VALUE.
  5. Math.round rounds half up (towards positive infinity), so round(2.5) is 3 but round(-2.5) is −2. JavaScript's Math.round does the same.
  6. BigInteger.TWO.pow(100) is exact at any size, like 2n ** 100n in JavaScript. It's an object, so you use methods (add, multiply), not operators.
AdvancedBigDecimal for money

A double can't hold 0.1 exactly, so sums of prices drift. BigDecimal stores a whole number of digits plus a scale (how many digits are after the point), so 19.99 is exactly 1999 with scale 2. It's slower and wordier than double, which is fine for money and wrong for physics.

Money.java
void main() {
    IO.println("new BigDecimal(0.1)   = " + new BigDecimal(0.1));
    IO.println("new BigDecimal(\"0.1\") = " + new BigDecimal("0.1"));

    var price = new BigDecimal("19.99");
    var total = price.multiply(BigDecimal.valueOf(3));
    var vat = total.multiply(new BigDecimal("0.20")).setScale(2, RoundingMode.HALF_UP);
    IO.println("total " + total + ", vat " + vat + ", with vat " + total.add(vat));

    var a = new BigDecimal("2.0");
    var b = new BigDecimal("2.00");
    IO.println("2.0 equals 2.00:    " + a.equals(b));
    IO.println("2.0 compareTo 2.00: " + a.compareTo(b));

    IO.println("10 / 3 to 4 places: " + BigDecimal.TEN.divide(new BigDecimal("3"), 4, RoundingMode.HALF_EVEN));
    IO.println("10 / 3 exactly:     " + BigDecimal.TEN.divide(new BigDecimal("3")));
}
Terminal
$ java Money.java
new BigDecimal(0.1)   = 0.1000000000000000055511151231257827021181583404541015625
new BigDecimal("0.1") = 0.1
total 59.97, vat 11.99, with vat 71.96
2.0 equals 2.00:    false
2.0 compareTo 2.00: 0
10 / 3 to 4 places: 3.3333
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
	at java.base/java.math.BigDecimal.divide(BigDecimal.java:1810)
	at Money.main(Money.java:16)
What’s happening
  1. new BigDecimal(0.1) takes the double 0.1, which is already slightly wrong, and faithfully shows every digit of that binary approximation. new BigDecimal("0.1") parses the text and is exactly one tenth. Always build money from strings (or BigDecimal.valueOf(double), which goes through Double.toString, so valueOf(0.1) is 0.1), never with the double constructor.
  2. 19.99 × 3 is exactly 59.97. VAT at 20% is 11.9940, and setScale(2, RoundingMode.HALF_UP) rounds it to cents, 11.99. The total with VAT is 71.96. No drifting digits anywhere.
  3. equals on BigDecimal compares the value and the scale, so 2.0 and 2.00 are not equal. compareTo compares only the value and returns 0. Use compareTo to compare amounts; and be careful putting BigDecimals in a HashSet or as HashMap keys, which use equals.
  4. divide with a scale and a rounding mode gives 3.3333. HALF_EVEN ("banker's rounding") rounds ties to the even neighbour, which avoids a systematic upward bias over many operations.
  5. divide without a rounding mode must give the exact answer, and 10/3 has no finite decimal form, so it throws ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. That's the run's last line, and the program stops there, on purpose: decide how to round every division of money.

#Strings: immutable, pooled and compared with equals

Added

A Java String is an object, and it's immutable: no method changes it; methods like toUpperCase() or replace() return a new string. JavaScript strings are immutable too, so that part will feel familiar. What won't is comparison. In JavaScript, === on two strings compares their characters. In Java, == on two strings compares references (are these the same object?), and you compare characters with equals.

To make that confusing, Java keeps a string pool: every string literal in your code ("hello") is stored once, and every use of the same literal points to that one object. So == often seems to work, on literals, and then fails on strings that were built at run time, read from a request or a file, or returned by a method.

The mental model: == asks "is this the same piece of paper?"; equals asks "do these two pieces of paper say the same thing?" The pool is a shared drawer of pre-printed papers for literals, which is why two literals happen to be the same paper.

Equals.java
void main() {
    String a = "hello";
    String b = "hello";
    String c = new String("hello");
    String d = "hel" + "lo";
    String part = "hel";
    String e = part + "lo";

    IO.println("a == b:          " + (a == b));
    IO.println("a == c:          " + (a == c));
    IO.println("a == d:          " + (a == d));
    IO.println("a == e:          " + (a == e));
    IO.println("a.equals(e):     " + a.equals(e));
    IO.println("a == e.intern(): " + (a == e.intern()));
}
Terminal
$ java Equals.java
a == b:          true
a == c:          false
a == d:          true
a == e:          false
a.equals(e):     true
a == e.intern(): true
What’s happening
  1. a and b are the same literal, so both point to the one pooled "hello": a == b is true.
  2. new String("hello") always creates a new object, a copy of the pooled one. Same characters, different object: a == c is false. (There's never a reason to write new String("...") in real code.)
  3. "hel" + "lo" joins two literals, which is a compile-time constant: the compiler joins them itself and stores "hello" in the class file, so d is the pooled object too and a == d is true.
  4. part + "lo" involves a variable, so it's joined at run time into a new String object: a == e is false, although e is "hello". This is the case that matters in real code: anything from a request, a database or a method call is a run-time string.
  5. a.equals(e) compares the characters: true. Always compare strings with equals.
  6. e.intern() returns the pooled string with the same characters, so a == e.intern() is true. You'll rarely call intern() yourself; it's here to show what the pool is.
A final variable changes the answer
Constant.java
void main() {
    final String part = "hel";
    String joined = part + "lo";
    IO.println(joined == "hello");
}
Show answer
Terminal
$ java Constant.java
true
What’s happening
  1. This looks like case e above, which was false. The difference is final: a final local variable of type String initialised with a constant is a constant variable in the language rules.
  2. So part + "lo" is a compile-time constant expression, the compiler folds it into the literal "hello", and joined points at the pooled object.
  3. It prints true. Remove final and it prints false. A great interview puzzle and a terrible thing to depend on: this is exactly why == on strings is a bug even when tests pass.
Advancednull-safe comparison

input.equals("yes") throws NullPointerException when input is null. Two common fixes: put the literal first ("yes".equals(input) is simply false for null), or use Objects.equals(a, b), which handles null on either side. For case-insensitive checks there's equalsIgnoreCase.

NullSafe.java
void main() {
    String input = null;
    IO.println("\"yes\".equals(input):       " + "yes".equals(input));
    IO.println("Objects.equals(input, null): " + Objects.equals(input, null));
    IO.println("YES equalsIgnoreCase yes:    " + "YES".equalsIgnoreCase("yes"));
    IO.println("input.equals(\"yes\"):       " + input.equals("yes"));
}
Terminal
$ java NullSafe.java
"yes".equals(input):       false
Objects.equals(input, null): true
YES equalsIgnoreCase yes:    true
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "<local1>" is null
	at NullSafe.main(NullSafe.java:6)
$ javac -g NullSafe.java
$ java NullSafe
"yes".equals(input):       false
Objects.equals(input, null): true
YES equalsIgnoreCase yes:    true
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "input" is null
	at NullSafe.main(NullSafe.java:6)
What’s happening
  1. "yes".equals(input) calls equals on the literal, which is never null, and equals(null) is false by contract.
  2. Objects.equals(input, null) is true: both are null. It's the safe choice when either side can be null.
  3. equalsIgnoreCase ignores case: true.
  4. input.equals("yes") calls a method on null, so it throws NullPointerException and the run ends there, as intended. The message says the variable "<local1>" is null, not input: the source launcher compiles without debug information, so the class file doesn't keep local variable names.
  5. Compiled with javac -g (which keeps them, as a Maven build does by default), the same failure names the variable: because "input" is null. Chapter 05 is all about null.
AdvancedBuilding strings: immutability and StringBuilder

Because a String never changes, s = s + x in a loop creates a brand-new string every time and copies everything so far. For a handful of joins that's fine (the compiler optimises a single expression like "Total: " + total, chapter 01). For a loop, use StringBuilder, a mutable buffer you append to and turn into a String once. (StringBuffer is its older, synchronised twin; you won't need it.)

Builder.java
void main() {
    String name = "rohit";
    name.toUpperCase();
    IO.println(name);
    name = name.toUpperCase();
    IO.println(name);

    var sb = new StringBuilder();
    for (int i = 1; i <= 5; i++) {
        if (!sb.isEmpty()) sb.append(", ");
        sb.append(i);
    }
    IO.println(sb.toString());
    IO.println(sb.reverse());
    IO.println(String.join(" | ", List.of("a", "b", "c")));
}
Terminal
$ java Builder.java
rohit
ROHIT
1, 2, 3, 4, 5
5 ,4 ,3 ,2 ,1
a | b | c
What’s happening
  1. name.toUpperCase(); creates "ROHIT" and throws it away; name still points at "rohit", which prints. The same bug exists in JavaScript (name.toUpperCase(); alone does nothing there either).
  2. name = name.toUpperCase(); points the variable at the new string: ROHIT.
  3. The StringBuilder appends into one growing buffer: 1, 1, 2, … 1, 2, 3, 4, 5. isEmpty() on a StringBuilder is Java 15+; the check avoids a leading comma.
  4. sb.reverse() reverses the buffer in place (a builder is mutable) and returns it, so it prints 5 ,4 ,3 ,2 ,1, commas and spaces reversed too.
  5. For the common case of joining a list, String.join (or Collectors.joining in a stream) is simpler than a builder: a | b | c.
AdvancedText blocks

A text block (Java 15) is a multi-line string between """ delimiters, like a JavaScript template literal without the ${}. The compiler removes the indentation that's common to all lines (the "incidental" whitespace), so you can indent it with your code.

Blocks.java
void main() {
    String json = """
        {
          "name": "Keyboard",
          "price": 49.99
        }
        """;
    IO.print(json);
    IO.println("lines: " + json.lines().count());

    String sql = """
        SELECT id, name \
        FROM products \
        WHERE price > %d""".formatted(20);
    IO.println(sql);
}
Terminal
$ java Blocks.java
{
  "name": "Keyboard",
  "price": 49.99
}
lines: 4
SELECT id, name FROM products WHERE price > 20
What’s happening
  1. The text block's content starts on the line after the opening """. The closing """ is on its own line at the same indentation as {, so that indentation is stripped from every line and the JSON prints flush left, with its inner two-space indent kept.
  2. Because the closing """ is on its own line, the string ends with a newline, so IO.print (no extra newline) prints it cleanly. json.lines().count() (Java 11) counts 4 lines.
  3. In the second block, a \ at the end of a line (an escape added with text blocks) means "no newline here", so the SQL comes out as one line: SELECT id, name FROM products WHERE price > 20.
  4. Java has no ${} interpolation (string templates were a preview in Java 21 and 22 and were withdrawn). formatted(20) (Java 15) is String.format called on the string itself, and %d is replaced by 20.
AdvancedMethods worth knowing, and the UTF-16 surprise

Java 11 added the string methods you'd expect from JavaScript (strip, isBlank, repeat, lines); Java 12 added indent and transform, and Java 15 formatted. A few behave differently from their JavaScript namesakes:

Methods.java
void main() {
    IO.println("[" + "  hi  ".strip() + "]");
    IO.println("isBlank " + "   ".isBlank() + ", isEmpty " + "   ".isEmpty());
    IO.println("ab".repeat(3));
    IO.println("a\nb\nc".lines().map(String::toUpperCase).toList());
    IO.println("%s has %d items".formatted("cart", 3));
    IO.println("Keyboard".substring(3) + " " + "Keyboard".substring(3, 6) + " " + "Keyboard".indexOf("board"));
    IO.println("a,b,,c,,".split(",").length + " parts: " + Arrays.toString("a,b,,c,,".split(",")));
    IO.println("1.2.3".split(".").length + " vs " + "1.2.3".split("\\.").length);
    String smile = "😀";
    IO.println("length " + smile.length() + ", code points " + smile.codePointCount(0, smile.length()));
}
Terminal
$ java Methods.java
[hi]
isBlank true, isEmpty false
ababab
[A, B, C]
cart has 3 items
board boa 3
4 parts: [a, b, , c]
0 vs 3
length 2, code points 1
What’s happening
  1. strip() removes leading and trailing whitespace (Unicode-aware; the older trim() only removes the space character and ASCII control characters). isBlank() is true for whitespace-only, isEmpty() only for "".
  2. repeat(3) gives ababab; lines() gives a stream of lines, here uppercased into [A, B, C].
  3. substring(3) is board, substring(3, 6) is boa (end index exclusive, like JavaScript's slice), and indexOf("board") is 3.
  4. split differs from JavaScript twice. First, it drops trailing empty strings: "a,b,,c,," gives 4 parts [a, b, , c], where JavaScript gives 6. The empty string in the middle stays.
  5. Second, its argument is a regular expression: "." means "any character", so every character is a separator and everything is empty: 0 parts. Escape it as "\\." to get the 3 parts you wanted.
  6. A String is a sequence of UTF-16 chars, exactly like a JavaScript string, so an emoji outside the Basic Multilingual Plane takes two: length() is 2 (JavaScript's "😀".length is 2 as well). codePointCount counts real characters: 1.

#Operators and control flow

Added

Most of Java's operators and statements look exactly like JavaScript's, because both borrowed them from C: if, for, while, do/while, ? :, &&, ||, ++, +=, the bit operators, and break and continue. The differences are few, and each one bites a JavaScript developer at least once:

In JavaScriptIn Java
if (count), if (name): truthinessonly boolean is allowed in a condition; if (count) doesn't compile
=== and ==one ==: values for primitives, references for objects; equals for object values
7 / 2 is 3.57 / 2 is 3 (integer division)
a ?? b, a?.bno such operators (chapter 05 covers the alternatives, such as Optional)
switch falls through without breakthe old switch does too, but the arrow form (case X ->, Java 14) never falls through and can return a value
for (const x of list)for (var x : list), the enhanced for (Java 5)
typeof xx instanceof Type (chapter 05)

The modern switch is the one to learn properly. A switch expression (Java 14) produces a value, uses case A, B -> arrows that never fall through, and must cover every possible input. When a case needs several statements, it uses a block and yield to give its value (yield is to a switch case what return is to a method).

Sizes.java
void main() {
    for (String size : List.of("S", "M", "XL")) {
        IO.println(size + ": new " + points(size) + ", old " + oldPoints(size));
    }
    IO.println(points("XXL"));
}

int points(String size) {
    return switch (size) {
        case "S" -> 1;
        case "M" -> 2;
        case "L", "XL" -> {
            int base = 3;
            yield size.equals("XL") ? base + 1 : base;
        }
        default -> throw new IllegalArgumentException("unknown size: " + size);
    };
}

int oldPoints(String size) {
    int points;
    switch (size) {
        case "S":
            points = 1;
            break;
        case "M":
            points = 2;          // no break: falls through into "L"
        case "L":
            points = 3;
            break;
        case "XL":
            points = 4;
            break;
        default:
            points = -1;
    }
    return points;
}
Terminal
$ java Sizes.java
S: new 1, old 1
M: new 2, old 3
XL: new 4, old 4
Exception in thread "main" java.lang.IllegalArgumentException: unknown size: XXL
	at Sizes.points(Sizes.java:16)
	at Sizes.main(Sizes.java:5)
What’s happening
  1. points is a switch expression: the whole switch is a value that return hands back. case "S" -> 1 means "if it's S, the value is 1"; nothing runs into the next case, so there's no break to forget.
  2. case "L", "XL" lists two labels for one branch. That branch needs a local variable, so it's a block, and yield gives the block's value: 4 for XL.
  3. oldPoints is the classic switch statement. The "M" case is missing its break, so after setting points = 2 it falls straight into the "L" case and sets points = 3. The output shows the bug: M: new 2, old 3. S and XL agree in both versions.
  4. A switch expression must be exhaustive: every possible input needs a value. For strings that means a default, and here default throws. points("XXL") throws IllegalArgumentException: unknown size: XXL, which ends the run on purpose.
  5. The old form still compiles and is everywhere in older code. For new code, prefer the arrow form, as an expression when you're computing a value. Chapter 05 takes switch further: switching on types, with case Circle c ->, and exhaustiveness checked over sealed types.
Adding characters
Chars.java
void main() {
    IO.println('a' + 'b');
    IO.println("" + 'a' + 'b');
    IO.println('a' + 1 + "c");
    IO.println((char) ('a' + 1));
}
Show answer
Terminal
$ java Chars.java
195
ab
98c
b
What’s happening
  1. A char is a 16-bit number (its UTF-16 code), not a one-letter string. 'a' + 'b' is numeric addition: 97 + 98 = 195.
  2. "" + 'a' + 'b' is evaluated left to right: "" + 'a' is the string "a", then + 'b' gives "ab". Once a String is involved, + means concatenation, the same left-to-right rule as JavaScript (1 + 2 + "3" is "33" there).
  3. 'a' + 1 + "c": first 'a' + 1 is the int 98, then 98 + "c" is "98c".
  4. (char) ('a' + 1) casts 98 back to a char, which prints as b. This is how you step through letters.
AdvancedNo truthiness

A Java condition must be a boolean. There's no truthy 1, no falsy "" or null: you write the comparison you mean.

Truthy.java
void main() {
    int count = 3;
    String name = "";
    if (count) IO.println("has items");
    if (name) IO.println("has a name");
}
Terminal
$ java Truthy.java
Truthy.java:4: error: incompatible types: int cannot be converted to boolean
    if (count) IO.println("has items");
        ^
Truthy.java:5: error: incompatible types: String cannot be converted to boolean
    if (name) IO.println("has a name");
        ^
2 errors
error: compilation failed
What’s happening
  1. if (count) gives "incompatible types: int cannot be converted to boolean". In Java you'd write if (count > 0).
  2. if (name) fails the same way for String. The Java versions of JavaScript's checks are name != null, !name.isEmpty() or !name.isBlank(), and you pick the one you mean.
  3. Both errors are reported and nothing runs. This rule removes a whole class of JavaScript bugs (if (count) being false for a legitimate 0) at the cost of a few more characters.
AdvancedCompound assignment hides a cast

x += y isn't quite x = x + y: the compound form includes a cast back to the type of x. With a small type like byte, that hides an overflow the plain form refuses to compile.

Compound.java
void main() {
    byte b = 10;
    b += 300;
    IO.println("b += 300 gives " + b);

    int i = 5;
    i += 2.9;
    IO.println("i += 2.9 gives " + i);
}
Terminal
$ java Compound.java
b += 300 gives 54
i += 2.9 gives 7
What’s happening
  1. b += 300 is compiled as b = (byte) (b + 300). b + 300 is the int 310, and the cast keeps the low 8 bits: 310 − 256 = 54.
  2. b = b + 300; would not compile ("incompatible types: possible lossy conversion from int to byte"), because without the hidden cast an int doesn't fit in a byte.
  3. i += 2.9 is i = (int) (i + 2.9), so 7.9 is truncated to 7. The fractional part disappears without a warning.
  4. The lesson: compound assignment on a narrower type can lose data silently. Keep arithmetic in int, long or double and convert deliberately.
AdvancedLoops and labelled break

The enhanced for (for (var item : items)) walks any array or Iterable, like for…of. Java has no forEach statement, but collections have a forEach method that takes a lambda (chapter 08). To leave nested loops at once, label the outer loop and break to the label (JavaScript has labels too, but few people use them).

Search.java
void main() {
    int[][] grid = {
        {1, 3, 5},
        {7, 8, 9},
        {10, 12, 14}
    };

    int foundRow = -1, foundCol = -1;
    search:
    for (int row = 0; row < grid.length; row++) {
        for (int col = 0; col < grid[row].length; col++) {
            if (grid[row][col] % 2 == 0) {
                foundRow = row;
                foundCol = col;
                break search;
            }
        }
    }
    IO.println("first even number at row " + foundRow + ", col " + foundCol);

    int total = 0;
    for (int[] row : grid) {
        for (int n : row) {
            if (n > 10) continue;
            total += n;
        }
    }
    IO.println("total of numbers up to 10: " + total);
}
Terminal
$ java Search.java
first even number at row 1, col 1
total of numbers up to 10: 43
What’s happening
  1. search: labels the outer for. Scanning row 0 finds only odd numbers; in row 1, 7 is odd, then 8 is even.
  2. break search; leaves both loops at once, with foundRow = 1 and foundCol = 1. A plain break would only leave the inner loop, and the outer loop would carry on to row 2 and overwrite the answer with 10.
  3. The second part uses the enhanced for twice: for (int[] row : grid) walks the rows (each an int[]), and for (int n : row) walks the numbers. continue skips 12 and 14.
  4. The total is 1 + 3 + 5 + 7 + 8 + 9 + 10 = 43. When a labelled break gets complicated, moving the search into a method and using return is usually clearer.

#Arrays

Added

A Java array is a fixed-length block of elements of one type: new int[3] is three ints, forever. It can't grow or shrink, every element starts at a default value (0, false, or null for objects), and reading past the end throws instead of giving undefined. A JavaScript array is something else: a growable list that can hold anything. The Java equivalent of that is ArrayList (chapter 07), and in application code you'll use List far more often than arrays.

Arrays still matter: main(String[] args) takes one, varargs methods (String.format(String, Object...)) receive one, primitive arrays (int[], byte[]) are the compact, fast way to hold lots of numbers or bytes, and interview coding questions use them constantly.

The mental model: an array is a row of numbered lockers bolted to the floor. You can change what's in a locker, but not how many lockers there are. And the array variable is an arrow to the row, so == on two arrays compares arrows, not contents.

Lockers.java
void main() {
    int[] scores = new int[3];
    String[] names = new String[2];
    boolean[] flags = new boolean[2];
    IO.println(Arrays.toString(scores) + " " + Arrays.toString(names) + " " + Arrays.toString(flags));

    int[] primes = {7, 2, 5, 3};
    Arrays.sort(primes);
    IO.println(Arrays.toString(primes) + ", length " + primes.length);

    int[] copy = {2, 3, 5, 7};
    IO.println("==: " + (primes == copy) + ", equals: " + primes.equals(copy)
            + ", Arrays.equals: " + Arrays.equals(primes, copy));
    IO.println("toString() starts with [I@: " + primes.toString().startsWith("[I@"));

    int[] bigger = Arrays.copyOf(primes, 6);
    IO.println("copyOf to 6: " + Arrays.toString(bigger));

    primes[4] = 11;
}
Terminal
$ java Lockers.java
[0, 0, 0] [null, null] [false, false]
[2, 3, 5, 7], length 4
==: false, equals: false, Arrays.equals: true
toString() starts with [I@: true
copyOf to 6: [2, 3, 5, 7, 0, 0]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
	at Lockers.main(Lockers.java:19)
What’s happening
  1. new int[3] creates three ints set to 0; a String[] starts full of null, a boolean[] full of false. Arrays.toString prints them: [0, 0, 0] [null, null] [false, false].
  2. {7, 2, 5, 3} is an array initialiser. Arrays.sort sorts in place and numerically (JavaScript's default sort() compares as strings, so [10, 9].sort() gives [10, 9] there). length is a field, not a method: length 4.
  3. primes == copy compares references: false. Arrays don't override equals, so primes.equals(copy) is the same reference check: false. Arrays.equals compares element by element: true.
  4. Printing an array directly gives something like [I@ plus a hash code ([I is the JVM's name for int[]). The hash changes from run to run, so this page only checks how it starts. Use Arrays.toString, or Arrays.deepToString for nested arrays.
  5. "Growing" an array means copying it: Arrays.copyOf(primes, 6) makes a new 6-element array, padded with zeros.
  6. primes[4] = 11 writes past the end of a 4-element array. Java checks every index and throws ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4, ending the run on purpose. In JavaScript, primes[4] = 11 would just grow the array.
AdvancedArrays.asList and other traps

Arrays.asList turns an array into a List, but not the kind you might think: it's a fixed-size view backed by the array. And with a primitive array, it doesn't do what it looks like at all.

AsList.java
void main() {
    String[] letters = {"b", "a", "c"};
    List<String> view = Arrays.asList(letters);
    view.set(0, "z");
    IO.println("after set: array " + Arrays.toString(letters) + ", list " + view);
    Collections.sort(view);
    IO.println("after sort: array " + Arrays.toString(letters));

    try {
        view.add("d");
    } catch (UnsupportedOperationException e) {
        IO.println("view.add: " + e);
    }

    int[] numbers = {1, 2, 3};
    var wrapped = Arrays.asList(numbers);
    IO.println("Arrays.asList(int[]) size: " + wrapped.size());
    List<Integer> boxed = Arrays.stream(numbers).boxed().toList();
    IO.println("boxed: " + boxed + ", size " + boxed.size());

    List<String> independent = new ArrayList<>(List.of(letters));
    independent.add("d");
    IO.println("independent copy: " + independent + ", array still " + Arrays.toString(letters));
}
Terminal
$ java AsList.java
after set: array [z, a, c], list [z, a, c]
after sort: array [a, c, z]
view.add: java.lang.UnsupportedOperationException
Arrays.asList(int[]) size: 1
boxed: [1, 2, 3], size 3
independent copy: [a, c, z, d], array still [a, c, z]
What’s happening
  1. view.set(0, "z") writes through to the array: both now say z first. The list has no storage of its own; it's a window onto letters.
  2. Sorting the view sorts the array underneath: [a, c, z].
  3. view.add("d") throws UnsupportedOperationException: the view can't change size, because the array can't. (List.of(...) lists are stricter still: no set either, chapter 07.)
  4. Arrays.asList(numbers) with an int[] gives a list of size 1 whose single element is the whole array: generics can't hold int, so T becomes int[]. To get a List<Integer>, box the numbers through a stream: [1, 2, 3], size 3.
  5. When you want an ordinary, growable, independent list, copy into an ArrayList: adding to it leaves the array alone.

#Your turn: types and strings

Added
Your turn: split a bill fairly

Split £100.00 between 3 people in exact money arithmetic: everyone pays the same amount rounded down to the penny, and the first person also pays the pennies left over. Print each share and prove the shares add up to the total.

Show answer
Split.java
void main() {
    var total = new BigDecimal("100.00");
    int people = 3;

    var share = total.divide(BigDecimal.valueOf(people), 2, RoundingMode.DOWN);
    var remainder = total.subtract(share.multiply(BigDecimal.valueOf(people)));

    var shares = new ArrayList<BigDecimal>();
    for (int i = 0; i < people; i++) {
        shares.add(i == 0 ? share.add(remainder) : share);
    }
    IO.println("shares: " + shares);

    var sum = shares.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
    IO.println("sum " + sum + ", matches total: " + (sum.compareTo(total) == 0));
}
Terminal
$ java Split.java
shares: [33.34, 33.33, 33.33]
sum 100.00, matches total: true
What’s happening
  1. divide(…, 2, RoundingMode.DOWN) gives the share to the penny, rounded down: 100.00 / 3 is 33.33.
  2. Three shares of 33.33 make 99.99, so the remainder is 0.01.
  3. The first person pays 33.34 and the others 33.33: [33.34, 33.33, 33.33].
  4. The stream adds the shares with BigDecimal::add, starting from BigDecimal.ZERO, and compareTo confirms they make 100.00 exactly. With double, you'd be rounding a drifting value and hoping.
Your turn: a palindrome check

Write isPalindrome(String text) that ignores case, spaces and punctuation, so "Never odd or even" and "A man, a plan, a canal: Panama!" are palindromes and "Java" isn't. Print the result for all three.

Show answer
Palindrome.java
boolean isPalindrome(String text) {
    var letters = new StringBuilder();
    for (char ch : text.toCharArray()) {
        if (Character.isLetterOrDigit(ch)) {
            letters.append(Character.toLowerCase(ch));
        }
    }
    String forwards = letters.toString();
    String backwards = letters.reverse().toString();
    return forwards.equals(backwards);
}

void main() {
    for (String text : List.of("Never odd or even", "A man, a plan, a canal: Panama!", "Java")) {
        IO.println(isPalindrome(text) + "  " + text);
    }
}
Terminal
$ java Palindrome.java
true  Never odd or even
true  A man, a plan, a canal: Panama!
false  Java
What’s happening
  1. toCharArray() gives the string's chars, and Character.isLetterOrDigit keeps only letters and digits, lowercased: "Never odd or even" becomes neveroddoreven.
  2. forwards is taken with toString() before reverse(), because reverse() changes the builder in place. Calling toString() after it would compare the reversed text with itself and always say true.
  3. The strings are compared with equals, never ==: both were built at run time, so == would be false even for a real palindrome.
  4. The output is true for the two palindromes and false for Java (java reversed is avaj).
Your turn: factorials that don't lie

Print 20! as a long, then show that 21! doesn't fit in a long by making the multiplication throw instead of wrap, and finally print 25! exactly.

Show answer
Factorial.java
import java.math.BigInteger;

long factorial(int n) {
    long result = 1;
    for (int i = 2; i <= n; i++) {
        result = Math.multiplyExact(result, i);
    }
    return result;
}

BigInteger bigFactorial(int n) {
    var result = BigInteger.ONE;
    for (int i = 2; i <= n; i++) {
        result = result.multiply(BigInteger.valueOf(i));
    }
    return result;
}

void main() {
    IO.println("20! = " + factorial(20));
    try {
        IO.println("21! = " + factorial(21));
    } catch (ArithmeticException e) {
        IO.println("21! = " + e.getMessage());
    }
    IO.println("25! = " + bigFactorial(25));
}
Terminal
$ java Factorial.java
20! = 2432902008176640000
21! = long overflow
25! = 15511210043330985984000000
What’s happening
  1. factorial(20) multiplies 2 × 3 × … × 20 in long arithmetic. 20! = 2,432,902,008,176,640,000, just under Long.MAX_VALUE (about 9.2 × 10¹⁸), so it prints correctly.
  2. factorial(21) needs 21 × 20!, about 5.1 × 10¹⁹, which doesn't fit. With plain result * i it would silently wrap to a wrong (even negative) number; Math.multiplyExact throws ArithmeticException: long overflow instead, and the catch prints the message.
  3. bigFactorial(25) uses BigInteger, which grows as needed, so 25! prints in full. BigInteger is immutable like String and BigDecimal, so the result of multiply must be assigned back.

Written fresh, no doc. Examples were run with Eclipse Temurin 25.0.5.1 and Spring Boot 4.2.0 (Maven 3.10.1); facts come from openjdk.org, docs.oracle.com and spring.io, read 2026-11-26.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.