250x250
Recent Posts
Notice
Today
Total
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
관리 메뉴

코딩알파

[Java] 배열출력방법 toString ,향상된 for문 본문

JAVA공부

[Java] 배열출력방법 toString ,향상된 for문

코딩알파 2021. 9. 12. 19:21
728x90

다양한 배열 출력방법

그냥 출력했을때

 

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,20,30};
        System.out.println(arr1);
        }
    
    
    
 
}
cs

 

1
[I@10f87f48
cs

 

우리가 생각했던 거와 다르게 출력되는 걸 볼 수 있습니다.
이것은 직접 인덱스를 통해서 접근을 안 해서 뜨는 겁니다.

 

Arrays.toString()

클래스 위에 import java.util.Arrays; 선언

Arrays.toString() 으로 써준다.

 

Arrays.toString()  사용

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.Arrays;
public class TTest {
 
    public static void main(String[] args) {
 
    
        int[] arr1 =new int[] {10,20,30};
        System.out.println("arr1="+Arrays.toString(arr1));
        }
    
    
    
 
}
 
cs

 

1
arr1=[10, 20, 30]
cs

 

배열을 출력할 때 굳이 for 문을 쓰지 않아도 쉽게 출력이 가능합니다.

 

향상된 for문

기존 for 문으로 인덱스를 접근하는 방법보다 더욱 간단하게 써서 배열을 출력하는 방법입니다.

 

1
2
3
4
5
for( 타입 변수 : 배열 ) {
 
실행문
 
}
cs

 

향상된 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,20,30};
        System.out.print("arr1=");
        for(int e : arr1) {
            System.out.print(e+" ");
        }
        
        }
    
}
 
cs

 

1
arr1=10 20 30 
cs

 

지금까지 배열 출력 방법을 알아보았습니다.

 

728x90
Comments