Java String Manipulation Methods
String Length
Methods used to obtain information about objects are known as accessor methods.
The String class provides an accessor method called length(), which returns the number of characters contained in a string object.
The following code will result in the len variable being equal to 14:
public class StringExample {
public static void main(String args[]) {
String website = "www.example.com";
int len = website.length();
System.out.println("Website length: " + len);
}
}
When compiled and executed, the above code produces the following output:
Website length: 14
String Concatenation
The String class provides methods to concatenate two strings:
string1.concat(string2);
This returns a new string with string2 concatenated to string1. The concat() method can also be used with string literals, like:
"My name is ".concat("John");
However, the more common approach is to use the '+' operator for string concatenation:
"Hello, " + "world" + "!"
The result is:
"Hello, world!"
Here's an example:
public class StringConcat {
public static void main(String args[]) {
String prefix = "Site: ";
System.out.println(prefix + "www.example.com");
}
}
When compiled and executed, the above code produces the following output:
Site: www.example.com
Creating Formatted Strings
We know that printf() and format() methods can be used to format numeric output.
The String class uses a static method format() that returns a String object rather than a PrintStream object.
The static format() method of the String class can be used to create reusable formatted strings, not just for one-time print output.
For example:
System.out.printf("Float value: " + "%f, Integer value: " + " %d, String value: " + "is %s", floatVar, intVar, stringVar);
You can also write it like this:
String formattedString;
formattedString = String.format("Float value: " + "%f, Integer value: " + " %d, String value: " + " %s", floatVar, intVar, stringVar);