JAvaにおけるlengthとlength()の違い

922 ワード


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 Unicode
* code units in the string.
     *
     * @return  the length of the sequence of characters represented by this
     *          object.
     */
    public int length() {
        return value.length;
    }