코딩알파
[Java] 배열 기초부터 알아보기 본문
배열: 같은 타입의 데이터를 연속된 공간에 저장하는 자료구조
배열은 같은 타입의 데이터를 연속된 공간에 나열시키고, 각 데이터에 인덱스를 부여해 놓는다.
길이가 7인 배열
인덱스 0 | 인덱스 1 | 인덱스 2 | 인덱스 3 | 인덱스 4 | 인덱스 5 | 인덱스 6 |
배열은 인덱스 0부터 시작한다.
인덱스는 각 항목의 데이터를 읽거나, 저장하는 데 사용된다.
배열의 값을 찾을 때는 인덱스를 이용한다.
배열 이름[인덱스] // 인덱스 위치의 값을 찾아낸다.
public class ttts {
public static void main(String[] args) {
int[] number= {81,100,105};
System.out.println(number[0]);
}
}
|
cs |
81
|
cs |
배열 선언
타입[ ] 변수; // 이것을 대체로 써주는 것이 좋다.
타입 변수 [ ] ;
둘 다 사용 가능하다.
배열에 값을 넣어서 배열 객체를 만들 수 있다.
데이터 타입[ ] 변수 = { 값 0 , 값 1 , 값 2 , 값 3...... } ;
기본 배열구조 |
|
public class ttts {
public static void main(String[] args) {
int[] number= {81,100,105};
System.out.println("number[0]="+number[0]);
System.out.println("number[1]="+number[1]);
System.out.println("number[2]="+number[2]);
System.out.print("number=");
for(int i=0; i<number.length; i++) {
System.out.print(number[i]+" ");
}
}
}
|
|
number[0]=81
number[1]=100
number[2]=105
number=81 100 105
|
cs |
배열에 저장된 값을 모두 출력하려면 for을 이용해서 배열을 출력할 수 있다.
다른 출력방법도 있지만 우선 넘어가도록 한다.
더 알고 싶으시면 아래 주소 클릭
2021.09.12 - [JAVA공부] - [Java] 배열 출력방법 toString , 향상된 for문
[Java] 배열출력방법 toString ,향상된 for문
다양한 배열 출력방법 그냥 출력했을때 1 2 3 4 5 6 7 8 9 10 11 12 13 public class TTest { public static void main(String[] args) { int[] arr1 =new int[] {10,..
review96.tistory.com
배열 변수를 이미 선언한 후에 다른 실행문에서 중괄호를 사용한 배열 생성은 허용되지 않는다.
|
타입[] 변수
변수 = { 값 0 ,값 1 , 값 2 ....}; //컴파일에러
|
cs |
이것은 new연산자를 사용해서 해결할 수 있다.
|
타입[] 변수;
변수 = new 타입[] { 값 0 ,값 1 , 값 2 ....};
|
cs |
new 연산자 사용 |
|
public class ttts {
public static void main(String[] args) {
int[] scores;
scores=new int[] {80,90,100};
int sum1 = 0;
for(int i=0; i<scores.length; i++) {
sum1+=scores[i];
}
System.out.println("총합:"+sum1);
}
}
|
cs |
|
총합:270
|
cs |
new연산자 배열 생성
값의 목록을 가지고 있지 않지만, 이후에 값을 저장할 배열을 미리 만드는 배열
|
타입[] 변수 = new 타입[길이];
|
cs |
길이가 10인 int [ ] 배열
배열값 넣어주기 |
public class javaStudyTest {
public static void main(String[] args) {
int[] arr1= new int[3];
for(int i=0; i<arr1.length; i++) {
System.out.println("arr1["+i+"]="+arr1[i]);
}
arr1[0]=11;
arr1[1]=22;
arr1[2]=33;
for(int i=0; i<arr1.length; i++) {
System.out.println("arr1["+i+"]="+arr1[i]);
}
}
}
|
cs |
arr1[0]=0
arr1[1]=0
arr1[2]=0
arr1[0]=11
arr1[1]=22
arr1[2]=33
|
cs |
배열길이
배열 길이란 배열에 저장할 수 있는 전체 항목 수를 말한다. 배열의 길이를 읽으려면 length를 쓰면 된다.
배열 변수.length;
length 필드는 읽기 전용 필드이기 때문에 값을 바꿀수 없다.
|
public class javaStudyTest {
public static void main(String[] args) {
int[]num1= {11,22,33,44,55,66};
int leng= num1.length;
System.out.println("num1의 길이는"+ leng);
for(int i=0; i<num1.length; i++){ //배열의 길이를 사용해서 i의 조건을 주는것
System.out.println("num1["+i+"]="+num1[i]);
}
}
}
|
cs |
num1의 길이는6
nun[0]=11
nun[1]=22
nun[2]=33
nun[3]=44
nun[4]=55
nun[5]=66
|
cs |
'JAVA공부' 카테고리의 다른 글
[Java] 배열 복사 알아보기 (0) | 2021.10.03 |
---|---|
[Java] for문 별 피라미드 만들기 (이중for문) (0) | 2021.09.29 |
[Java] String 타입 기초부터 알아보기 (0) | 2021.09.28 |
[Java] while문 do-while문 반복문 알아보기(break, continue) (0) | 2021.09.19 |
[Java] for문 반복문알아보기 (0) | 2021.09.19 |