Working with Selected Classes from the Java API
Working with Selected Classes from the Java API
This domain covers String, StringBuilder, ArrayList, key java.time types, and simple lambda expressions with Predicate. The exam focuses on immutability, index rules, overloaded methods, and target typing.
String and StringBuilder
Stringis immutable. Methods such assubstring,replace,trim,toUpperCase, andconcatreturn a new string; the original is unchanged.substring(begin, end)includesbeginand excludesend.StringBuilderis mutable and not thread-safe:append,insert,delete,deleteCharAt,reverse, andtoStringchange or expose its contents.StringBuilderdoes not overrideequals, so==andequalsboth compare references.ArrayListis a resizable generic list:add,get,set,size,contains, andremove.remove(int index)removes by position;remove(Object o)removes the first equal element. Autoboxing can make the choice subtle.
java.time and lambdas
LocalDate, LocalTime, and LocalDateTime are immutable; plusDays, minusHours, and similar methods return new objects. Period represents a date-based amount, Duration a time-based amount. DateTimeFormatter parses and formats; pattern letters are case-sensitive (MM month, mm minute). A lambda assigned to Predicate<T> implements boolean test(T t).
Worked example
String s = "java";
s.substring(1, 3);
StringBuilder sb = new StringBuilder(s);
sb.append("8").reverse();
System.out.println(s + " " + sb);
substring returns av but the result is discarded, so s remains java. The builder becomes java8, then 8avaj. Output: java 8avaj.
Traps
String.charAtandsubstringthrowStringIndexOutOfBoundsExceptionfor invalid indexes.ArrayList.get(size())andremove(size())throwIndexOutOfBoundsException.List<Integer>.remove(1)selects the index overload, not the value overload.LocalDatemethods do not mutate the receiver.- A lambda needs a functional interface target;
Predicate<String> p = s -> s.isEmpty();is valid.