Predict the six lines printed by the Cache program in Section 4 (a = b = 127; c = d = 128 as Integers; e = 128 as an int; f = 127L as a Long).
Wrapper classes turn the eight primitives into objects so they can live in collections and generics. Know autoboxing, valueOf vs parseXxx, the Integer cache (−128…127) behind the == trap, and the String family: immutability, the string pool, StringBuffer vs StringBuilder.
int is a loose coin; collections such as ArrayList accept only items in envelopes (objects). A wrapper is the envelope — an Integer holds one int — and autoboxing is a clerk who slips coins into envelopes and takes them out for you. To save paper the clerk reuses envelopes for small, common amounts (−128 to 127), so two 'envelopes of 100' may be literally the same envelope while two 'envelopes of 1000' are different ones. That is exactly why == on wrappers lies.Integer.valueOf; unboxing: Integer → int via intValue(). Unboxing null throws NullPointerException.Integer.parseInt("42") returns a primitive int; Integer.valueOf("42") returns a (cached) Integer. Bad text → NumberFormatException. new Integer(5) is deprecated.== is true inside that range and false outside it. Compare wrappers with equals().equals is type-strict: Long.valueOf(1).equals(1) is false (the 1 boxes to an Integer). Integer == int unboxes and compares values.new String("x") always makes a new object. == compares references, equals() compares contents.substring(begin, end) excludes end; length() for String, length for arrays, size() for collections; compareTo returns a difference (0 when equal).Java's eight primitive types are fast, but they are not objects. A primitive cannot be stored in a collection (List<int> is illegal), cannot be null to mean 'no value', has no methods, and cannot be passed where an Object is expected. A wrapper class is an object that holds exactly one primitive value — so the value can go wherever objects go.
| Primitive | Wrapper class | Parse a String |
|---|---|---|
| byte | Byte | Byte.parseByte(s) |
| short | Short | Short.parseShort(s) |
| int | Integer | Integer.parseInt(s) |
| long | Long | Long.parseLong(s) |
| float | Float | Float.parseFloat(s) |
| double | Double | Double.parseDouble(s) |
| char | Character | — (use s.charAt(0)) |
| boolean | Boolean | Boolean.parseBoolean(s) |
The six numeric wrappers extend the abstract class Number, which declares intValue(), longValue(), floatValue(), doubleValue(), byteValue() and shortValue(); BigInteger, BigDecimal and AtomicInteger are Numbers too. Character and Boolean extend Object directly. All wrappers are in java.lang, are final and immutable, implement Comparable, and offer constants such as Integer.MAX_VALUE (2147483647), Integer.MIN_VALUE, Integer.SIZE (32 bits) and Integer.BYTES (4).
int is Integer (not Int) and the wrapper of char is Character (not Char).import java.util.Map;
import java.util.TreeMap;
public class Tally {
public static void main(String[] args) {
String[] offices = {"Kochi", "Thrissur", "Kochi"};
Map<String, Integer> count = new TreeMap<>(); // Map<String, int> is illegal
for (String o : offices)
count.put(o, count.getOrDefault(o, 0) + 1); // unbox, add 1, box again
System.out.println(count);
Integer interviewMark = null; // a primitive int cannot say "not yet"
System.out.println(interviewMark == null ? "mark pending" : "mark " + interviewMark);
}
}Wrappers also supply the type-specific behaviour generic code needs: equals() and hashCode() (so Integers work as HashMap keys), compareTo() (so Collections.sort can order a List<Integer>) and toString(). The cost is memory — an Integer object takes about 16 bytes against 4 for an int — so keep large numeric arrays as primitives (int[]), not Integer[].
Boxing wraps a primitive in its wrapper object; unboxing extracts the primitive again. Since J2SE 5.0 the compiler does both automatically — autoboxing and auto-unboxing — by inserting Integer.valueOf(…) and ….intValue() calls wherever a primitive and a wrapper meet: assignments, method arguments and return values, collections, arithmetic and comparisons.
import java.util.ArrayList;
import java.util.List;
public class Boxing {
public static void main(String[] args) {
Integer a = Integer.valueOf(10); // manual boxing
int b = a.intValue(); // manual unboxing
Integer c = 20; // autoboxing: the compiler writes Integer.valueOf(20)
int d = c + 5; // auto-unboxing: c.intValue() + 5
List<Integer> list = new ArrayList<>();
list.add(7); // autoboxing into a collection
int first = list.get(0); // auto-unboxing out of it
System.out.println(b + " " + d + " " + first);
Integer missing = null;
// int bad = missing; // compiles, but throws NullPointerException
}
}Autoboxing is convenient but not free. Long sum = 0L; for (long i = 0; i < n; i++) sum += i; unboxes, adds and creates a new Long object on every iteration — declare long sum instead. And because wrappers can be null, an innocent-looking int y = map.get(key); throws NullPointerException when the key is missing.
List<Integer>, list.remove(1) calls remove(int index) — it removes the element at index 1, because an exact int match beats boxing. To remove the value 1, write list.remove(Integer.valueOf(1)).| Call | Returns | Result |
|---|---|---|
Integer.parseInt("42") | int | 42 |
Integer.valueOf("42") | Integer (cached when small) | 42 |
Integer.parseInt("ff", 16) | int, radix 16 | 255 |
Integer.parseInt("1010", 2) | int, radix 2 | 10 |
Integer.toString(255) | String | "255" |
Integer.toBinaryString(10) | String | "1010" |
Integer.toHexString(255) | String | "ff" |
Integer.toOctalString(8) | String | "10" |
String.valueOf(3.5) | String | "3.5" |
Double.parseDouble("2.5e3") | double | 2500.0 |
Boolean.parseBoolean("TRUE") | boolean | true — case-insensitive; any other text gives false |
Integer.parseInt("12a") or (" 5") | — | throws NumberFormatException (no trimming either) |
parseXxx vs valueOf: parseInt returns a primitive and creates no object; valueOf returns a wrapper and may reuse a cached one. The wrapper constructors (new Integer(5), new Double("2.5")) always create a fresh object; they were deprecated in Java 9 and marked for removal in Java 16 — use valueOf. Java 8 added helpers such as Integer.compare(a, b), Integer.sum, Integer.max.
| Method | Example | Result |
|---|---|---|
| isDigit | Character.isDigit('7') | true |
| isLetter | Character.isLetter('a') | true |
| isLetterOrDigit | Character.isLetterOrDigit('_') | false |
| isUpperCase / isLowerCase | Character.isUpperCase('K') | true |
| isWhitespace | Character.isWhitespace(' ') | true |
| toUpperCase / toLowerCase | Character.toUpperCase('b') | 'B' |
| getNumericValue | Character.getNumericValue('7') | 7 |
Integer.valueOf(int) — and therefore autoboxing — keeps a cache of Integer objects for −128 to 127 and returns the same object every time a value in that range is boxed. Outside the range a new object is normally created. == on two references asks 'are these the same object?', so its answer depends on the cache.
public class Cache {
public static void main(String[] args) {
Integer a = 127, b = 127; // both come from the cache: SAME object
Integer c = 128, d = 128; // outside the cache: two different objects
int e = 128;
Long f = 127L;
System.out.println(a == b); // true
System.out.println(c == d); // false
System.out.println(c.equals(d)); // true (contents compared)
System.out.println(c == e); // true (c is unboxed; numbers compared)
System.out.println(f.equals(127)); // false (127 boxes to an Integer, not a Long)
System.out.println(f == 127); // true (numeric comparison after unboxing)
}
}-XX:AutoBoxCacheMax=<n>.Boolean.TRUE and Boolean.FALSE.new Integer(…) never uses the cache, so new Integer(5) == new Integer(5) is false.Wrappers are immutable: Integer x = 5; x++; does not change an Integer object — it unboxes, adds one and boxes a new Integer into x. That is why a method cannot change a caller's Integer argument, just as it cannot change a String.
==. Use a.equals(b), or compare the unboxed values (a.intValue() == b.intValue()). And remember equals also checks the type — an Integer is never equal to a Long.String is a final class in java.lang representing an immutable sequence of characters: no String method changes the object it is called on. toUpperCase(), concat(), replace() and the others return a new String and leave the original intact. Immutability makes strings safe to share, safe as HashMap keys (the hash code is cached), thread-safe without locks, and secure — a file name or URL cannot be altered after it has been checked.
Because strings cannot change, the JVM keeps one shared copy of each literal in the string pool (intern pool), part of the heap since Java 7. Every occurrence of the literal "Java" — and every compile-time constant expression such as "Ja" + "va" — refers to that pooled object. new String("Java") always creates a separate object, and intern() returns the pooled copy of any string.
public class Pool {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Java"; // the same pooled object as s1
String s3 = new String("Java"); // a new object on the heap
String s4 = "Ja" + "va"; // constant expression: folded at compile time
String part = "Ja";
String s5 = part + "va"; // computed at run time: a new object
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s1.equals(s3)); // true
System.out.println(s1 == s4); // true
System.out.println(s1 == s5); // false
System.out.println(s1 == s5.intern()); // true
String t = "kshb";
t.toUpperCase(); // the result is thrown away; t is unchanged
System.out.println(t + " " + t.toUpperCase()); // kshb KSHB
}
}Had part been declared final String part = "Ja";, it would be a compile-time constant and s1 == s5 would be true. For comparisons use equals() (contents), equalsIgnoreCase(), and compareTo(), which compares lexicographically and returns the difference of the first mismatching characters — or of the lengths if one string is a prefix of the other: "cat".compareTo("car") is 't' − 'r' = 2, and "abc".compareTo("abcde") is 3 − 5 = −2.
| Method | Call | Result |
|---|---|---|
| length() | s.length() | 10 |
| charAt(i) | s.charAt(3) | 'a' |
| substring(begin) | s.substring(7) | "PSC" |
| substring(begin, end) | s.substring(0, 6) | "Kerala" — index 6 is excluded |
| indexOf / lastIndexOf | s.indexOf('a'), s.lastIndexOf('a') | 3, 5 |
| indexOf(String) | s.indexOf("PSC") | 7 (−1 when absent) |
| contains / startsWith / endsWith | s.contains("la"), s.startsWith("Ker"), s.endsWith("C") | true, true, true |
| toLowerCase / toUpperCase | s.toLowerCase() | "kerala psc" |
| replace | s.replace('a', '@') | "Ker@l@ PSC" |
| trim / strip | " hi ".trim() | "hi" |
| split | "a,b,,c".split(",") | 4 parts: a, b, (empty), c |
| concat | s.concat(" 2026") | "Kerala PSC 2026" |
| equalsIgnoreCase | s.equalsIgnoreCase("KERALA psc") | true |
| compareTo | "cat".compareTo("car") | 2 |
| isEmpty / isBlank (Java 11) | " ".isEmpty(), " ".isBlank() | false, true |
| String.join / repeat (Java 11) | String.join("-", "a", "b"), "ab".repeat(3) | "a-b", "ababab" |
| toCharArray / valueOf | "hi".toCharArray().length, String.valueOf(42) | 2, "42" |
str.length() (a String method), arr.length (an array field, no parentheses), list.size() (a collection method). Indexes always start at 0, and every 'end' index in the Java API is exclusive.When text must change repeatedly, use a mutable character sequence. StringBuffer (JDK 1.0) and StringBuilder (J2SE 5.0) share the same API: append() (overloaded for every type, and returning the object itself so calls can be chained), insert(offset, x), delete(start, end), deleteCharAt(i), replace(start, end, str), reverse(), setCharAt(i, c), length(), capacity(), setLength() and toString(). The only difference is that StringBuffer's methods are synchronized.
Capacity is the size of the internal array, as opposed to the number of characters stored (length()). An empty builder starts at 16; new StringBuilder("abc") starts at 16 + 3 = 19; new StringBuilder(50) at 50. When an append needs more room the array grows to old capacity × 2 + 2 (or to the required length, if that is larger).
public class Builder {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
System.out.println(sb.length() + " " + sb.capacity()); // 0 16
sb.append("Hello").append(' ').append(2026); // chained appends
System.out.println(sb + " " + sb.length() + " " + sb.capacity()); // Hello 2026 10 16
sb.append(" Kerala PSC!"); // 22 chars > 16
System.out.println(sb.length() + " " + sb.capacity()); // 22 34
sb.insert(0, ">> "); // >> Hello 2026 Kerala PSC!
sb.delete(3, 9); // removes "Hello "
System.out.println(sb); // >> 2026 Kerala PSC!
sb.reverse();
System.out.println(sb); // !CSP alareK 6202 >>
StringBuffer buf = new StringBuffer("abc");
System.out.println(buf.capacity()); // 19 (16 + 3)
}
}| Point | String | StringBuffer | StringBuilder |
|---|---|---|---|
| Mutable? | No — immutable | Yes | Yes |
| Thread-safe? | Yes (because immutable) | Yes — synchronized methods | No — not synchronized |
| Speed for repeated changes | Slow: every change makes a new object | Moderate (locking overhead) | Fastest |
| Introduced | JDK 1.0 | JDK 1.0 | J2SE 5.0 |
| equals() | Compares contents | Not overridden — compares references | Not overridden — compares references |
| String pool | Literals are pooled | Never pooled | Never pooled |
| Use for | Fixed values, map keys | Text modified by several threads | Building text in one thread, e.g. in loops |
The compiler implements a + b + c on strings efficiently (StringBuilder up to Java 8, invokedynamic string concatenation since Java 9). But s += x inside a loop still creates a brand-new String on every pass — quadratic work for long texts. Build such text in a StringBuilder and call toString() once at the end.
Try the problem first, then reveal the working one step at a time.
Predict the six lines printed by the Cache program in Section 4 (a = b = 127; c = d = 128 as Integers; e = 128 as an int; f = 127L as a Long).
Predict the output of the Pool program in Section 5 (s1 and s2 literals, s3 via new, s4 = "Ja" + "va", s5 = part + "va" with a non-final part, and the toUpperCase lines).
Trace the Builder program in Section 7: give length and capacity after each stage and the text after insert, delete and reverse.
Evaluate: "apple".compareTo("banana"), "cat".compareTo("car"), "abc".compareTo("abcde"), "B".compareTo("a"), the number of parts in "2026-12-03".split("-"), and "Kerala".indexOf('z').
What is printed? Integer p = 100, q = 100, r = 1000, s = 1000; System.out.println((p == q) + " " + (r == s) + " " + r.equals(s) + " " + (r.intValue() == s));
Predict: String a = "PSC"; String b = a; a = a + "2026"; System.out.println(a + " " + b + " " + (a == b));
Choose String, StringBuffer or StringBuilder: (a) building a 10,000-line report inside one method; (b) a log buffer appended to by several threads; (c) a configuration key used in a HashMap; (d) reversing a word typed by the user.
Give the result or the exception: (a) Integer x = null; int y = x; (b) Integer.parseInt("1010", 2) (c) Integer.valueOf("077") (d) Integer.decode("077") (e) Integer.parseInt(" 5") (f) Boolean.parseBoolean("yes")
What does this print, and why? List<Integer> list = new ArrayList<>(List.of(10, 20, 30)); list.remove(1); list.remove(Integer.valueOf(10)); System.out.println(list);
== between wrapper objects compares references — it is true for −128…127 only because of the cache. Always use equals() or compare unboxed values.equals is type-strict: Long.valueOf(5).equals(5) and Double.valueOf(1).equals(1) are false because the argument boxes to an Integer.s.toUpperCase() or s.concat(x) without assigning the result changes nothing.equals() — two builders with the same text are not 'equal'.substring(begin, end) excludes end; length() (String) vs length (array) vs size() (collection) is a favourite trick.list.remove(1) on a List<Integer> removes index 1, not the value 1.10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
char isModelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
StringBuffer buf = new StringBuffer("Hello");
buf.delete(0, 2);
System.out.println(buf);