

배열은 백터로 불리며 동일한 타입이 연속된 공간을 차지 한다.
특징:메모리를 연속해서 사용하는 이유는 첫 번째 값을 찾고 바로 두 번째 값을 찾아내기 위해서다.
장점으로 스캔 하는 속도가 빠르다.
package ex03;
public class ArrayEx01 {
public static void main(String[] args) {
int[] arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
for (int i = 0; i <=2 ; i++) {
System.out.println(arr[i]);
}
}
}
결과

반복문을 사용한 배열
package ex03;
public class ArrayTest1 {
public static void main(String[] args) {
int[]s = new int[10];
for (int i=0; i<s.length; i++){ // 변수명. lngth는 배열의 공간을 나타내는 문법이다.
s[i]=i;
System.out.print(s[i]+" ");
}
}
}
결과

배열의 초기화
package ex03;
public class AraayTest3 {
public static void main(String[] args) {
int[]scores = {10, 20, 30, 40, 50};
for(int i =0; i<scores.length; i++){
System.out.print(scores[i]+" ");
}
}
}
결과

for-each(반복문)
for-each문은 배열에서만 사용하며,
변수 안에다 배열의 값을 집어 넣고 싶을 때 사용한다.
문법으로는 for(변수 : 배열)이다.
package ex03;
public class ArrayTest4 {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
for (int value : numbers){
System.out.print(value + " ");
}
}
}
결과

string은 클래스 자료형으로 문자열을 담는다.
package ex03;
public class PizzaTopping {
public static void main(String[] args) {
String[] toppings = {"Pepperon1", "Mushrooms", "Onions", "Sausage", "Bacon"};
for (String s : toppings){
System.out.print(s + " ");
}
}
}
결과

Share article