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.
Here 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);
}
}3
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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.