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.
A String is created by enclosing text in double quotes "".
public class Main {
public static void main(String[] args) {
String greeting = "Hello, World!";
System.out.println(greeting);
}
}
The String class has many useful methods for performing operations on strings.
The length() method returns the number of characters in a string.
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
The toUpperCase() and toLowerCase() methods convert a string to all uppercase or all lowercase letters.
String txt = "Hello World"; System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD" System.out.println(txt.toLowerCase()); // Outputs "hello world"
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.
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7
The + operator can be used between strings to combine them. This is called concatenation.
String firstName = "John"; String lastName = "Doe"; System.out.println(firstName + " " + lastName);
You can also use the concat() method:
String firstName = "John";
String lastName = "Doe";
System.out.println(firstName.concat(" ").concat(lastName));