Table of Contents
The String length() method in Java is a simple yet powerful tool for working with string data. In this comprehensive guide, we‘ll cover everything you need to know to effectively use length() in your code.
What is the String length() Method?
The length() method is a member method of Java‘s String class that returns the number of characters contained in a string. Here is a basic example:
String myString = "Hello World";
int length = myString.length(); // length = 11
This makes length() useful for:
- Getting the length of a string for validation or size checks
- Iterating through each character in a string via a loop
- Substring operations
- Comparing strings
- String buffer and builder operations
- Encoding or decoding strings
- And many other string manipulation tasks
How length() Works Internally
Under the hood, length() works by determining the number of 16-bit Unicode characters exists between the start and end of the string as represented internally in memory.
The String class stores strings as arrays of characters, similar to a char array. So length() just returns the length property of this internal array.
Here‘s a visual representation:
String: "Hello World"
Internal char array:
___________________
| H | e | l | l | o | | W | o | r | l | d | \0 |
--------------------
0 1 2 3 4 5 6 7 8 9 10
length() = 11
So length is essentially the index of the last actual character plus one, to count the extra null terminating character.
This also means the maximum length of a Java string is Integer.MAX_VALUE, or 2^31 – 1, since that‘s the max array size.
When to Use length()
Here are some common use cases where length() comes in handy:
1. String Validation
You can check if a string meets length requirements:
String password = "123";
if (password.length() < 8) {
System.out.println("Password must be at least 8 characters");
}
This validates the password is long enough before allowing registration, for example.
2. Looping Through Strings
You can iterate through each character in a string with a for loop:
String str = "Hello";
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(i));
} // prints out each char
Here we use length() to set the terminating condition of the loop.
3. Substring Creation
Extract a substring using index values based on length:
String str = "World";
String sub = str.substring(0, str.length()-2); // "Wo"
By subtracting from length(), we can get the last characters.
4. Comparing String Lengths
Compare strings by their character count:
String str1 = "Apple";
String str2 = "Banana";
if (str1.length() > str2.length()) {
System.out.println(str1 + " is longer than " + str2);
} else if (str1.length() == str2.length()) {
System.out.println("Strings are equal length");
}
This prints out comparisons based on the string lengths.
5. Finding Display Widths
Determine display widths for padding strings:
String text = "Hello";
int width = 20;
// calculate padding
int pad = width - text.length();
// display padded
System.out.println(text + new String(new char[pad]).replace("\0", " "));
Here we use length() to calculate space for padding the string to a certain total width.
6. Encoding/Decoding
Base64 encoding can use length() to determine decoded buffer size:
String encoded = "U29tZSBTdHJpbmc=";
byte[] buf = new byte[encoded.length()*3/4]; //allocate bufferbased on length
Base64.Decoder decoder = Base64.getDecoder();
decoder.decode(encoded, buf);
System.out.println(new String(buf)); // "Some String"
Similar usage applies for any type of string encoding/decoding.
So in summary, length() can be used for:
- Validation and input rules
- Looping and substring operations
- Comparing strings
- Formatting display strings
- Encoding and decoding strings
And much more! It‘s one of the most widely applicable String methods.
length() Explained Through Examples
Let‘s now go through some detailed examples to see length() used in different scenarios.
Example 1: Get String Length
This simple example prints out the basic length of a hardcoded string:
public class Main {
public static void main(String[] args) {
String message = "Hello World";
int length = message.length();
System.out.println("The length of the message is: " + length);
}
}
// Output: The length of the message is: 11
We assign the string "Hello World" to a variable called message.
Then we get the length using message.length() and store it in the integer variable length.
Finally we print out the value of length, displaying 11.
So you can see it gives the number of Unicode characters, including spaces and punctuation.
Next let‘s try getting input from the user.
Example 2: String Length of User Input
Here‘s an example that gets string input from the user and prints out the length:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter any string: ");
String userInput = scanner.nextLine();
int length = userInput.length();
System.out.println("You entered: " + userInput);
System.out.println("Length is: " + length);
}
}
// Enter any string: Hello World!
// You entered: Hello World!
// Length is: 13
Now instead of hardcoding the string, we allow input with Scanner.
We get the input string, get its length, then print out both the original string and the length.
This shows that length() works the same whether hard-coded or user input.
Let‘s build on this example next.
Example 3: Validating String Length
Here is an example that validates a user-provided password meets length criteria:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
final int MIN_LENGTH = 8;
System.out.print("Choose a new password (min " + MIN_LENGTH + " chars): ");
String password = scanner.nextLine();
if (password.length() < MIN_LENGTH) {
System.out.println("Password too short! Must have " + MIN_LENGTH + " chars.");
} else {
System.out.println("Password accepted.");
}
}
}
// Choose a new password (min 8 chars): 123
// Password too short! Must have 8 chars.
// Choose a new password (min 8 chars): mypassword
// Password accepted.
Here we check if the user‘s password meets a minimum length requirement.
We define a constant MIN_LENGTH, then compare input.length() to that constant to validate.
If too short, we output a warning – otherwise it is accepted.
So this shows how to easily validate string sizes using length().
Example 4: Counting Character Occurrences
Here is an example that counts how many times a given character occurs in a string:
public class Main {
public static void main(String[] args) {
String message = "Hello World. Hello All.";
char charToCheck = ‘l‘;
int count = 0;
for(int i = 0; i < message.length(); i++) {
if(message.charAt(i) == charToCheck) {
count++;
}
}
System.out.println("The character " + charToCheck +
" appears " + count + " times.");
}
}
// Output: The character l appears 3 times.
We use length() in our for loop condition to iterate through each index of the string.
Inside the loop, we grab each char with charAt() and compare it to our target. If match, increment counter.
Finally we print the total count of matches after looping through the whole string length.
This shows how length() can facilitate operations across all characters.
Example 5: Creating a Random Password
Here is a useful example that generates a random password of a given length:
import java.util.*;
public class Main{
public static void main(String[] args) {
int length = 10;
System.out.println(generatePassword(length));
}
public static String generatePassword(int length) {
String symbols = "~`!@#$%^&*()-_=+[]{}|;:,.<>/?";
String numbers = "0123456789";
String lowercase = "abcdefghijklmnopqrstuvwxyz";
String uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String allowedChars = "";
allowedChars += symbols;
allowedChars += numbers;
allowedChars += lowercase;
allowedChars += uppercase;
Random random = new Random();
char[] password = new char[length];
for(int i = 0; i < length ; i++) {
password[i] =
allowedChars.charAt(random.nextInt(allowedChars.length()));
}
return new String(password);
}
}
// Output: n5mA@?!W7x02
Here length() is used to both set the length, and to get a random index bounded by the number of allowed chars.
We build up a string of allowed characters, get its length, then use that length with Random to pick a random one for each position in the password char array based on the requested total length.
This demonstrates how flexible length() can combine with Random and arrays to create randomized strings.
Example 6: Removing End of String
Here is some substring logic that removes the end of a string based on length:
public class Main {
public static void main(String[] args) {
String message = "Hello World";
int length = message.length();
//remove last 5 chars
String trimmedString = message.substring(0, length - 5);
System.out.println(trimmedString);
}
}
// Output: Hello
We get the total length, then substring from 0 to length minus 5. This removes "World", leaving just "Hello".
This shows how subtracting from length() can let you trim off the end of a string.
Example 7: Encoding/Decoding Base64
Finally, here is length() being used to facilitate Base64 encoding and decoding:
import java.util.Base64;
public class Main {
public static void main(String[] args) {
try {
String original = "Hello World";
Base64.Encoder encoder = Base64.getEncoder();
String encoded = encoder.encodeToString(original.getBytes("utf-8"));
byte[] bytes = new byte[encoded.length()];
Base64.Decoder decoder = Base64.getDecoder();
decoder.decode(encoded, bytes);
String decoded = new String(bytes, "utf-8");
System.out.println("Original: " + original);
System.out.println("Encoded: " + encoded);
System.out.println("Decoded: " + decoded);
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
// Output:
// Original: Hello World
// Encoded: SGVsbG8gV29ybGQ=
// Decoded: Hello World
We use .length() to allocate the byte array for decoding the exact right size, based on the encoded length.
This allows us to reuse the byte buffer across multiple decodings, rather than hard-coding a size that might be too small or wasting space.
So length() can optimize memory usage in encoding/decoding operations.
length() Rules and Gotchas
While length() is generally straightforward, there are some edge cases to keep in mind:
- Empty strings – "".length() returns 0
- Null strings cause a NullPointerException
- Multibyte chars – Some Unicode chars may count as 2+ chars toward length
- Surrogate pairs – High/low surrogates for extended codes take 2 chars
- Shared backing arrays – Changes in one String may affect length() in others
- Streaming access can make getting a definitive length difficult or impossible
So in certain cases – like external sources, streaming data, or highly dynamic usage – getting an exact definitive length may be tricky.
But for most typical string usage, length() will correctly report the number of chars.
Alternatives to length()
While length() is the standard way to get a Java string‘s length, there are a couple alternatives:
1. String Size in Bytes
If you want the raw byte size of the string‘s backing array, use:
str.getBytes().length
However this reflects the UTF encoding rather than actual chars.
2. Regular Expressions Word Count
To count whitespace-delimited words, a regex can be used:
str.split("\\s+").length;
This splits on any whitespace and counts the parts.
So options exist, but length() is best for character count.
Conclusion
The length() method is one of the most simple yet useful String methods in Java. It allows easy access to string sizes for validation, looping, manipulation and more.
Here are some key takeaways:
- length() gives the number of Unicode characters in a String
- It works by getting length of internal char array
- Commonly used for validation, looping, substring operations, comparisons, formatting strings, encoding/decoding, etc
- Watch out for edge cases like empty, null and multibyte strings
- Alternatives exist using bytes or regex, but length() is the standard
Hopefully this article provided a comprehensive overview of length() and how it can be applied. It‘s a string operation you‘ll use again and again when working with string data in Java.
Happy coding!