java.lang.String length()

Description :

This java tutorial shows how to use the length() method of java.lang.String class. This method returns an int data type which is the number of Uncicode units of the String . This is generally just counts how many characters are in the String object.

Method Syntax :

public int length()

Method Returns :

This method returns an int datatype which is the character count of the String Object.

Exception :

No Exception is expected as specified on java api.

Java Code Example :

This example source code demonstrates the use of length() method of String class. Basically this example just prints the size of our string.

package com.javatutorialhq.tutorial;

/*
 * This example source code demonstrates the use of  
 * length() method 
 * of String class
 */

public class StringLengthDemo {

    public static void main(String[] args) {
        String strVal = "String example tutorial";
        System.out.println("length of strVal:"+strVal.length());
        System.out.println("Length:"+"strval".length());
        System.out.println("Length:"+new String("sample string").length());

    }

}

Sample Output :

Running the above example of length() method implementation will give you the following output

java string length method example

java string length method example

Exception Scenario :

No Exception specified on Java API

Suggested Reading List :