Java String length() Method: How to Get a String’s Size (Example)
Understanding Java’s String.length() Method
The length() method is a core part of Java’s String API. It returns the number of 16‑bit Unicode code units in a string, which is effectively the string’s size in characters for most text. This method is read‑only; it does not modify the string itself.
Syntax
public int length()
Parameters: None
Return Value: The number of characters (Unicode code units) in the string.
Practical Example
Below is a simple Java program that demonstrates how to retrieve the length of two different strings. The output shows the numeric result for each string.
public class SampleString {
public static void main(String[] args) {
// Define two String objects
String s1 = "Hello Java String Method";
String s2 = "RockStar";
// Use length() to get the size of each string
int length1 = s1.length();
System.out.println("Length of s1: " + length1);
System.out.println("Length of s2: " + s2.length());
}
}
Output:
Length of s1: 24 Length of s2: 8
Why It Matters
Knowing a string’s length is fundamental for tasks such as input validation, text parsing, and buffer allocation. Because length() operates in constant time, it’s efficient even for very long strings.
Java
- Master Java String Manipulation: Essential Functions, Methods, and Practical Examples
- Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example
- Mastering Java's String compareTo() Method: Syntax, Use Cases, and Practical Examples
- Java String.contains() Method: How to Check for Substrings – Practical Examples
- Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
- Java Abstraction: Mastering Abstract Classes, Methods, and Practical Examples
- Mastering Java's split() Method: A Practical Guide with Code Examples
- Reading Files in Java with BufferedReader – A Practical Guide with Examples
- Python len(): A Practical Guide to Measuring Object Lengths
- Master Python's String.find() Method: Syntax, Examples & Alternatives