How to work with strings

Create and combine strings

String literals use double quotes. The + operator concatenates text and values.

String first = "Ada";
String message = "Hello, " + first + "!";
System.out.println(message);

Use common methods

Strings are immutable, so methods return new strings rather than changing the original.

String raw = "  Java Course  ";
String clean = raw.trim().toLowerCase();
System.out.println(clean.length());

Compare content

Use equals to compare string content. The == operator compares object references and is not the right content test.

String answer = new String("yes");
System.out.println(answer.equals("yes")); // true
System.out.println(answer == "yes");      // usually false

Read characters and substrings

Indexes start at zero. The end index of substring is excluded.

String word = "Java";
System.out.println(word.charAt(0));
System.out.println(word.substring(1, 3)); // av