← Chapter 3 — Strings, Escapes & Math

13. String Methods & Concatenation

mixed

Description

Strings let a program store labels, names, messages, and other text. Concatenation joins pieces of text with the + operator.

String methods return information or a new String. They do not change the original String because String objects are immutable.

Subtopics

Joining text

Description

Concatenation combines values into a message.

Explanation

When one operand is a String, + converts the other value to text.

Example

String message = "Hello, " + "Aditi";

Useful methods

Description

length, toUpperCase, and contains inspect text.

Explanation

Store a returned value if you need the changed version.

Example

String shout = name.toUpperCase();

Explanation

For a few pieces of text, + is clear. For many changes in a loop, StringBuilder is usually a more efficient choice.

Example

public class StringMethodsDemo {
    public static void main(String[] args) {
        String name = "Rohan";
        String greeting = "Hello, " + name.toUpperCase();
        System.out.println(greeting);
    }
}

Key points

  • Strings are immutable.
  • + joins text.
  • Methods return new String values.

Open reference