선언과 생성
public class Main {
public static void main(String[] args) {
int[] students; // 배열 변수 선언
students = new int[5]; // 배열 생성
for(int i=0;i<5;i++){
students[i] = 100 - i * 10;
}
for(int i=0;i<5;i++){
System.out.println(students[i]);
}
}
}
배열의 선언과 생성은 다음 코드의 3번째, 4번째 줄와 같이 한다.
(다음 코드의 4번째 줄, 배열을 생성하는 부분에서 students 변수에 배열의 주소값이 입력된다. 참조를 통한 입력)
코드 축약
public class Main {
public static void main(String[] args) {
int[] students = {100, 90, 80, 70, 60};
for(int i=0;i<5;i++){
System.out.println(students[i]);
}
}
}
위 코드는 다음과 같이 축약이 가능하다.
2차원 배열
public class Main {
public static void main(String[] args) {
int arr[][] = new int[2][3];
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[1][0] = 4;
arr[1][1] = 5;
arr[1][2] = 6;
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
System.out.println(arr[i][j]);
}
System.out.println(); // 들여쓰기.
}
}
}
2차원 배열도 1차원 배열과 비슷하게 다음과 같이 만들 수 있다.
향상된 for 문
public class Main {
public static void main(String[] args) {
int[] numbers = new int[5];
for(int i=0;i<5;i++){
numbers[i] = i*10;
}
for (int number : numbers){
System.out.println(number);
}
}
}
배열과 for 문을 사용해야 하는 경우 다음과 같이 간단하게 사용할 수 있다.
다만 다음과 같은 for문은 index값을 찹조할수 없어 i 의 값을 사용하지 않을 때 사용한다.
'인프런 - 백엔드(김영한) > java' 카테고리의 다른 글
접근 제어자 (4) | 2024.10.17 |
---|---|
class / 객체 (0) | 2024.10.11 |
형변환 (0) | 2024.10.06 |
입력 (2) | 2024.10.03 |
조건문 (0) | 2024.10.03 |