Java 中的 length 和 length() 有什么区别?\

javaobject oriented programmingprogramming

Java 中的 length 是数组的实例变量,而 length() 是 String 类的方法。

length

  • 数组是一个对象,它包含相同类型的固定数量的值。
  • 数组中的 length 变量返回数组的长度,即数组中存储的元素数量。
  • 数组一旦初始化,其长度就无法更改,因此可以直接使用长度变量来获取数组的长度。
  • length 变量仅用于数组

示例

public class ArrayLengthTest {
   public static void main(String args[]) {
      int array[] = {1, 2, 3, 4, 5, 6, 7};
      System.out.println("数组的长度为:" + array.length);
   }
}

输出

数组的长度为:7

length()

  • length() 方法是 String 类 静态方法
  •  length()  返回 字符串对象的长度,即存储在对象中的字符数。
  • String 类 使用此方法,因为可以使用对象上的各种操作来修改字符串的长度。
  • String 类在内部使用 char[] 数组,它不会向外界公开。

示例

public class StringLengthMethodTest {
   public static void main(String args[]) {
      String str = "Welcome to Tutorials Point";
      System.out.println("Length of String using length() method is: " + str.length());
   }
}

输出

Length of String using length() method is: 26

相关文章