๐ WAYPOINT LESSON
The String API you may use
โญ beginnerโณ 14 min read๐ Lesson 25 of 256
length, substring, charAt, indexOf, compareTo; index bounds; immutability.
A String is an object โ the first one you use. You never create it
with new in exam code; a literal is fine:
String name = "Minh";
The exam's official method set (the Java Quick Reference list):
name.length() // 4
name.substring(1) // "inh" โ from index 1 to the end
name.substring(1, 3) // "in" โ index 1,2 (end index EXCLUDED)
name.charAt(0) // 'M' โ returns a char, not a String
name.indexOf("i") // 1 โ first position, -1 when absent
name.equals("Minh") // true
name.compareTo("Nam") // <0 โ "Minh" sorts before "Nam"
Index rules: valid positions are 0 through length() - 1. Out of
range โ StringIndexOutOfBoundsException at runtime. For substring(lo, hi): lo may equal length() (empty result), but hi may not exceed it.
Immutability: String methods never change the string โ they return
new ones. name.toUpperCase() alone does nothing; you must store it:
name = name.toUpperCase();