View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

What is String Length Java? Methods to Find String Length with Examples

By Pavan Vadapalli

Updated on May 28, 2025 | 18 min read | 7.27K+ views

Share:

Did you know? When a system rejects your password as weak, it’s often due to a simple check—string length Java. Requiring at least eight character blocks around 50,000 common English words between three and seven letters, cutting down a huge number of easy-to-crack passwords. Just length alone makes a big difference.

In Java, understanding string length Java is crucial because it refers to the total number of characters a string holds. This count includes letters, digits, symbols, spaces, and even invisible characters like newline (\n). To find this length, Java offers a built-in method called length(). Understanding how this method works is key to handling tasks like input validation, data parsing, and formatting output correctly. 

Though it sounds simple, measuring string length in Java has some nuances. For example, the length() method counts UTF-16 code units, so some characters, like emojis, may count as two, not one. This blog covers the main process, alternative approaches, practical examples, common pitfalls, and tips to handle tricky cases, helping you avoid bugs and write cleaner code.

 

Master Java and more with upGrad’s Software Development course featuring an updated Generative AI curriculum and specializations in Cyber Security, Full Stack Development, Game Development, and more. Build a strong foundation with hands-on projects, expert mentorship, and training on the latest tools and languages!

What is String Length Java? Definition & Core Concepts

In Java, the length of a string refers to the number of characters it contains, including letters, digits, spaces, punctuation, and special symbols. For example, the string "Hello, India!" has a length of 13 characters.

What is Substring?

A substring is simply a smaller section of a string. For example, in the string "Hello, India!", the substring "India" is a portion extracted from the full string. It’s important to note that when using the substring() method, the second index is exclusive, meaning it does not include the character at that position. For example, "Hello, India!".substring(7, 12) will return "India".

 

The length() method in Java returns the number of UTF-16 code units in a string, not necessarily the number of Unicode characters. This distinction is important because some characters, like emojis or certain accented letters, may be represented by more than one code unit.

 

Why is knowing the string length in Java important?

Understanding string length in Java is essential because strings appear everywhere in programming — usernames, addresses, phone numbers, or data fetched from external sources like files or APIs.

 

Additionally, while string length can influence memory usage, it’s more helpful in preventing allocation errors or optimizing data handling, as the length determines how much memory Java allocates for the string.

 

Lastly, it's key to remember that the .length() method is specific to strings (as integers) and should not be confused with .length used for arrays. This distinction is a common source of bugs in Java.

 

It’s time to build on this foundation and deepen your programming skills. Whether you’re aiming to become a software developer, enhance your coding expertise, or prepare for tech interviews, upGrad offers courses tailored to your goals. Here are three programs that can help you sharpen your skills and advance your career:

 

 

Here’s an example to understand string length in Java better:

public class StringLengthExample {
    public static void main(String[] args) {
        String city = "Bengaluru, India!";
        int length = city.length();
        System.out.println("Length of string: " + length);
    }
}

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Output:
Length of string: 18

Output Explanation: 
In the string "Bengaluru, India!", there are 18 characters in total. The .length() method counts every character, including letters, commas, spaces, and the exclamation mark. So, it counts: B, e, n, g, a, l, u, r, u, ,, (space), I, n, d, i, a, !

This demonstrates how the .length() method works with strings containing spaces and punctuation. Understanding it well will help you handle strings confidently and avoid common pitfalls in your code.

Now, let’s move ahead and understand the application of the length method to get the string size Java. 

Applying the Length Method to Get String Size in Java

The .length() method is the standard built-in method to find the string length Java, returning the number of characters it contains.It’s a built-in method of the String class that returns an integer representing the total number of characters in the string, including spaces, punctuation, and special symbols.

 

Example:

public class LengthDemo {
    public static void main(String[] args) {
        String message = "Namaste India!";
        System.out.println("Message length: " + message.length());
    }
}

 

Output:
Message length: 13

Output Explanation: 
In this example, the string "Namaste India!" contains 13 characters. Notice that the space between "Namaste" and "India" and the exclamation mark at the end are counted as characters too. The .length() method directly returns the stored length of the string, which is maintained internally by the Java runtime. Therefore, it is a constant-time operation, with a time complexity of O(1). This ensures that retrieving the length of a string is fast and efficient, regardless of the string's size.

 

Also Read: Exploring Java Architecture: A Guide to Java's Core, JVM and JDK Architecture

Getting the Substring Length in Java

Sometimes, you may not need the entire string length, but only a part of it. In such cases, you can calculate the substring length Java using the substring() method. To measure the length of a specific portion of a string, use substring() to extract it, then apply .length(). Once you have the substring length Java, you can apply .length() to find out how many characters that part contains.

 

Example: 

public class SubstringLengthExample {
    public static void main(String[] args) {
        String fullString = "Hello Mumbai!";
        String part = fullString.substring(6, 12); // extracts "Mumbai"
        System.out.println("Substring: " + part);
        System.out.println("Length of substring: " + part.length());
    }
}

Output:
Substring: Mumbai
Length of substring: 6

 

Output Explanation: 
The substring(6, 12) method extracts characters starting from index 6 up to, but not including, index 12. Java strings use zero-based indexing, meaning the first character is at index 0. The second index is exclusive, so index 12 (the exclamation mark) is not included. The substring "Mumbai" has 6 characters, and calling .length() on it returns 6. This distinction is important as it's a frequent source of errors when working with string indices in Java.

 

Take your first step towards mastering JavaScript with upGrad’s course on JavaScript Basics. With 19 hours of learning, you'll cover key concepts like Variables, Policy Influence, and Conditionals, while gaining hands-on experience and expert mentorship. Learn at your own pace and build a strong foundation in JavaScript to kickstart your coding career. Start today!

 

Meanwhile, this is not the only way to get the length of string Java. Let’s look at some alternative methods. 

5 Alternative Ways to Find String Length in Java

While .length() is the most common and straightforward way to get a string’s length, there are situations where other methods come in handy. Depending on your specific needs, like working with character arrays, mutable strings, Unicode characters, and different data types like integers, floats, or booleans within your strings, you may want to explore these alternatives. Additionally, third-party libraries can provide more specialized functionality for string manipulation in Java.

1. Using toCharArray() and Getting the Array Length

You can convert a string into a char array, where each character becomes an element in the array. Then, by checking the length of this array in Java, you indirectly find the string’s length. This method might be useful if you're manipulating the string (e.g., removing whitespace or performing transformations) before counting the characters. It allows for more flexibility when you need to perform specific operations on the individual characters.

public class CharArrayLength {
    public static void main(String[] args) {
        String name = "Delhi";
        char[] chars = name.toCharArray();
        System.out.println("Length using char array: " + chars.length);
    }
}

Output:
Length using char array: 5

Explanation: 
Here, "Delhi" is converted into a char[] containing each letter separately. The array’s .length property returns how many characters the string has.

 

Also Read: Difference Between Array and String

2. Counting Characters Manually with a Loop

Although less efficient, manually looping through characters lets you process each character as you count. This can be useful if you want to perform additional checks or transformations during counting. For example, if you want to count only the digits in a string or skip whitespaces, this approach gives you the flexibility to apply custom logic.

public class ManualLength {
    public static void main(String[] args) {
        String input = "Pune 123";
        int count = 0;
        for(char c : input.toCharArray()) {
            // Only count digits, skip spaces
            if(Character.isDigit(c)) {
                count++;
            }
        }
        System.out.println("Count of digits: " + count);
    }
}

 

Output: 
Count of digits: 3

 

Explanation: 
In this example, the loop counts only the digits ('1', '2', '3') in the string "Pune 123", skipping non-digit characters like letters and spaces. This method provides control over the counting process, which the .length() method doesn't allow.

 

Also Read: What is Mutable and Immutable in Python? Definitions, Data Types, Examples, and Key Differences

3. Using StringBuilder or StringBuffer Length

If you’re working with mutable strings, i.e., strings that can change after creation, like StringBuilder or StringBuffer, these classes provide their own .length() method to get the current number of characters.

public class StringBuilderLength {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Chennai");
        System.out.println("StringBuilder length: " + sb.length());
    }
}

Output:
StringBuilder length: 7


Explanation: 
StringBuilder objects are often used when building or modifying strings dynamically. Its .length() method tracks the current size, which can change as you append or delete characters.


Also Read: StringBuffer vs. StringBuilder: Difference Between StringBuffer & StringBuilder

4. Using codePointCount for Unicode-Aware Length

Java’s .length() method counts UTF-16 code units, which are the building blocks used internally to represent characters. However, certain characters, such as emojis or some complex Unicode characters, may be represented by more than one code unit. As a result, while .length() counts each code unit individually; it may not match the number of visually distinct characters (e.g., an emoji may count as two code units).

 

On the other hand, the codePointCount() method counts actual Unicode code points, providing a more accurate count of visible characters, especially when dealing with characters that use multiple code units.

public class UnicodeLength {
    public static void main(String[] args) {
        String text = "नमस्ते"; // Hindi for Hello
        int length = text.length();
        int codePoints = text.codePointCount(0, text.length());
        System.out.println("Length using length(): " + length);
        System.out.println("Length using codePointCount(): " + codePoints);
    }
}

 

Output:
Length using length(): 6
Length using codePointCount(): 6

Explanation: 
For simple Hindi words, .length() and .codePointCount() may return the same result. However, with complex Unicode characters (like emojis), codePointCount() provides a more accurate count of visible characters.

 

Boost your career with the Data Science with AI Bootcamp, offering 110+ hours of live sessions, 11 hands-on projects, 17 essential tools, and 1000+ assessments. Learn from experts, build real skills, and get personalized career support to land your dream job. Enroll now and start mastering data science and AI!

5. Using External Libraries for String Length in Java

In text-heavy applications, such as natural language processing, transliteration tools, or complex string manipulations common in Indian languages, external libraries like Apache Commons Lang can simplify string handling. For example, StringUtils.length() safely returns the length and handles null strings without throwing exceptions.

import org.apache.commons.lang3.StringUtils;

public class ApacheLength {
    public static void main(String[] args) {
        String text = "Kolkata";
        System.out.println("Length using StringUtils: " + StringUtils.length(text));
    }
}

 

Output:
Length using StringUtils: 7

 

Explanation: 
Unlike .length(), which throws a NullPointerException if the string is null, StringUtils.length() returns 0 for null strings, making your code safer and cleaner. This is particularly useful in form validation or large-scale data processing where nulls are common.

These alternative methods give you flexibility depending on your programming context, whether you’re dealing with mutable strings or Unicode complexities, or need safer handling of null values. Understanding these options allows you to pick the best tool for measuring string length in Java.

Let’s take a closer look at when to use which method to identify string size Java. 

Method

Best Use Case & Advantages

Disadvantages

.length() The standard way to get the length of any Java String. Simple, fast, and built-in. Counts UTF-16 code units; may miscount characters with multiple code units (e.g., emojis).
toCharArray().length When you need to process each character individually or convert a string to a char array. Easy to iterate over characters. Requires extra memory for the char array; less efficient in terms of time and space.
Manual Loop Counting When counting characters, perform additional processing on each character. Customizable per character. More complex and verbose; slower due to explicit iteration and additional processing.
StringBuilder.length() For mutable strings where content changes dynamically. Reflects the current length of the mutable string. Only applicable to StringBuilder or StringBuffer; not a general string method.
codePointCount() When working with complex Unicode characters (e.g., emojis, Indian scripts). Accurately counts Unicode code points. Slightly more complex to use and may require additional handling for multi-code-unit characters.
StringUtils.length() (Apache Commons Lang) When you need safe handling of null strings without exceptions. Null-safe, convenient utility method. Requires adding an external library (Apache Commons Lang).

 

Also Read: SQL For Beginners: Essential Queries, Joins, Indexing & Optimization Tips

Now that you know when to use which method to identify the string length in Java, let’s move towards the practical applications of string length. 

Exploring the Practical Applications of String Length in Java

Understanding the length of the string in Java is essential, as it’s used across many areas of software development. It plays a key role in validating input, formatting content for display, processing data files, and enforcing data security measures. Let’s explore these common uses along with relevant Java examples.

Example 1: Validating Mobile Number Length

Mobile apps, websites, and services that collect phone numbers rely on string length checks to ensure the input matches expected formats. In India, mobile numbers are exactly 10 digits long. Validating this early helps prevent errors like failed messages or incorrect user profiles.

String mobileNumber = "9876543210";
if(mobileNumber.length() == 10) {
    System.out.println("Valid mobile number.");
} else {
    System.out.println("Invalid number length.");
}

 

Example 2: Formatting User Names

User names or product titles that are too long can disrupt UI layouts, especially on mobile devices. By checking the string length, you can trim or truncate the text to maintain a clean and readable interface.

String userName = "Srinivasan Raghunathan";
if(userName.length() > 20) {
    userName = userName.substring(0, 20) + "...";
}
System.out.println(userName);

 

This limits the displayed name to 20 characters, adding ellipsis (...) to indicate truncation. This is a good use case for substring() combined with .length() to handle static text. However, if your UI needs to dynamically adjust text or handle continuous changes (e.g., appending or modifying strings based on user input), using StringBuilder would be more efficient and suitable for managing such dynamic changes.

Example 3: Processing Fixed-Width Data Files

Industries like banking and logistics often exchange data in fixed-width text files. When reading such data, checking the length of each field confirms that it matches the expected size, helping catch data inconsistencies or formatting issues.

 

While the exact code depends on file reading logic, a simple length check like this can be part of data validation:

String fieldData = "1234567890";  // Example fixed-width field
int expectedLength = 10;          // Define expected length for validation
if(fieldData.length() == expectedLength) {
    // Process data
} else {
    // Handle error or log issue
}

 

This step helps ensure smooth data imports and reduces processing errors by validating that each field meets the required length.

 

Take your skills to the next level with the AI-Driven Full-Stack Development bootcamp. This 8-month industry-aligned program offers 100+ live hours, 15+ essential tools, and 18 projects to build your portfolio. Learn from experts, gain hands-on experience, and get ready to launch your career in full-stack development with AI. Enroll today and code your future!

Example 4: Enforcing Password Length for Security

Password policies almost always include minimum length requirements to discourage weak passwords. Checking the length helps enforce this rule before allowing account creation or password changes.

String password = "securePass123";
if(password.length() >= 8) {
    System.out.println("Password length acceptable.");
} else {
    System.out.println("Password too short.");
}

 

This simple validation blocks passwords that are too short, improving overall security.

 

Also Read: How to Find the Length of a String Using length() Method in JAVA

 

Since the usage of string length in Java is so vast, pitfalls are also common. Let’s take a look at common errors faced when applying the code to measure string size in Java.

Common Mistakes & Their Solutions When Finding the Length of the String in Java

While using the .length() method in Java is simple, there are some common mistakes developers can make when working with strings. Here are some errors and their solutions for each one.

1. Difference Between .length() and .length

A frequent confusion arises between the .length() method and the .length property in Java. Both are used to determine the size of an object, but they apply to different types.

  • ..length() is a method used with strings in Java to return the number of characters in the string. It is a function defined in the String class.
  • On the other hand, .length is a final field used with arrays to return the number of elements in the array. It is not a method, but rather a property that directly provides the size of the array.

 

This distinction is crucial because a string is an object in Java, and arrays are not.

 

Common Mistake:

Using .length (without parentheses) when working with strings will result in a compile-time error. Since .length is a property of arrays, you cannot use it with strings, which require the .length() method.

 

Example:

public class LengthDifference {
    public static void main(String[] args) {
        String name = "Hyderabad";
        char[] letters = name.toCharArray();

        // Error: Trying to use .length without parentheses for a string
        System.out.println("String length using length: " + name.length);  // Incorrect
        System.out.println("Array length using length: " + letters.length); // Correct
    }
}


Output:
Compile-time error: The method length() is undefined for the type String

 

Solution:
Ensure you’re using .length() with strings and .length with arrays. Here’s the corrected code:

public class LengthDifference {
    public static void main(String[] args) {
        String name = "Hyderabad";
        char[] letters = name.toCharArray();

        // Correct: Using .length() for strings
        System.out.println("String length using length(): " + name.length());
        
        // Correct: Using .length for arrays
        System.out.println("Array length using length: " + letters.length);
    }
}

Output: 
String length using length(): 9
Array length using length: 9
 

2. Handling Null or Empty Strings

Strings in Java are immutable, meaning once a string is created, its length never changes. However, a string can also be null or empty (""). If you try to call .length() on a null string, you will encounter a NullPointerException.

 

Common Mistake:

Forgetting to check if a string is null or empty before calling .length(). This mistake can cause runtime exceptions and crash the program.

 

Example:

public class NullStringExample {
    public static void main(String[] args) {
        String s = null;

        // Error: Trying to access .length() on a null string
        System.out.println("String length: " + s.length());  // This will throw NullPointerException
    }
}

 


Output: 
Exception in thread "main" java.lang.NullPointerException

Solution:
Always check if the string is null or empty before calling .length(). This can be done with a simple null check, or, for cleaner and more readable code, you can use StringUtils.isEmpty(), which checks both for null and empty strings.

import org.apache.commons.lang3.StringUtils;

public class NullStringExample {
    public static void main(String[] args) {
        String s = null;

        // Correct: Using StringUtils.isEmpty() to check for null or empty
        if(!StringUtils.isEmpty(s)) {
            System.out.println("String length: " + s.length());
        } else {
            System.out.println("String is null or empty");
        }
    }
}

 


Output:
String is null or empty

 

By using StringUtils.isEmpty(), you can more cleanly and safely check whether a string is null or empty, avoiding the potential NullPointerException and making your code easier to read and maintain.

3. Incorrect Handling of Unicode Characters

Java's .length() method counts UTF-16 code units, which can cause problems when dealing with Unicode characters. Some characters (like emojis or characters in languages like Hindi) may be represented by more than one UTF-16 code unit but still represent a single character, leading to incorrect length calculations.

 

Common Mistake:

Misunderstanding that .length() counts UTF-16 code units, not actual Unicode characters, especially when dealing with characters outside the Basic Multilingual Plane (BMP). Java's .length() method returns the number of UTF-16 code units in a string, not necessarily the number of visible characters. This distinction becomes important when dealing with complex scripts, such as Hindi or emojis, where multiple code units may represent a single visible character.

 

Example:

public class UnicodeMistake {
    public static void main(String[] args) {
        String text = "नमस्ते";  // Hindi for Hello

        // Error: .length() will not count this correctly in some cases
        System.out.println("Length using length(): " + text.length());
    }
}

 

Output:
Length using length(): 6

 

Here, for the Hindi word "नमस्ते" (Namaste), the .length() method will count each UTF-16 code unit, which may not correspond to the expected number of visible characters. Some characters in complex scripts are represented by multiple code units in UTF-16, which can lead to a discrepancy between the number of code units and the number of visible characters.

 

Note: .length() counts UTF-16 units, not actual user-perceived characters.

 

Solution:

For an accurate count of Unicode characters (especially when dealing with emojis or non-BMP characters), use the codePointCount() method, which counts the actual Unicode characters.

public class UnicodeSolution {
    public static void main(String[] args) {
        String text = "नमस्ते";  // Hindi for Hello

        // Correct: Use codePointCount() for accurate Unicode character count
        int codePoints = text.codePointCount(0, text.length());
        System.out.println("Length using codePointCount(): " + codePoints);
    }
}


Output:
Length using codePointCount(): 6

 

Here, codePointCount() correctly counts the number of Unicode characters in the string.

 

Now that you’ve got a solid understanding of string length in Java, why not take your skills further? upGrad’s free course on Core Java Basics offers expert guidance and hands-on experience to help you strengthen your Java foundation and expand your coding abilities. Start today and unlock the tools to advance your programming career with upGrad.

Improve Your Java Programming Skills with upGrad

Understanding string length in Java is essential for tasks like input validation, data formatting, and security. Whether you're validating phone numbers, formatting user names, or processing data, knowing how to measure string length ensures clean, efficient code. However, common mistakes, like confusing .length() with .length or miscounting Unicode characters, can lead to errors.

 

So, how can you ensure you're mastering these essential skills and taking your Java expertise to the next level? upGrad offers the perfect solution with hands-on learning, expert mentorship, and practical exercises that will help you strengthen your Java foundation and expand your programming abilities. 

Explore our range of courses from beginner level to experts and advance your programming career!

 

Struggling to master core Java concepts or unsure which course can help you take your skills further? Don’t let confusion hold you back. Reach out to upGrad’s expert counsellors for personalized guidance or visit one of our offline centres to find the perfect course that aligns with your goals.

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Reference:  
https://www.baeldung.com/java-regex-password-validation
https://www.sciencedirect.com/science/article/abs/pii/B978159749276800011X

Frequently Asked Questions (FAQs)

1. How do I handle string length issues when working with large datasets in Java?

2. What’s the difference between using .length() for strings and arrays in Java?

3. What happens if I use .length() on an empty string in Java?

4. Can I apply the .length() method to a string literal directly, or should I assign it to a variable first?

5. How do I handle special characters or whitespace when calculating string length?

6. Can .length() be used on StringBuilder or StringBuffer objects?

7. Why do I need to use codePointCount() instead of .length() for certain characters?

8. Is there a performance difference between using .length() and .toCharArray().length?

9. Can .length() return a negative value?

10. How do I safely check for string length when a string could be null?

11. How does the .length() method behave with strings that contain only non-ASCII characters?

Pavan Vadapalli

900 articles published

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s...

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months