Length
A Java String
object may be null
—but if it exists, it has zero or more characters. This character count is its length. With length()
we get this number.
In a loop over characters, we can proceed from 0 to length()
minus 1. A string
's length has many uses in programs. We can take the length of a literal directly.
We use string
literals. These are specified directly in the program. Then with the plus operator, we combine (concatenate) these strings.
string
variable reference. This returns the character count.public class Program { public static void main(String[] args) { // Create strings with literals. String value1 = "Java"; String value2 = "Programmer"; // Concatenate strings. String value3 = value1 + " " + value2; // Print string. System.out.println(value3); // Get string lengths. int length1 = value1.length(); int length2 = value2.length(); int length3 = value3.length(); // Print lengths. System.out.println(length1); System.out.println(length2); System.out.println(length3); } }Java Programmer 4 10 15
This program uses a literal "abc" and immediately takes the length of that literal. This returns the number 3. This is valid Java syntax.
public class Program { public static void main(String[] args) { // Take the length of a literal directly. int length = "abc".length(); System.out.println(length); } }3
When using string
literals in a program, we want to avoid confusing code. It is clearer to use length()
on a literal than encode the magic value 3 in a program.
The length()
method is called on a String
object. The String
must not be null
. Length
returns the character count in the string data.