Java.lang.String.length() Method

Advertisements


Description

The java.lang.String.length() method returns the length of this string. The length is equal to the number of Unicode code units in the string.

Declaration

Following is the declaration for java.lang.String.length() method

public int length()

Parameters

  • NA

Return Value

This method returns the length of the sequence of characters represented by this object.

Exception

  • NA

Example

The following example shows the usage of java.lang.String.length() method.

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

  public static void main(String[] args) {
  
    String str = "tutorials point";
    // prints length of string
    System.out.println("length of string =  " + str.length());
    // checks if the string is empty or not
    System.out.println("is this string empty? = " + str.isEmpty());
    
    // empty string
    str = "";
    // prints length of string
    System.out.println("length of string =  " + str.length());
    // checks if the string is empty or not
    System.out.println("is this string empty? = " + str.isEmpty());
  }
}

Let us compile and run the above program, this will produce the following result:

length of string = 15
is this string empty? = false
length of string = 0
is this string empty? = true



Advertisements
Advertisements