← Java from Scratch Lesson 10 of 88 · 10 XP

Strings

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

String is an immutable object. Its methods return a new string:

String s = "Hello World";
s.length()              // 11
s.toUpperCase()         // "HELLO WORLD"
s.indexOf("World")      // 6 (-1 if it isn't there)
s.substring(6)          // "World"
s.substring(0, 5)       // "Hello" — from 0 UP TO 5, not including it
s.charAt(0)             // 'H'
s.contains("lo")        // true
s.replace("World", "IGD")
s.trim(), s.strip()     // without spaces at the edges
s.split(" ")            // an array of words
String.join("-", "a", "b")   // "a-b"
"ab".repeat(3)          // "ababab"

Strings are compared only with equals:

String a = "hi", b = new String("hi");
a == b         // false — these are TWO different objects, == compares references
a.equals(b)    // true  — compares the characters
a.equalsIgnoreCase("HI")   // true

For many concatenations in a loop, use StringBuilder: sb.append(x), and at the end sb.toString().

Task. Read a line FirstName LastName. Print the initials A. K., the last name in capital letters and the last name backwards (with new StringBuilder(s).reverse()).

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.