WeCodeAcademy

Java Strings

A String holds text. Strings are objects, so they come with many useful methods.

ExampleJava
public class Main {
  public static void main(String[] args) {
    String s = "Hello, Java";
    System.out.println(s.length());          // 11
    System.out.println(s.toUpperCase());     // HELLO, JAVA
    System.out.println(s.substring(7));      // Java
    System.out.println(s.indexOf("Java"));   // 7
    System.out.println(s.replace("Java", "World"));
    System.out.println(s.charAt(0));         // H
    System.out.println("a,b,c".split(",").length); // 3

    String a = "hi", b = "hi";
    System.out.println(a.equals(b));         // compare text with equals
    System.out.println(String.format("%s has %d items costing %.2f", "Cart", 3, 9.5));
  }
}
Output
11
HELLO, JAVA
Java
7
Hello, World
H
3
true
Cart has 3 items costing 9.50

Always compare strings with .equals(), not ==: == compares whether two variables point at the same object, not whether the text is the same.

Quick check

How do you compare the text of two strings?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.