[Java] 배열

Hyo Kyun Lee·2022년 1월 28일
0

Java

목록 보기
6/49

1. 배열선언

int[] array = new int[100];

  • 어떤 형태의 값을 저장할지 자료형 선언과 변수명 선언
  • 배열 역시 반드시 class로 부터 선언하고, new int[100]과 같이 배열 크기를 선언한다.
public class test {
	//프로그램의 시작점
	public static void main(String[] args) {
		int[] array = new int[100];
		array[1] = 5;
	
	}
}

2. 배열선언과 값 초기화를 동시에 진행

int[] array = new int[](1,2,3,4,5);

3. new class 사용없이 중괄호를 통한 배열 선언

int[] array3 = {1, 2, 3, 4};

4. for문을 활용하여 배열 선언

유의 문법 : array.length (*python : len(array))


public class test {
	//프로그램의 시작점
	public static void main(String[] args) {
		int[] array = new int[100];
		
		for(int i=0;i<array.length;i++) {
			array[i] = i;
		}
		for(int i=0;i<array.length;i++) {
			System.out.println(array[i]);
		}
	}
}

5. 2차원 배열

1차원 배열과 선언하는 방식이 똑같다. 단지 2차원 형식으로 선언하는 부분에서 다르다.

public class test {
	//프로그램의 시작점
	public static void main(String[] args) {
		int[][] array = new int[5][5];
	}
}

위와 같이 선언과 초기화를 동시에 진행할 수 있고, 아래와 같이 선언과 초기화를 별도로(각각 다르게) 진행할 수 있다.

public class test {
	//프로그램의 시작점
	public static void main(String[] args) {
		int[][] array = new int[5][5];
		
		int[][] array2 = new int[3][];
		
		array[0] = new int[1];
		array[1] = new int[2];
		array[3] = new int[3];
	}
}

중괄호를 이용하여 선언해줄 수도 있다.

public class test {
	//프로그램의 시작점
	public static void main(String[] args) {
		int[][] array = {{1}, {1,2,3}};
	}
}

※ 유의사항
최초 선언한 배열의 크기는 변하지 않는다.

0개의 댓글