java中length和length()的区别

 

length()方法是求String字符串对象中字符的个数,而length是求字数组中有多少个元素

public class Test {
    public static void main(String[] args) {
        String str ="abcdefg";
        int a[] ={1,3,5};
        System.out.println(str.length());//String中length()方法
        System.out.println(a.length);//数组的属性
        //结果输出 7  3
    }
}

String中length()方法源码,底层也是将String转换成char数组,调用length属性

    /** The value is used for character storage. */
    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;
    }

 


版权声明:本文为u010919402原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。