Java String length() method
Syntax and Examples

Java String length() Method

Introduction

The length() method in Java is a fundamental tool for working with strings. It simply tells you how many characters are present within a string. Think of it like counting the letters in your name or words in a sentence – that's essentially what this method does.

Syntax

public int length()

Parameters

Parameter Description
None This method doesn't accept any input parameters.

Return Value

The length() method returns an integer representing the number of characters in the string.

Examples

Example 1: Basic String Length

Let's start with a simple example to illustrate how length() works. We'll create a string and then use length() to find out its length.

public class StringLengthExample1 {
  public static void main(String[] args) {
    String myString = "Hello, World!";
    int stringLength = myString.length();
    System.out.println("The length of the string is: " + stringLength);
  }
}
The length of the string is: 13

In this example, `myString` contains "Hello, World!". The length() method returns 13 because there are thirteen characters in the string (including the space and the exclamation mark).

Example 2: Empty String

What happens when we use length() on an empty string? Let's find out.

public class StringLengthExample2 {
  public static void main(String[] args) {
    String emptyString = "";
    int length = emptyString.length();
    System.out.println("The length of the string is: " + length);
  }
}
The length of the string is: 0

As expected, an empty string has a length of zero.

Example 3: String with Unicode Characters

Java strings can contain Unicode characters. Let's see how length() handles those.

public class StringLengthExample3 {
  public static void main(String[] args) {
    String unicodeString = "你好世界"; // Chinese for "Hello World" 
    int length = unicodeString.length();
    System.out.println("The length of the string is: " + length);
  }
}
The length of the string is: 4

Even though '你好世界' looks like four characters, each character in this string is represented by one code point. The `length()` method returns the number of code points (characters) in the string.

Example 4: String Derived from User Input

Often you’ll get strings from user input – let's see how to use `length()` with that kind of data.

import java.util.Scanner;

public class StringLengthExample4 {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter a string: ");
    String userInput = scanner.nextLine();

    int length = userInput.length();
    System.out.println("The length of your input is: " + length);

    scanner.close();
  }
}

This example prompts the user to enter a string, then calculates and prints its length.