Java String Length ExampleUse the length method on strings to get their character counts.
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.
An example. We use string literals. These are specified directly in the program. Then with the plus operator, we combine (concatenate) these strings.
Concat The plus-operator combines strings. We combine the data from two or more strings this way.
Length We call the length method on each string variable reference. This returns the character count.
Java program that uses strings
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
Literal length. This program uses a literal "abc" and immediately takes the length of that literal. This returns the number 3. This is valid Java syntax.
Java program that uses length, literal
public class Program { public static void main(String[] args) { // Take the length of a literal directly. int length = "abc".length(); System.out.println(length); } }
Some notes. 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.
A summary. The length() method is called on a String object. The String must not be null. Length returns the character count in the string data.
© 2007-2022 sam allen.
see site info on the changelog.