为什么在Java中使用Array.length()时出现错误?

385 阅读2分钟

为什么在Java中使用Array.length()时出现错误?

改进文章

保存文章

喜欢这篇文章

  • 最后更新: 2022年6月7日

如果我们使用Array.length()会发生什么?

在谈到为什么我们不能写**Array.length()的原因之前,让我们先看看如果我们试图在Java代码中使用Array.length()**会发生什么。下面是一个代码片断来检查。

爪哇

import java.io.*;
class GFG {
public static void main(String[] args)
{
int arr[] =new int[3];
int size = arr.length();
}
}

尝试运行上述代码。你会看到,由于使用length(),出现了一个编译时错误。

编译错误。

Main.java:6: error: cannot find symbol
       int size = arr.length();
                     ^
 symbol:   method length()
 location: variable arr of type int[]
1 error

为什么我们不能在Java中使用Array.length()?

我们已经看到,使用**length()**会出现错误。但问题是为什么?

虽然数组在Java中是对象,但length是数组对象中的一个实例变量(数据项),而不是一个方法。所以,我们不能使用**length()**方法来了解数组的长度。

一旦数组的长度变量被初始化,它就不能被修改或改变。它只用于数组,并给出数组的大小(长度),即数组中元素的总数。

而Java中的String对象有**length()**方法,该方法返回当时字符串中存在的字符数。这个方法是访问对象的字段成员的一种方式。它可以随着对字符串的操作进行修改。

length字段在数组中使用,如:int[]、double[]、long[]、String[]等。
length()方法在String对象中使用,如:String、StringBuilder等。String, StringBuilder等。

length实例变量和length()方法的实现。

下面的代码片断展示了length实例变量和**length()**方法的使用情况。

爪哇

// Java program to explain
// length field in array object
public class Main {
public static void main(String args[])
{
// arr is an integer array
int[] arr =new int[3];
// length is a field variable for array arr
System.out.println("Length of the array is: "
+ arr.length);
// str in a String
String str ="GeeksFor";
// length() is method for
// getting length of string
System.out.println("Length of the string " + str
+" is: " + str.length());
// Updating the string
str +="Geeks";
System.out.println("Length of the updated string "
+ str +" is: " + str.length());
}
}

输出

Length of the array is: 3
Length of the string GeeksFor is: 8
Length of the updated string GeeksForGeeks is: 13

我的个人笔记arrow_drop_up

保存