프로그래밍 언어/JAVA

[JAVA] 배열 타입(1)

김곰댕 2021. 6. 15. 16:03
728x90

배열이란

같은 타입의 데이터를 연속된 공간에 저장하는 자료구조

각 데이터 저장 위치는 인덱스를 부여해서 접근할 수 있다.

 

배열의 필요성

1. 중복된 변수 선언을 줄이기 위해 사용

2. 반복문을 이용해서 요소들을 쉽게 처리하기 위해

 

배열 선언

배열을 사용하기 위해서는 우선 배열 변수를 선언해야 한다.

타입[ ] 변수;                             타입 변수[ ];

배열 변수는 참조 변수이므로 배열이 생성되기 전에 null로 초기화가 가능하다.

타입[ ] 변수 =null;

배열 변수가 null값을 가진 상태에서는 항목에 접근하기 위해 "변수[인덱스]" 못함 (NullPointException 발생)

 

값 목록으로 배열 생성

변수 선언과 동시에 값 목록을 대입

데이터타입[] 변수 = {값0, 값1, 값2, 값3, ...};           String[] names = {"신용권", "홍길동", "감자바"};

변수 선언후에 값 목록을 대입

데이터타입[] 변수;                                           String[] names = null;
변수 = new 타입[] {값0, 값1, 값2, 값3, ...};              names = new String[] {"신용권", "홍길동", "감자바"};

배열을 매개변수로 가지는 메소드를 호출할 때, 배열을 직접 생성해서 매개값으로 주는 경우

int add(int[] scores){...}
------------------------------------------------------------------------------------------------------------------------
int result = add({95,85,90)};   //컴파일 에러
int result = add(new int[] {95, 85, 90} );

 

예제)

package sec06.exam01_array_bylist;

public class ArrayCreateByValueListExample 
{
	public static void main(String[] args) 
	{
		int[] scores = { 83, 90, 87 }; //배열 변수 scores는 스택에 생성, 값목록은 힙 영역에 생성 - 힙영역에 생성된 배열 객체의 주소를 scores가 가지고있다.
		
		System.out.println("scores[0]:" + scores[0]);
		System.out.println("scores[1]:" + scores[1]);
		System.out.println("scores[2]:" + scores[2]);

		int sum = 0;
		for(int i = 0; i<3; i++)
		{
			sum += scores[i]; 
		}
		
		System.out.println("총합: " + sum);
		
		double avg = (double) sum/3;
		System.out.println("평균 : " + avg);
	}
}

출력 결과

package sec06.exam01_array_bylist;

public class ArrayCreateByValueListExample2 
{
	public static void main(String[] args) 
	{
		int[] scores;
		scores = new int[] {83, 90, 87};
		int sum1 = 0;
		for(int i =0; i<3; i++)
		{
			sum1 += scores[i];
		}
		
		System.out.println("총합은: " + sum1);
		
		int sum2 = add(new int[] { 83,90,87 });
		
		System.out.println("총합은: " + sum2);
	}
	public static int add(int[] scores)
	{
		int sum = 0;
		for(int i =0; i<3; i++)
		{
			sum += scores[i];
		}
		return sum;
	}
}
//배열 변수를 미리 선언하고 그 다음에 변수에 배열 객체를 대입할 경우 new 연산자를 사용해야 하며 배열 타입을 한번 더 넣어주어야함.
//어떤 메소드가 배열 변수를 가지고 있으면 이 메소드를 호출할 때 배열 객체를 입력할때는 new 연산자를 사용해야 함.

출력 결과

 

new 연산자로 배열 생성

배열 생성시 값 목록을 가지고 있지 않고 향후 값들을 저장할 배열을 미리 생성하고 싶은 경우

타입[] 변수 = new 타입[길이];    //길이 : 배열이 저장할 수 있는 값의 개수'

타입[] 변수 = null;
변수 = new 타입[길이];

항목의 기본 값

new로 배열을 생성하는 경우 항목에 기본값이 있음.

 

예제)

package sec06.exam01_array_bylist;

public class ArrayCreateByNewExample 
{

	public static void main(String[] args) 
	{
		int[] arr1 = new int[3];
		for(int i =0; i<3; i++) //int 타입 초기값 확인
		{
			System.out.println("arr1[" + i + "]" + arr1[i]);
		}
		System.out.println();
		
		arr1[0] = 10;
		arr1[1] = 20;
		arr1[2] = 30;
		for(int i =0; i<3; i++)
		{
			System.out.println("arr1[" + i + "]" + arr1[i]);
		}
		System.out.println();
		
		double[] arr2 = new double[3];
		for(int i=0; i<3; i++) //double 타입 초기값 확인
		{
			System.out.println("arr2[" + i + "]" + arr2[i]);
		}
		
		arr2[0] = 0.1;
		arr2[1] = 0.2;
		arr2[2] = 0.3;
		System.out.println();
		
		for(int i =0; i<3; i++)
		{
			System.out.println("arr1[" + i + "]" + arr2[i]);
		}
		
		String[] arr3 = new String[3];
		System.out.println();
		
		for(int i =0; i<3; i++) //String 타입 초기값 확인
		{
			System.out.println("arr1[" + i + "]" + arr3[i]);
		}
		System.out.println();
		
		arr3[0] = "1월";
		arr3[1] = "2월";
		arr3[2] = "3월";
		
		for(int i =0; i<3; i++)
		{
			System.out.println("arr1[" + i + "]" + arr3[i]);
		}
	}
}

출력 결과

728x90