Object-oriented programming series: 1. Classes, objects, access modifiers · 2. Immutability, equals/hashCode, final · 3. Inheritance, encapsulation, polymorphism · 4. Abstract classes and interfaces · 5. UML, class relationships · 6. Wrappers, BigDecimal, String
This post covers three groups of “foundation” classes that a Java backend uses every day and often gets wrong: wrapper classes, BigInteger/BigDecimal, and String/StringBuilder. Afterwards you’ll avoid the == trap, null unboxing, wrong money math and O(n²) concatenation. Read part 2 on immutable objects first; designing class relationships with UML is in part 5.
At a glance:
mindmap
root((Wrapper, BigDecimal, String))
Wrapper
Compare with equals
Cache from -128 to 127
Unboxing null throws NPE
BigDecimal for money
Create from String
Divide with scale, RoundingMode
Compare with compareTo
String is immutable
Loops use StringBuilder
1. Wrapper classes
Key idea: primitives aren’t objects, so each primitive has a wrapper class for places that need an object. The compiler converts between them for you (autoboxing), and that automation causes three traps: ==, unboxing null, and the cost of creating objects.
Places that need an object where a primitive won’t fit: generics (List<int> is illegal), null values, utility methods.
| Primitive | Wrapper | Primitive | Wrapper | |
|---|---|---|---|---|
byte |
Byte |
float |
Float |
|
short |
Short |
double |
Double |
|
int |
Integer |
char |
Character |
|
long |
Long |
boolean |
Boolean |
The mapping table on the slide is wrong: it has no int row and maps long → Integer. The correct pairs are int → Integer and long → Long, as in the table above.
- Wrappers are immutable and
final. - Autoboxing / unboxing (the compiler converting
int ↔ Integer):Integer c = a + b;works becauseaandbare unboxed toint, added, and the result is boxed back.
Integer a = 1, b = 2;
Integer c = a + b; // unbox, add, box: Integer.valueOf(a.intValue() + b.intValue())
int parsed = Integer.parseInt("42"); // String -> int
Integer boxed = Integer.valueOf("42"); // String -> Integer (uses the cache)
String bin = Integer.toBinaryString(10); // "1010"
int max = Integer.MAX_VALUE; // 2147483647
Character.isDigit('7'); // true
Boolean.parseBoolean("TRUE"); // true (case-insensitive)
Double.compare(0.1 + 0.2, 0.3); // 1
The shared API of the numeric wrappers
Key idea: the numeric wrappers (Byte, Short, Integer, Long, Float, Double) all extend java.lang.Number and implement Comparable, so they share one set of methods: MIN_VALUE/MAX_VALUE, xxxValue(), compare, valueOf/parseXxx. Radix overloads exist only on the integral wrappers.
Two common mix-ups: Double.MIN_VALUE is the smallest positive value, and narrowing (byteValue(), intValue()) truncates bits or drops the fraction without any error.
Numeric-wrapper API table, radix overloads and the Integer cache
| Group | Methods | Notes |
|---|---|---|
| Constants | MIN_VALUE, MAX_VALUE |
For Float/Double, MIN_VALUE is the smallest positive value (4.9E-324), not the most negative one. The most negative is -Double.MAX_VALUE. |
Conversions (from Number) |
byteValue(), shortValue(), intValue(), longValue(), floatValue(), doubleValue() |
Narrowing truncates bits or drops the fraction: Integer.valueOf(300).byteValue() is 44, Double.valueOf(3.99).intValue() is 3. |
| Comparison | compareTo(other), static compare(a, b) |
Returns a negative number, zero or a positive number. |
| Strings | toString(), static valueOf(String) (returns the wrapper), static parseInt(String) / parseDouble(String)… (return the primitive) |
Malformed input throws NumberFormatException. |
| Radix | Integer.parseInt(s, radix), Integer.valueOf(s, radix), Integer.toString(i, radix), and the same on Long, Short, Byte |
Only on the integral wrappers. |
Integer.parseInt("ff", 16); // 255
Integer.valueOf("1010", 2); // 10
Integer.toString(255, 2); // "11111111"
Long.parseLong("zz", 36); // 1295
Integer.valueOf(5).compareTo(7); // -1
Double.valueOf(9.75).intValue(); // 9
2. BigInteger and BigDecimal
Key idea: a long tops out around 9.2 × 10¹⁸ and a double isn’t exact. For huge integers use BigInteger; for exact decimals (money) use BigDecimal.
BigInteger: integers of arbitrary size, bounded only by memory. Used in cryptography (RSA), large factorials, very large IDs.BigDecimal: aBigInteger(the unscaled value, the integer inside) plus ascale(digits after the decimal point). It is the standard for money.- Both are immutable; arithmetic goes through methods (
add,subtract,multiply,divide,remainder/mod,pow), and you must reassign the result.
BigInteger big = BigInteger.TWO.pow(100); // 1267650600228229401496703205376
BigInteger r = new BigInteger("123456789123456789").mod(BigInteger.valueOf(97));
BigInteger[] qr = BigInteger.valueOf(17).divideAndRemainder(BigInteger.valueOf(5)); // [3, 2]: quotient and remainder in one division
BigInteger p = BigInteger.probablePrime(64, new SecureRandom()); // a random 64-bit prime (with a vanishingly small error chance)
BigInteger next = BigInteger.valueOf(100).nextProbablePrime(); // 101
BigDecimal price = new BigDecimal("19.99"); // build from a String
BigDecimal qty = BigDecimal.valueOf(3);
BigDecimal total = price.multiply(qty); // 59.97
total = total.add(new BigDecimal("0.03")); // 60.00 (reassign: it's immutable)
BigDecimal pitfalls that come up in senior interviews:
Picking the RoundingMode isn’t enough; you also have to decide where to round. 10% VAT on three lines of 333,333 VND: rounding the VAT per line and adding gives 99,999 VND, rounding the VAT of the total gives 100,000 VND. Airline booking: a double-entry ledger and change history (the “sum of rounded VAT lines differs from the VAT on the total” pitfall) explains why that one-dong difference makes reconciliation fail every day, and how to settle on a single rounding rule.
In a Spring app: the cart and checkout post keeps money in BigDecimal, snapshots the price on each order line at checkout and computes the order total from the lines in exactly one place.
3. String, StringBuilder (and StringBuffer)
Key idea: String is immutable: every “modifying” method (concat, replace, toUpperCase, substring…) returns a new string. When you modify many times, as when building a string in a loop, use StringBuilder, a string you can change in place.
Why String is immutable:
- The string pool (identical literals share one object): sharing is only safe if nobody can change a string.
- Security: file paths, URLs and class names can’t be altered after they’ve been passed around.
- Thread safety and a cached hash, which make strings excellent
HashMapkeys.
String s1 = "hi";
String s2 = "hi"; // same pooled object as s1
String s3 = new String("hi"); // a new object on the heap
s1 == s2; // true
s1 == s3; // false
s1.equals(s3); // true: always compare strings with equals
s1 == s3.intern(); // true: intern() returns the pooled copy
StringBuilder: append, insert, delete, deleteCharAt, replace, reverse and setCharAt modify an internal character array in place, which grows automatically. Methods return the same sb, so calls chain.
StringBuilder sb = new StringBuilder("abc");
sb.reverse().insert(0, '>').append(42); // ">cba42": methods return the same sb, so calls chain
String result = sb.toString();
StringBuilder hello = new StringBuilder("Hello, World");
hello.deleteCharAt(5); // "Hello World": remove one character by index
hello.replace(0, 5, "Hi"); // "Hi World": replaces [0, 5); the end index is exclusive
hello.replace(2, 100, "!"); // "Hi!": an end past the length is clamped to length()
String internals: compact strings, the heap-resident pool, newer methods
Exercises
All solutions were run on JDK 21.
1. Write code using methods of the wrapper, String, StringBuilder, BigInteger and BigDecimal classes
Task: write a snippet that calls typical methods of each class and prints the results, to check the cache, radixes, mod and money rounding for yourself.
Solution to exercise 1: code run on JDK 21 with its output
// Wrappers
int n = Integer.parseInt("2024");
Integer cached1 = 100, cached2 = 100;
System.out.println(cached1 == cached2); // true (within the cache)
System.out.println(Integer.valueOf(1000).equals(1000)); // true
System.out.println(Integer.toHexString(255) + " " + Long.MAX_VALUE + " " + Character.toUpperCase('a'));
System.out.println(Integer.compare(3, 7) + " " + Integer.sum(3, 7) + " " + Integer.bitCount(7));
System.out.println(Integer.valueOf(1000).doubleValue() + " " + Double.valueOf(9.75).intValue()); // 1000.0 9
System.out.println(Integer.parseInt("777", 8) + " " + Integer.toString(255, 16) + " " + Integer.MIN_VALUE); // 511 ff -2147483648
// String
String s = " Backend Java ";
System.out.println(s.strip().toLowerCase().replace("java", "Spring")); // "backend Spring"
System.out.println("a,b,,c".split(",").length); // 4
System.out.println("ha".repeat(3) + " " + "abc".contains("b") + " " + "abc".indexOf('c'));
System.out.println(String.join("-", List.of("2026", "11", "17"))); // 2026-11-17
System.out.println("Hi %s, you are %d".formatted("Vinh", 28));
// StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) sb.append(i).append(i < 5 ? "," : "");
sb.insert(0, '[').append(']');
System.out.println(sb + " " + sb.length() + " " + sb.reverse()); // [1,2,3,4,5] 11 ]5,4,3,2,1[
sb.reverse().deleteCharAt(0).replace(sb.length() - 1, sb.length(), "");
System.out.println(sb); // 1,2,3,4,5
// BigInteger: 30! is far beyond long
BigInteger fact = BigInteger.ONE;
for (int i = 2; i <= 30; i++) fact = fact.multiply(BigInteger.valueOf(i));
System.out.println(fact + " " + fact.bitLength() + " bits " + BigInteger.valueOf(97).isProbablePrime(20));
BigInteger[] qr = fact.divideAndRemainder(BigInteger.valueOf(1_000_000_007));
System.out.println(qr[1] + " " + BigInteger.valueOf(-7).mod(BigInteger.valueOf(5)) + " " + BigInteger.valueOf(1000).nextProbablePrime()); // 109361473 3 1009
// BigDecimal: money math
BigDecimal price = new BigDecimal("199000");
BigDecimal vat = price.multiply(new BigDecimal("0.08")).setScale(0, RoundingMode.HALF_UP);
BigDecimal perPerson = price.add(vat).divide(BigDecimal.valueOf(3), 0, RoundingMode.HALF_EVEN);
System.out.println(vat + " " + price.add(vat) + " " + perPerson); // 15920 214920 71640
System.out.println(new BigDecimal("1.10").stripTrailingZeros().toPlainString()); // 1.1
Remember
- Explain why
Integer a = 127, b = 127; a == bistruebutfalsewith 128. - Know where
nullunboxing can happen (maps, JPA, JSON) and whynew Integer(..)was deprecated. - Write a correct
BigDecimaldivision and explain howequalsdiffers fromcompareTo. - Tell
BigInteger.modfromremainder, and know which one to use for a shard index. - Explain why concatenating in a loop is O(n²) and when
+is still fine.
Interview questions
Junior
What is a wrapper class? What is autoboxing?
A wrapper is a class that wraps a primitive (Integer wraps int…); autoboxing/unboxing is the compiler converting between the two automatically.
Wrappers work where an object is required, such as generics or null values. Behind the scenes, autoboxing calls valueOf() and unboxing calls intValue().
Why is String immutable?
So strings can be shared safely in the string pool, so sensitive parameters can’t be tampered with, for thread safety, and so the hash can be cached.
Sensitive parameters are things like paths, URLs and class names. The cached hash makes strings great HashMap keys.
Mid
String vs StringBuilder vs StringBuffer: when do you use each?
String is immutable; StringBuilder is mutable, not thread-safe, and fast; StringBuffer is mutable and thread-safe via synchronized, so it’s slower and rarely needed.
Use StringBuilder (or String.join, Collectors.joining) when building strings in loops, and plain + for one-off expressions, which the compiler already optimizes.
What does Integer a = 1000, b = 1000; a == b return? What about int c = mapOfInteger.get("missing");?
The first is false; the second throws a NullPointerException.
1000 is outside the -128..127 cache, so a and b are different objects. The second line unboxes null.
Why not use double for money, and how do you use BigDecimal correctly?
double is binary and can’t represent 0.1 exactly, so errors accumulate; BigDecimal is exact if you use it correctly.
- Build from a
StringorvalueOf. - Give every division an explicit scale and
RoundingMode. - Compare with
compareTo(becauseequalsalso compares scale). - Agree on rounding rules with the business; use
NUMERIC/DECIMALcolumns in the database.
How do new Integer(5) and Integer.valueOf(5) differ? Why were the wrapper constructors deprecated?
new Integer(5) always creates a new object; Integer.valueOf(5) returns a cached instance (-128 to 127), which saves memory and makes == between two calls true.
The constructors were deprecated in Java 9 and marked for removal in Java 16. They force a fresh object every time, which defeats caching and blocks turning wrappers into value classes (Project Valhalla), where object identity no longer means anything. Use valueOf, parseInt or autoboxing.
How do BigInteger.remainder and BigInteger.mod differ?
remainder takes the sign of the dividend (like %); mod is always non-negative, in [0, m).
-7 remainder 5 = -2, -7 mod 5 = 3. mod throws ArithmeticException if the modulus isn’t positive. When you need both quotient and remainder, use divideAndRemainder, which divides only once.
Senior
What goes wrong when you use BigDecimal as a HashMap or HashSet key?
equals/hashCode include the scale, so 2.0 and 2.00 are different keys, yet compareTo treats them as equal.
A TreeMap uses compareTo and merges them; a HashMap doesn’t. Normalize with stripTrailingZeros() or a fixed setScale before using values as keys, or use a TreeMap.
You’re building a CSV export with several million rows. What do you watch out for in terms of performance and memory?
Don’t build the whole file in memory: stream rows one line at a time to a BufferedWriter or straight into the response output stream.
- No
+=in loops (O(n²)). Even a singleStringBuilderfor the whole file can hold hundreds of MB on the heap. - Pre-size each row’s
StringBuilder. - Escape CSV special characters and specify UTF-8.
- Over HTTP, use a streaming response so you neither pin memory nor hit timeouts.
Useful phrases for interviews
- “For money, I use
BigDecimalbuilt from strings, with an explicit rounding mode, and I compare withcompareTo.” - “Comparing
Integers with==only works by accident inside the cache range, so I always useequals.” - “Strings are immutable, so concatenating in a loop is quadratic; I’d use a
StringBuilderorString.join.” - “The wrapper constructors are deprecated for removal, so I use
valueOfor plain autoboxing.” - “A narrowing conversion like
byteValue()silently truncates, so I validate the range first.” - “
Double.MIN_VALUEis the smallest positive double, not the most negative one.” - “
BigInteger.modis never negative, so I use it for shard or ring indexes.” - “For an export of millions of rows, I’d stream line by line instead of building one giant string.”
Notes based on the Fundamentals of Backend course (Ronin Engineer), rewritten in my own words. The slides’ reference book is Y. Daniel Liang, Introduction to Java Programming and Data Structures (11th edition); many of their diagrams come from it.