在C/C++语言中,每当调用一个方法需要传递数组时,就必须同时传递数组的长度,因为在方法调用时传递的参数为数组的首地址,而对数组的实际长度却无法获取,这样会导致在对数组进行访问时可能产生越界。
在Java语言中,数组提供了length属性来获取数组的长度。
在Java语言中,length()方法是针对字符串而言的,String提供了length()方法来计算字符串的长度。
package com.haobi;
public class Test {
public static void testArray(int[] arr) {
System.out.println("数组长度为:"+arr.length);
}
public static void testString(String s) {
System.out.println("字符串长度为:"+s.length());
}
public static void main(String[] args) {
int[] arr = {1,2,3,4};
String s = "haobi";
testArray(arr);
testString(s);
}
}
//程序输出结果如下:
数组长度为:4
字符串长度为:5