Objects in memory practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most memory mistakes in everyday Java come from four habits: forgetting the header and the objects behind references when sizing, comparing wrappers with ==, comparing strings with ==, and keeping large numeric data in boxed collections. Each has a short, reliable fix.
Mistake 1: adding up only the fields
Adding 4 + 8 + 4 for a class with an int, a double and a String gives 16 bytes, but the object is bigger.
Example 1 · Mistake: counting only the fields
public class SizeMistakeDemo { static int align(int bytes) { return (bytes + 7) / 8 * 8; }
public static void main(String[] args) { // class Hostel { int rooms; double fee; String name; } name = "Godavari" int fieldsOnly = 4 + 8 + 4; // the common wrong answer int shallow = align(12 + 4 + 8 + 4); // header + fields + padding int nameString = 24; int nameBytes = align(16 + 8); int deep = shallow + nameString + nameBytes;
System.out.println("Fields only (wrong): " + fieldsOnly + " bytes"); System.out.println("Shallow size: " + shallow + " bytes"); System.out.println("Deep size: " + deep + " bytes"); }}Fields only (wrong): 16 bytes Shallow size: 32 bytes Deep size: 80 bytes
What this code does
- 16 bytes is the fields alone. With the 12-byte header the object is 28, rounded to 32 bytes.
- The name
"Godavari"adds a 24-byteStringand a 24-bytebyte[8], so the deep size is 80 bytes: five times the wrong answer.
On 64-bit HotSpot (Java 17 and 21, default settings) every object adds a 12-byte header, and the total is rounded up to a multiple of 8. Arrays add 16 bytes (header plus length).
The String field is only a 4-byte reference. The string itself is a separate 24-byte object with its own byte[]. Shallow size counts the object alone; deep size follows the references; retained size counts what would be freed.
Mistake 2: == on Integer, Long and other wrappers
== on two wrapper objects compares references. Autoboxing uses valueOf, which shares cached objects for -128 to 127, so the bug stays hidden in tests with small numbers and appears with real fees, marks or votes.
Example 2 · Mistake: == on Integer fees
import java.util.HashMap;import java.util.Map;
public class WrapperMistakeDemo { public static void main(String[] args) { Map<String, Integer> feesPaid = new HashMap<>(); feesPaid.put("Kiran", 100); feesPaid.put("Latha", 85000); Map<String, Integer> feesDue = new HashMap<>(); feesDue.put("Kiran", 100); feesDue.put("Latha", 85000);
for (String name : feesPaid.keySet()) { boolean wrong = feesPaid.get(name) == feesDue.get(name); boolean right = feesPaid.get(name).equals(feesDue.get(name)); System.out.println(name + ": == says " + wrong + ", equals says " + right); } }}Kiran: == says true, equals says true Latha: == says false, equals says true
What this code does
- Kiran's fee of 100 is inside the cache, so both maps hold the same
Integerand==happens to be right. - Latha's 85000 was boxed twice into two objects.
==says the fees differ;equalscompares the values and is right for both.
The fix is a.equals(b), Objects.equals(a, b) when either may be null, or a primitive on one side (int top), which makes Java compare numbers. Keep the types the same: a Long never equals an Integer.
Mistake 3: == on strings from input, files or substring
Literals and compile-time constants are pooled, so "Chennai" == "Chennai" is true. Strings made at run time (by split, substring, StringBuilder, reading a file, user input) are new objects, so == with a literal is false even when the text matches.
Example 3 · Mistake: == on strings from split
public class StringMistakeDemo { public static void main(String[] args) { String row = "4521367890,Chennai,CNF"; // one line of a booking file String[] parts = row.split(","); String city = parts[1]; String status = parts[2];
System.out.println("city == \"Chennai\" : " + (city == "Chennai")); System.out.println("city.equals(\"Chennai\") : " + city.equals("Chennai")); System.out.println("status == \"CNF\" : " + (status == "CNF")); System.out.println("\"CNF\".equals(status) : " + "CNF".equals(status)); System.out.println("city.intern() == \"Chennai\": " + (city.intern() == "Chennai")); }}city == "Chennai" : false
city.equals("Chennai") : true
status == "CNF" : false
"CNF".equals(status) : true
city.intern() == "Chennai": trueWhat this code does
splitcreates newStringobjects, socity == "Chennai"isfalsealthough the text is the same.equalscompares the text.intern()returns the pooled copy and makes==true, but for comparing textequalsis the right tool.
Compare text with "Chennai".equals(city) (literal first, so a null city is safe) or a method such as startsWith. intern() would make == work, but it is the wrong tool for comparison: use it only to save memory for many repeated values.
Mistake 4: boxed collections for large numeric data
A List<Integer> costs about 20 bytes per value and a HashMap<Integer, Integer> about 70 to 75 bytes per entry, against 4 bytes per int in an array.
Example 4 · Fix: a counting map becomes an int[]
import java.util.HashMap;import java.util.Map;
public class BoxedCountsDemo { public static void main(String[] args) { int students = 300_000; int[] marks = new int[students]; for (int i = 0; i < students; i++) { marks[i] = (i * 7) % 501; }
// Before: a boxed map from mark to count (up to 501 entries, many boxed counts) Map<Integer, Integer> boxed = new HashMap<>(); for (int m : marks) { boxed.merge(m, 1, Integer::sum); // each new count above 127 is a new Integer }
// After: marks are 0..500, so the mark itself is the index int[] counts = new int[501]; for (int m : marks) { counts[m]++; }
System.out.println("Students with 450: map says " + boxed.get(450) + ", array says " + counts[450]); System.out.println("Distinct marks: map " + boxed.size() + ", array length " + counts.length); System.out.println("Array memory: " + (16 + 4 * counts.length + 7) / 8 * 8 + " bytes, one object"); }}Students with 450: map says 599, array says 599 Distinct marks: map 501, array length 501 Array memory: 2024 bytes, one object
What this code does
- Both give 599 students with 450 marks. The map holds 501 nodes, 501 keys and a boxed count per mark (counts above 127 are new
Integerobjects each time they change). - Marks are 0 to 500, so
counts[m]++uses the mark as the index: one 2024-byte object, no boxing and no hashing.
When the keys are small whole numbers, such as marks 0 to 500 or roll numbers from 1, the key can be the array index.
Rewrite counting maps as int[] counts indexed by the value, flags as BitSet, and sums or maximums as IntStream. The program gets smaller and usually faster too.
Finish up
Mark complete & continue
Next: What garbage collection does