Java中的length vs length()的差别和对比

array.length:
长度是适用于的最终变量
数组
。借助length变量, 我们可以获得数组的大小。
string.length():
length()方法是一个最终变量, 适用于字符串对象。 length()方法返回字符串中存在的字符数。
长度vs长度()

  1. length变量适用于数组, 但不适用于字符串对象, 而length()方法适用于字符串对象, 但不适用于数组。
  2. 例子:
    // length can be used for int[], double[], String[] // to know the length of the arrays.// length() can be used for String, StringBuilder, etc // String class related Objects to know the length of the String

  3. 要直接访问数组的字段成员, 我们可以使用。长度; 而。长度()调用一种方法来访问字段成员。
例子:
// Java program to illustrate the // concept of length // and length() public class Test { public static void main(String[] args) { // Here array is the array name of int type int [] array = new int [ 4 ]; System.out.println( "The size of the array is " + array.length); // Here str is a string object String str = "lsbin" ; System.out.println( "The size of the String is " + str.length()); } }

输出如下:
The size of the array is 4The size of the String is 13

基于长度与长度()概念的练习题
让我们看看以下程序的输出?
以下程序的输出是什么?
public class Test { public static void main(String[] args) { // Here str is the array name of String type. String[] str = { "GEEKS" , "FOR" , "GEEKS" }; System.out.println(str.length); } }

输出如下:
3

说明:这里的str是一个字符串类型的数组, 这就是为什么使用str.length查找其长度的原因。
以下程序的输出是什么?
public class Test { public static void main(String[] args) { // Here str[0] pointing to a string i.e. GEEKS String[] str = { "GEEKS" , "FOR" , "GEEKS" }; System.out.println(str[ 0 ].length); } }

输出如下:
error: cannot find symbolsymbol: method length()location: variable str of type String[]

说明:这里的str是一个字符串类型的数组, 这就是为什么不能使用str.length()查找其长度的原因。
以下程序的输出是什么?
public class Test { public static void main(String[] args) { // Here str[0] pointing to String i.e. GEEKS String[] str = { "GEEKS" , "FOR" , "GEEKS" }; System.out.println(str[ 0 ].length()); } }

输出如下:
5

说明:这里的str [0]指向字符串, 即GEEKS, 因此可以使用.length()进行访问
【Java中的length vs length()的差别和对比】如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

    推荐阅读