for的length后面为什么有括号 求字符串长度不是length吗

img


for的length后面为什么有括号 求字符串长度不是length吗

String类型内部是使用一个char数组存储的(jdk8),看String类型的源码的length方法可以看到

    public class String{
      private final char value[];
      /**
     * Returns the length of this string.
     * The length is equal to the number of <a href="Character.html#unicode">Unicode
     * code units</a> in the string.
     *
     * @return  the length of the sequence of characters represented by this
     *          object.
     */
    public int length() {
        return value.length;
    }
    }

String length()方法实际上返回的就是内部char数组的length,而该数组在String类中用private修饰,外部无法直接使用,所以String提供了对应的length()方法,用来获取字符串的长度