Understanding the String Class

A Java String is a sequence of characters that can't be changed once it's made, so every change creates a new string.

Novice · Java · Updated

By

String Representation

A string is a sequence of characters. Like an array, each character has a position (index), starting at 0.

Immutability

Strings are immutable. This means once a String object is created, it cannot be changed.

In other words, when you change the text of a string, Java builds a new string and the old one is thrown away.

// this creates a new string in memory
String name = "Vanessa";

// this line does not modify the original string
// it creates a new String
name += " Jones";

Do it: count a letter in a team's name

The stadium's sign maker charges by the letter. Before making a team's banner, they want to know how many of one letter its name needs.

The function gets two values:

  • team: the team's name, a String ("Tennessee").
  • letter: the letter to count, a char ('e').

A string's characters have indexes, like an array's elements, and two of its methods reach them: team.length() is how many characters it has, and team.charAt(i) is the char at index i. For example, the letter 'e' in "Tennessee":

Index 0 1 2 3 4 5 6 7 8
Character T e n n e s s e e
An 'e'? yes yes yes yes

So countLetter("Tennessee", 'e') returns 4.

Your job: write the function int countLetter(String team, char letter) so it returns how many of the name's characters are that letter.

  • Look at every character of team, from index 0 to the last.
  • A capital letter and a small letter are different characters: 'G' is not 'g'. So countLetter("Georgia", 'g') returns 1: the capital G at the start doesn't count.
  • If the letter isn't in the name, return 0.
  • If the name is the empty string "", return 0.

The box holds the function with nothing around it. Since Java 25, a small program can be written this way, so the function needs no class and no public static in front of it.

Practiced live on the lesson page: write the Java right there and check it.

Cheat sheets