The String Methods
Premium Content - Free Preview
As mentioned, the String Class contains a large number of methods. Later, we'll see how to look up classes like String in the Official Java Documentation. I also created a String reference with example code to help beginners. However, since documentation can still be confusing for a beginner, this node will cover the most common String methods!
Strings can be concatenated, or combined, with the
+ operator. For example:
String firstName = "Jim"; String lastName = "Jones"; String fullName = firstName + lastName; System.out.println(fullName);
This will print out:
+ operator is actually a shortcut for the
concat() method. So the 3rd line in the above code can equivalently be written as:
String fullName = firstName.concat(lastName);
There's no reason to use the longer form, but you should realize
+ is really just
concat(), an ordinary method of String.
Unlike instances of most classes, Strings in Java are immutable, which means that a String cannot change after it has been created. Methods that look like they modify a String really just return a new String as a value. For example, the
concat() method above does not change the initial String
firstname, which is why a new variable
fullName was needed to store the result. If you want to change the value of the current String, you can create a new String with the same variable name. For example:
String name = "Jim"; name = name.concat("Jones");
name now equals "JimJones".
charAt(i) - This method returns the
char located at position
i in the String. Strings are numbered like arrays, so the first letter in String
str is at position 0, and the last letter is at position
str.length()-1. For example, the following code grabs the characters 'a', 'b' and 'e':