int length()

优质
小牛编辑
119浏览
2023-12-01

描述 (Description)

java.lang.String.length()方法返回此字符串的长度。 长度等于字符串中Unicode代码单元的数量。

声明 (Declaration)

以下是java.lang.String.length()方法的声明

public int length()

参数 (Parameters)

NA

返回值 (Return Value)

此方法返回此对象表示的字符序列的长度。

异常 (Exception)

NA

例子 (Example)

以下示例显示了java.lang.String.length()方法的用法。

package cn.xnip;
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());
   }
}

让我们编译并运行上面的程序,这将产生以下结果 -

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