0
0
JavaHow-ToBeginner · 3 min read

How to Find Length of String in Java - Simple Guide

In Java, you can find the length of a string by using the length() method on a string object. For example, myString.length() returns the number of characters in myString.
📐

Syntax

The syntax to find the length of a string in Java is simple:

  • stringVariable.length() - calls the length() method on the string variable.
  • This method returns an integer representing the number of characters in the string.
java
int length = stringVariable.length();
💻

Example

This example shows how to find and print the length of a string in Java.

java
public class StringLengthExample {
    public static void main(String[] args) {
        String greeting = "Hello, friend!";
        int length = greeting.length();
        System.out.println("Length of string: " + length);
    }
}
Output
Length of string: 14
⚠️

Common Pitfalls

Common mistakes when finding string length include:

  • Trying to use length without parentheses, which is incorrect for strings (it works for arrays).
  • Calling length() on a null string, which causes a NullPointerException.

Always ensure the string is not null before calling length().

java
/* Wrong way: missing parentheses */
// int len = myString.length; // This causes a compile error

/* Right way: use parentheses */
int len = myString.length();

/* Null check example */
if (myString != null) {
    int len = myString.length();
} else {
    System.out.println("String is null");
}
📊

Quick Reference

OperationDescriptionExample
Get lengthReturns number of characters in stringmyString.length()
Null checkAvoid NullPointerExceptionif (myString != null) {...}
Arrays lengthUse .length without parentheses for arraysmyArray.length

Key Takeaways

Use the string's length() method with parentheses to get its length.
Never call length() on a null string to avoid errors.
Remember length() is a method for strings, not a property.
For arrays, use .length without parentheses instead.
Check for null before calling length() to write safe code.