java

[Java] int[] arr vs int arr[]

Across 2023. 4. 17. 17:13

 

int[] arr1 = new int[10];
int arr2[] = new int[10];

 

두가지 코드는 다르게 동작할까?

int[] arr1 = new int[10];
int arr2[] = new int[10];
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));

실행해보면

더보기
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

 

그냥 같은 배열임을 알 수 있다.

 

 

 

 

그럼 같은 문법을 다르게 표기 해놓은 이유가 무엇일까?

C나 C++에서의 배열선언방법과 유사하다고 한다.

ex)

int arr[5];
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

C/C++사용자들을 배려하기 위해 만들어 놓은 문법인데

 

 

 

 

여담으로 아래의 main 문법도 잘 동작한다

public static void main(String[] args)
public static void main(String args[])
public static void main(String ... args)

 

 

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

 

Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics)

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated

docs.oracle.com

 

 

공식문서에 의하면 크게 권하진 않는다

You can also place the brackets after the array's name:
// this form is discouraged
float anArrayOfFloats[];

However, convention discourages this form; the brackets identify the 
array type and should appear with the type designation.

int[] arr 든 int arr[]든 모두 컴파일러에게 알릴뿐 실제 배열을 생성하지는 않는다.

As with variables of other types, the declaration does not actually create an array; 
it simply tells the compiler that this variable will hold an array of the specified type.

 

변수에 배열을 선언하는 방식에서 문제가 될만한 케이스가 있는데

int[] a, b; // int a[]; int b[];
int c[], d;  // int c[]; int d;

이런경우 괜한 오해를 만들 수 있으니 기본자료형과 같이 선언하면 될 것 같다.

 

byte[] rowvector, colvector, matrix[];
byte rowvector[], colvector[], matrix[][];

여담으로 2차원배열도 선언가능하다.

 

결론은 가독성면에서 int[] arr가  유형과 변수 모두를 살펴봐야하는 번거로움을 줄일 수 있다.

 

 

 

여담으로 멘토님이 돌려주신 챗gpt의 답변 

int[] arr1 = new int[10];
int arr2[] = new int[10]; 

 

첫 번째 문장인 int[] arr1 = new int[10];은 "arr1은 int형 배열을 참조하는 변수로, 크기가 10인 배열을 생성하고 
arr1이 참조하도록 합니다."라는 의미입니다. 이 문장은 자바에서 배열 변수를 선언하는 권장 방식입니다.

두 번째 문장인 int arr2[] = new int[10];은 C나 C++에서 배열 변수를 선언하는 방식과 유사합니다. 이 문장은 "arr2가 int형 배열을 참조하는 변수이며, 크기가 10인 배열을 생성하고 arr2가 참조하도록 합니다."라는 의미입니다. 
하지만 이 방식은 자바에서는 권장되지 않으며, 가독성이 떨어질 수 있습니다.

따라서 배열 변수를 선언할 때는 첫 번째 방식을 사용하는 것이 좋습니다.

내부적으로는 두 가지 방식 모두 동일한 방식으로 배열을 생성하고 변수에 할당합니다.  따라서 런타임에는 차이가 없습니다.

다만 첫 번째 방식 int[] arr1 = new int[10];은 자바에서 배열 변수를 선언하는 권장 방식이므로 가독성이 더 좋습니다. 따라서 두 번째 방식 int arr2[] = new int[10];은 자바에서는 권장되지 않습니다.

또한 자바에서는 배열 변수를 선언할 때 첫 번째 방식을 사용하면, 변수 이름 뒤에 있는 대괄호([])를 사용하여 배열임을 명확하게  나타낼 수 있습니다. 예를 들어 int[] arr1은 arr1이 int형 배열임을  명확하게 나타내며, int arr1과 같이 대괄호를 생략하는 것은 컴파일러가 해석하기에 애매모호한 코드가 될 수 있습니다.

 

 

참고 링크

https://stackoverflow.com/questions/129178/difference-between-int-array-and-int-array

 

Difference between int[] array and int array[]

I have recently been thinking about the difference between the two ways of defining an array: int[] array int array[] Is there a difference?

stackoverflow.com