How to Use Java String Class length() Method

Function Description

The Java String class length() method is used to get the total number of characters count in a string. The length of the string is equal to the number of Unicode characters in the string. In length count, it considers all whitespaces, special characters, numbers, alphabets, etc. like- string “Hello ! 1 #@  ” length will be 12. This string has 2 whitespace characters at the end along with other whitespaces, special characters, alphabets, and a number.

Method  Signature

public int length()

Parameter

None

Return Type

length of a specified sequence of characters in int data type.

Examples of Java String Class length() Method

Example to get the length of string created through String literal and new keyword.

public class ExampleStringLength {
 
    public void StringLength() {

          // String object using string literal

          String string1 = "Welcome to string functions learning";
 
          // String object using new keyword

          String string2 = new String("Learning string length");
 
          // returns the length of the string1 object

          int string1Length = string1.length();
 
          // returns the length of the string2 object

          int string2Length = string2.length();
 
   System.out.println("Length of string1 is = " + string1Length);

   System.out.println("Length of string2 is = " + string2Length);

    }
 
    public static void main(String[] args) {

    ExampleStringLength example = new ExampleStringLength();

    example.StringLength();

    }
 
}
 
Output :

Length of string1 is = 36
Length of string2 is = 22

Example to get the length of blank string object

public class ExampleStringLength {
 
private void zeroLength() {

    // blank string using new keyword

    String str1 = new String();

    // blank string using String literal

    String str2 = "";
         
    // returns the length of the str1 object

    int str1Length = str1.length();
 
    // returns the length of the str2 object

    int str2Length = str2.length();
         
    System.out.println("Length of blank string str1 is = " + str1Length);

    System.out.println("Length of blank string str2 is = " + str2Length);

}
public static void main(String[] args) {

    ExampleStringLength example = new ExampleStringLength();

    example.zeroLength();
}
 
}
 

Output :

Length of blank string str1 is = 0
Length of blank string str2 is = 0

Example:- When NullPointerException has been thrown while using length()

If you will try to use the length() on null object of String, it will throw NullPointerException. To avoid this exception it is necessary to use null check before using length(), if you are not sure about String object to which you want to get the length.

package com.java.test;
 
public class ExampleStringLength {
 
    private void lengthException() {

          //str object is null

          String str = null;

          //str is null so it will throw nullPointerException

          System.out.println(str.length());

    }
 
    public static void main(String[] args) {

          ExampleStringLength example = new 

ExampleStringLength();

          example.lengthException();
    }
 
}
 

Output :

Exception in thread "main" java.lang.NullPointerException

at com.java.test.ExampleStringLength.lengthException(ExampleStringLength.java:42)

at com.java.test.ExampleStringLength.main(ExampleStringLength.java:47)

How to Avoid NullPinterException while using length() Method

To avoid this exception add null check before using length() method.

public class ExampleStringLength {

private void lengthCheck(String str) {

    //To avoid NullPoiterException applying null check     

    if(null != str) {

      //this statement will be executed only when str is not null

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

    }
    
 }
 
    public static void main(String[] args) {

    ExampleStringLength example = new ExampleStringLength();

          //str object is null

          String str = null;

          example.lengthCheck(str);

          //str object has value

          str = "testing";

          example.lengthCheck(str);
         
         
    }
 
}
 

Output : 

Str length is 7
 

In the Example, we gave a call to lengthCheck() method two times. First time we called for null string and second time for some string value “testing”. As the Null check was applied before length() method, the print statement was executed only once, for not null string “testing”.

Other Methods of String Class

SequenceMethodDescription
1char charAt(int index)This method is used to return the character of the string at specified index. First character is at index 0 while last is at string length-1 . StringIndexOutOfBounds Exception is thrown if valid index value is not passed.
2static String format(String format, Object… args)Return the formatted String. It is a static method and formats the string as per passing format and argument(s).
3static String format(Locale l, String format, Object… args)Return the formatted String. It is a static method and formats the string as per passing format and argument(s) and locale.
4String substring(int beginIndex)Returns substring from the given index position to the end index of the string.
5String substring(int beginIndex, int endIndex)Returns substring from the specified begin index to the specified end index.
6boolean contains(CharSequence s)Returns boolean value(true/false). It searches the given sequence of characters within the string and returns true/false accordingly. Characters will be case sensitive while searching in string.
7static String join(CharSequence delimiter, CharSequence… elements)Returns joined string. This method joins each passing String using the specified delimiter. It is a static method.
8static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)Returns the joined string. This method joins each passing string object of an iterate object using the specified delimiter and returns the concatenated string. It is a static method.
9boolean equals(Object another)Returns boolean value(true/false). It checks the equality of string with the passing object.
10boolean isEmpty()Returns boolean value(true/false). It returns true if the string is empty otherwise returns false.
11String concat(String str)Returns the concatenating string. It concatenates the passing string at the end of the string.
12String replace(char old, char new)Return the replaced string. It replaces all occurrences of the specified character with the new character.
13String replace(CharSequence old, CharSequence new)Return the replaced string. It replaces all occurrences of the specified Character sequence with the specified new Character sequence.
14String replaceAll(String regex, String replacement)Returns the replaced string. It replaces all occurrences of the sequence of characters with the given replacement string that are matching with the given regular expression.
15String replaceFirst(String regex, String replacement)Returns the replaced string. It replaces the first matching sequence of characters with the replacement string that matches with the given regular expression.
16static boolean equalsIgnoreCase(String another)Returns the boolean (true/false) value. It compares the passing string with string by ignoring the case. It  compares the content irrespective of lowercase or uppercase of the character(s).
17String[] split(String regex)Returns the array of strings resulting from splitting of the string     around matches of the given regular expression. String is breaked into strings from all  the matching regular expressions.
18String[] split(String regex, int limit)Returns the array of strings resulting from splitting of the string     around matches of the given regular expression. It breaks the string from all the matching regular expression upto the given limit.
19String intern()Returns an interned string. This method helps to compare two objects using == operator and checks in a string constant pool. it is faster for comparison.
20int indexOf(int ch)Returns the index value of first occurrence of the specified character within the string
21int indexOf(int ch, int fromIndex)Returns the index value of first occurrence of the specified character from the substring starting from specified index
22int indexOf(String substring)Returns the index value of first occurrence of the specified substring within the string.
23int indexOf(String substring, int fromIndex)Returns the index value of the first occurrence of the specified string within the substring starting from specified index to end of the string index.
24int lastIndexOf(int ch)Returns the index value of last occurrence of the specified character
25int lastIndexOf (int ch, int fromIndex)Returns the index value of last occurrence of the specified character, search starts at given fromIndex. 
26int lastIndexOf (String str)Returns the index value of last occurrence of the specified string.
27int lastIndexOf (String str, int fromIndexReturns the index value of last occurrence of the specified string, searches start from given fromIndex
28String toLowerCase()Returns all the characters of the string in lowercase .
29String toLowerCase(Locale l)Returns all the characters of the string in lowercase using specified locale.
30String toUpperCase()Returns all the characters of the string in uppercase.
31String toUpperCase(Locale l)Returns all the characters of the string in uppercase using specified locale.
32String trim()Returns the string after removing the white space from the beginning and end of the string.
33static String valueOf(int value)Return the converted string. It converts the objects and all primitive types of values into string. It is a static method.

In this article, we learned all about length() method of String class with examples. Apart from length() method we got an idea about other String methods too. We will come up with more articles explaining other String methods description with examples. For more details please click on the respective methods link.

This article was written by Renu Singh

14+ Years of experience in various phases of the software development life cycle. Specialties: Java/J2EE, Struts, Hibernate, JSF, JSP, Servlets, AJAX, Oracle, Oracle Knowledge, SQL Server 2000, DB2, EJB3.0. Companies Worked For: 1) Tata Consultancy Services 2) Infogain 3) TS Infotech 4) Daffodil Software Ltd.

Leave a Reply

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