String Length ExampleUse the length method on strings to get their character counts.
This page was last reviewed on Dec 30, 2021.
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.
Detail The plus-operator combines strings. We combine the data from two or more strings this way.
String Concat
Detail We call the length method on each 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
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.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 30, 2021 (edit link).
© 2007-2023 Sam Allen.