Java Strings
A String in Java is an object that holds a sequence of characters, such as a word, a sentence, or an entire paragraph. Strings are one of the most-used types in real programs, so getting comfortable with them early pays off.
Creating a String
You create a String by wrapping text in double quotes and assigning it to a variable of type String. Because String is a class (not a primitive), its name begins with a capital S. Once created, the text can be printed, measured, searched, and transformed using the many methods the String class provides.
Declaring and printing a String
public class Main {
public static void main(String[] args) {
String greeting = "Hello, Java!";
System.out.println(greeting);
}
}String Length
Every String can tell you how many characters it contains through the length() method. Notice the parentheses: length() is a method call for Strings, unlike arrays where length is a field without parentheses. This is a common source of confusion for beginners.
Measuring a String
String name = "Programming";
System.out.println("Characters: " + name.length()); // 11Common String Methods
The String class ships with dozens of helper methods. A few you will reach for constantly are shown below. Remember that these methods do not change the original String; they return a brand new one, because Strings in Java are immutable.
Using String methods together
String title = " java Basics ";
System.out.println(title.trim()); // "java Basics"
System.out.println(title.trim().toUpperCase()); // "JAVA BASICS"
System.out.println("java Basics".indexOf("Basics")); // 5- Use double quotes for String values; single quotes are only for a single char.
- length() counts every character, including spaces and punctuation.
- Chain methods left to right, for example text.trim().toLowerCase().
- To compare text, use equals() rather than == so you compare content, not object identity.
Exercise: Java Strings
What does == actually compare when used on two String objects?