Java Strings

Java Strings

Strings are used for storing text. A String variable in Java contains a sequence of characters and is a non-primitive (reference) type.

String objects are immutable, which means once a String object is created, its value cannot be changed.


Creating Strings

A String is created by enclosing text in double quotes "".

Creating a String

public class Main {
  public static void main(String[] args) {
    String greeting = "Hello, World!";
    System.out.println(greeting);
  }
}

Common String Methods

The String class has many useful methods for performing operations on strings.

String Length

The length() method returns the number of characters in a string.

String Length

String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());

Changing Case

The toUpperCase() and toLowerCase() methods convert a string to all uppercase or all lowercase letters.

Changing Case

String txt = "Hello World";
System.out.println(txt.toUpperCase());   // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase());   // Outputs "hello world"

Finding a Character

The indexOf() method returns the index (the position) of the first occurrence of a specified text in a string (including whitespace). Java counts positions from 0.

Finding a Character

String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7

String Concatenation

The + operator can be used between strings to combine them. This is called concatenation.

String Concatenation

String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);

You can also use the concat() method:

concat() Method

String firstName = "John";
String lastName = "Doe";
System.out.println(firstName.concat(" ").concat(lastName));