length() 方法用于返回字符串的长度。

空字符串的长度返回 0。

语法

public int length()

参数

返回值

返回字符串长度。

实例

以下实例演示了 length() 方法的使用:

public class Test {
public static void main(String[] args) {
String Str1 = new String("www.mybj123.com");
String Str2 = new String("mybj");
System.out.print("字符串 Str1 长度 :");
System.out.println(Str1.length());
System.out.print("字符串 Str2 长度 :");
System.out.println(Str2.length());
}
}

以上程序执行结果为:

字符串 Str1 长度 :15

字符串 Str2 长度 :4