Skip to content
Codewilds

Lesson 4 of 34 · Fundamentals

Java Strings and String Methods

easy10 XP3 min readFree lesson

Names, messages, passwords, commands — most programs spend a lot of time working with text. In Java, text is stored in a String, and the String class comes with dozens of handy methods for inspecting and transforming it.

Creating and joining Strings

A String literal is text in double quotes. The + operator joins Strings (and turns numbers into text along the way):

String first = "Ada";
String last = "Lovelace";
String full = first + " " + last;       // "Ada Lovelace"
String label = "Level " + 3;            // "Level 3"

Special characters are written with a backslash: \n (new line), \t (tab), \" (a double quote inside a String) and \\ (a backslash).

Indexes: length, charAt and substring

Each character has a position called its index, and indexes start at 0:

 H  i  g  h  l  a  n  d
 0  1  2  3  4  5  6  7
String place = "Highland";
place.length()          // 8
place.charAt(0)         // 'H' — a char, not a String
place.charAt(place.length() - 1)  // 'd' — the last character
place.substring(4)      // "land"  (from index 4 to the end)
place.substring(0, 4)   // "High"  (from 0 up to, NOT including, 4)
place.indexOf('l')      // 4  (first match)
place.indexOf("xyz")    // -1 (not found)

The end index of substring is exclusive, so substring(start, end) returns end - start characters. Asking for an index outside the String (like charAt(8) here) crashes the program with a StringIndexOutOfBoundsException.

Transforming Strings

String messy = "  Hello, Java!  ";
messy.trim()                  // "Hello, Java!"  (spaces removed at both ends)
messy.toUpperCase()           // "  HELLO, JAVA!  "
"java".replace('a', '4')      // "j4v4"
"Bytecode".contains("code")   // true
"Bytecode".startsWith("Byte") // true
"".isEmpty()                  // true

Strings are immutable: no method ever changes the original String. Every method returns a new String, so remember to use (or store) the result:

String name = "aria";
name.toUpperCase();          // result thrown away — name is still "aria"
name = name.toUpperCase();   // now name is "ARIA"

Comparing Strings: equals, not ==

This is the most famous Java beginner trap. == checks whether two variables point to the same object in memory, not whether they contain the same text. Two Strings with identical text can be different objects, so == may say false. Always compare text with equals:

String a = "Ada";
String b = new String("Ada");
System.out.println(a == b);                    // false (different objects)
System.out.println(a.equals(b));               // true  (same text)
System.out.println("ADA".equalsIgnoreCase(a)); // true

compareTo orders Strings alphabetically: "apple".compareTo("banana") is negative, because "apple" comes first.

Common mistakes

  • Comparing text with == — use equals or equalsIgnoreCase.
  • Off-by-one with substring: the end index is not included.
  • Forgetting that Strings are immutable and calling trim() or toUpperCase() without using the result.
  • Confusing char and String: 'A' is a char, "A" is a String. charAt returns a char.

Assignment

Implement four String helpers in Main:

  1. initials(String first, String last) — the uppercase initials followed by dots: initials("ada", "lovelace") returns "A.L.".
  2. shout(String text) — removes surrounding spaces, converts to uppercase and adds !: shout(" hello there ") returns "HELLO THERE!".
  3. isSameName(String a, String b) — true if the names are equal ignoring case and surrounding spaces: isSameName("Ada", " ada ") returns true.
  4. domain(String email) — the part after the @: domain("[email protected]") returns "highlands.io". If there is no @, return an empty String "".

Strings and formatting in other languages

Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.

Lesson last updated on .

Write code ↓
Java+10 XP

Press Run to execute your code, or Submit to check it against the tests.