logo

Java의 길이 대 길이()

배열.길이: 길이는 다음에 적용할 수 있는 최종 변수입니다. 배열 . 길이 변수의 도움으로 배열의 크기를 얻을 수 있습니다.

문자열.길이() : length() 메소드는 문자열 객체에 적용할 수 있는 최종 메소드입니다. length() 메서드는 문자열에 있는 문자 수를 반환합니다.



길이 대 길이()

1. 길이 변수는 배열에 적용 가능하지만 문자열 객체에는 적용되지 않는 반면, length() 메서드는 문자열 객체에 적용 가능하지만 배열에는 적용 가능하지 않습니다.

2. 예:



// length can be used for int[], double[], String[] // to know the length of the arrays. // length() can be used for String, StringBuilder, etc // String class  related Objects to know the length of the String>

3. 배열의 필드 멤버에 직접 액세스하려면 다음을 사용할 수 있습니다. .길이; 반면 .길이() 필드 멤버에 액세스하는 메서드를 호출합니다.

예:

자바






파이썬 정렬 사전

public> class> Test {> >public> static> void> main(String[] args)> >{> >// Here str[0] pointing to String i.e. GEEKS> >String[] str = {>'GEEKS'>,>'FOR'>,>'GEEKS'> };> >System.out.println(str[>0>].length());> >}> }>

>

>

산출

The size of the array is 4 The size of the String is 13>

길이와 길이()의 개념을 기반으로 한 연습 문제

다음 프로그램의 출력을 살펴보겠습니다.

  • 다음 프로그램의 출력은 무엇입니까?

자바




>

>

산출

3>

설명: 여기서 str은 문자열 유형의 배열이므로 str.length를 사용하여 길이를 찾습니다.

  • 다음 프로그램의 출력은 무엇입니까?

자바




public> class> Test {> >public> static> void> main(String[] args)> >{> >// Here str[0] pointing to a string i.e. GEEKS> >String[] str = {>'GEEKS'>,>'FOR'>,>'GEEKS'> };> >System.out.println(str.length());> >}> }>

>

>

산출:

error: cannot find symbol symbol: method length() location: variable str of type String[]>

설명: 여기서 str은 문자열 유형의 배열이므로 str.length()를 사용하여 길이를 찾을 수 없습니다.

  • 다음 프로그램의 출력은 무엇입니까?

자바




public> class> Test {> >public> static> void> main(String[] args)> >{> >// Here str[0] pointing to String i.e. GEEKS> >String[] str = {>'GEEKS'>,>'FOR'>,>'GEEKS'> };> >System.out.println(str[>0>].length());> >}> }>

>

>

산출

5>

설명: 여기서 str[0]은 문자열, 즉 GEEKS를 가리키므로 .length()를 사용하여 액세스할 수 있습니다.