Java String length() Method

Filed Under: Java

Java String length() function returns the length of the sequence of characters represented by this object.

Java String length

Sometimes we have to get the length of string in java programs, below code snippet shows you how to do it.


String str = "journaldev";
		
System.out.println("String length is "+str.length());

Above snippet will produce output as:


String length is 10

Let’s say we have a function to print string length like below.


public static void printStringLength(String s){
	System.out.println("input string length is "+s.length());
}

Can you guess what is the problem with above function? Well, it can lead to NullPointerException if someone is calling this function by passing string value as null. Below is a better implementation to avoid NullPointerException.


public static void printStringLength(String s){
	if(s == null) return;
	System.out.println("input string length is "+s.length());
}

Note that I am just ignoring and returning the call if input is null, you can log it or throw Exception or do anything else based on your requirement.

Java String Length for Unicode representation

If you look at the javadoc of String length() method, it says that the length is equal to the number of Unicode code units in the string. What does it mean? Let’s look at a small code snippet to easily understand meaning of this statement.


String str1 = "\u00A9"; //copyright character
		
System.out.println("String length is "+str1.length());

When you will run above program, string length will be printed as 1. In java, we can use Unicode characters to define a String and above unicode is for copyright character. Hence the length of String is 1 and if you will try to print it, it will be shown as ©.

Here is the final java string length program.


package com.journaldev.string;

public class JavaStringLength {

	public static void main(String[] args) {
		String str = "journaldev";

		System.out.println("String length is " + str.length());

		String str1 = "\u00A9";

		System.out.println("Unicode String length is " + str1.length());

		System.out.println("Unicode string value = "+str1);

		printStringLength(null);
	}

	public static void printStringLength(String s) {
		if (s == null)
			return; // do nothing
		System.out.println("input string length is " + s.length());
	}
}

Below image shows the output produced by above program.

java string length

Java String length without using length() function

This is a very interesting interview question, there are many alternative and non-recommended ways to get length of string. Let’s just look at these, good for arguments but don’t use in production environment.

Converting to character array and finding length


public static int getStringLength(String s) {
	int count = 0;
	char [] ca = s.toCharArray();
	for (char c : ca) {
		count++;
	}
	return count;
}

Calling length of character array


public static int getStringLength(String s) {
	return s.toCharArray().length;
}

Using String lastIndexOf() function cleverly


public static int getStringLength(String s) {
	return s.lastIndexOf("");
}

I am sure there will be other funny ways to find string length without using length() function, I guess above are the easiest ones. That’s all for java string length example program.

References: API Doc, StackOverflow Article

Comments

  1. Atul says:

    usnig lastindexof, we will get the length-1.

  2. viktor says:

    Your article not full
    String.codePointCount is used for count surrogate characters

    String val1 = “\u5B66\uD8F0\uDE30”;
    System.out.println(“character count: ” + val1.length());
    System.out.println(“code points: “+ val1.codePointCount(0, val1.length()));

    output

    character count: 3
    code points: 2

    1. Pankaj says:

      I didn’t understood what you are trying to say here. You have 3 unicode characters in the string, so the length output is 3. Am I missing something?

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages