Java : Enhanced for-loop(향상된 for)

m_ngyeong·2025년 3월 12일
0

Java

목록 보기
15/17
post-thumbnail

☕️ Java

향상된 For()

For each란 배열 내의 모든 값을 순회하는 for()문의 향상된 형태를 말한다.

  • 배열의 모든 요소를 스캔하는 과정에서 인덱스의 값이 필요하지 않음
  • 주로, 배열의 리스트를 순회할 때 요소 값을 변경하지 않고 읽기만 할 때 사용

형식:

for([배열 자료형][변수명]:[배열명|컬렉션 객체명]){
    // 각 변수(배열 내의 각각의 값)에 적용할 코드
}

예시:

public class Main {
    public static void main(String[] args) {
    
        int[] arrayTest = new int[10]; 
        
        // 기존 for문
        for (int i=0; i<10; i++) {
            arrayTest[i] = (i + 1) * 10;
            System.out.print(arrayTest[i] + " ");
        }
        System.out.println();
        
         // 확장 for문
        for(int num:arrayTest) {
            System.out.print(num + " ");
        }   
    }
}

//결과: 10 20 30 40 50 60 70 80 90 100 

참고,
https://pathas.tistory.com/126
https://backendcode.tistory.com/221

profile
ʚȉɞ

0개의 댓글

관련 채용 정보