Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

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

  1. Master Java String Manipulation: Essential Functions, Methods, and Practical Examples
  2. Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example
  3. Mastering Java's String compareTo() Method: Syntax, Use Cases, and Practical Examples
  4. Java String.contains() Method: How to Check for Substrings – Practical Examples
  5. Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
  6. Java Abstraction: Mastering Abstract Classes, Methods, and Practical Examples
  7. Mastering Java's split() Method: A Practical Guide with Code Examples
  8. Reading Files in Java with BufferedReader – A Practical Guide with Examples
  9. Python len(): A Practical Guide to Measuring Object Lengths
  10. Master Python's String.find() Method: Syntax, Examples & Alternatives