AI Hints
Home›Java Tutorial›Strings, Joining Strings and String Methods
Java · Lesson 19 of 120

Strings

Text in Java.

⏱ 2 min read▶ Video at 24:51🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

A String is a piece of text. A name, a sentence, or a whole paragraph. In Java, strings are written in double quotes.

  • A piece of text
  • In double quotes
  • Used everywhere

Making strings

String, with a capital S, is the type. An empty string has nothing between the quotes. Length tells us how many characters a string has. Char at gives one character, by position. Positions start at zero, so the last one is at length minus one. Run it. Lisbon has six letters, from L to n.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String city = "Lisbon";
        String empty = "";
        System.out.println("City: " + city);
        System.out.println("Letters: " + city.length());
        System.out.println("Empty has " + empty.length() + " letters");
        System.out.println("First letter: " + city.charAt(0));
        System.out.println("Last letter: " + city.charAt(city.length() - 1));
    }
}
Output
City: Lisbon
Letters: 6
Empty has 0 letters
First letter: L
Last letter: n

Positions start at zero

In Lisbon, L is at position zero, i at one, and so on, up to n at five. This is called an index. Almost everything in Java counts from zero. Asking for a position past the end, crashes the program.

keyvalue
L i s b o n0 1 2 3 4 5
FirstcharAt(0)
LastcharAt(length() - 1)
Too faran exception

Strings never change

Here, we call to upper case on word, but don't keep the result. Then we store the result back in word. Run it. The first print is still lower case! String methods never change the original. They make a new string. So you must keep the result.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String word = "java";
        word.toUpperCase();
        System.out.println(word);
        word = word.toUpperCase();
        System.out.println(word);
    }
}
Output
java
JAVA

Summary

A String is text in double quotes. Length counts the characters, and char at reads one, counting from zero. Strings never change, so keep the result. Next, joining strings.

Key takeaways
  • "double quotes"
  • length(), charAt()
  • Strings never change
Next up: Joining Strings — plus, concat, join