비슷한 유형의 여러 데이터를 나타낼 때는 배열을 활용하면 단 몇 줄의 코딩으로 원하는 값을 얻을 수 있다. 일일이 변수를 선언해서 값을 나타내지 않아도 된다.

 

Ex) int 1 =10;

      int 2 = 20;

      Int 3 = 30;  // 비효율적

 

 배열을 사용하는 방법은 선언, 생성, 할당의 3단계다.

 

Step1 선언, 생성, 할당을 따로 코딩

 

class Array01 {

public static void main(String[] args) {

 

int arrayInt[]; //선언

arrayInt = new int[5]; //생성

 

for(int i=0; i<arrayInt.length; i++){

arrayInt[i] = (i+1)*10; //할당

System.out.print(arrayInt[i] + " ");

}

}

}

 

Step2 선언+생성을 하고 할당

 

class Array02 {

public static void main(String[] args) {

 

int arrayInt[] = new int[5]; //선언과 동시에 생성

 

for(int i=0; i<arrayInt.length; i++){

arrayInt[i] = (i+1)*10; //할당

System.out.print(arrayInt[i] + " ");

}

}

}



Step3 선언+생성+할당을 동시에

 

class Array03 {

public static void main(String[] args) {

 

int arrayInt[] = {10,20,30,40,50}; // 선언+생성+할당을 동시에

for(int i=0; i<arrayInt.length; i++){

System.out.print(arrayInt[i] + " ");

}

}

}

 

결과는 모두 동일하게 10, 20, 30, 40, 50이 나온다.

 


+ Recent posts