조건문
반복문
if(조건) {
// 조건이 참일 때 실행할 코드
}
/* 실행할 코드가 한줄일 때 중괄호 생략가능 */
if(조건)
// 조건이 참일 때 실행할 코드
int number = 10;
if(number > 5) {
System.out.println("숫자는 5보다 큽니다.");
}
if(조건) {
// 조건이 참일 때 실행할 코드
} else {
// 조건이 거짓일 때 실행할 코드
}
int number = 3;
if(number > 5) {
System.out.println("숫자는 5보다 큽니다.");
} else {
System.out.println("숫자는 5보다 작거나 같습니다.");
}
👉 if-else 문을 삼항 연산자로 변환
/* if-else 문으로 구성되어 있고, 그 구문의 조건식과 실행 구문이 비교적 간단한 형태일 때 변환 */
System.out.println((number > 5) ? "숫자는 5보다 큽니다." : "숫자는 5보다 작거나 같습니다.");
if(조건1) {
// 조건1이 참일 때 실행할 코드
} else if(조건2) {
// 조건2가 참일 때 실행할 코드
} else {
// 모든 조건이 거짓일 때 실행할 코드
}
int number = 5;
if(number > 10) {
System.out.println("숫자는 10보다 큽니다.");
} else if(number > 5) {
System.out.println("숫자는 5보다 큽니다.");
} else {
System.out.println("숫자는 5보다 작거나 같습니다.");
}
switch(표현식) {
case 값1:
// 값1과 일치하는 경우 실행할 코드
break;
case 값2:
// 값2와 일치하는 경우 실행할 코드
break;
// ...
default:
// 모든 case와 일치하지 않는 경우 실행할 코드
}
int number = 5;
switch(number) {
case 1:
System.out.println("1입니다.");
break;
case 2:
System.out.println("2입니다.");
break;
default:
System.out.println("1 또는 2가 아닙니다.");
break;
}
👉 개선된 switch 문
자바 12에서는 switch 표현식이 도입되었고, 자바 13에서는 이러한 switch 표현식을
개선하고 확장하는 기능이 추가됨이전 작성 글 참고 : https://velog.io/@carpe07/연산자#switch-연산자
for(초기화식; 조건식; 증감식) {
// 반복해서 실행할 코드
}
/* 1부터 10까지 출력 */
for(int i = 1; i <= 10; i++) {
System.out.println(i);
}
/* 배열의 모든 요소 출력 */
int[] numbers = {1, 2, 3, 4, 5};
for(int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
for (요소타입 변수명 : 반복가능한객체) {
// 요소를 처리하는 코드
}
/* 배열 순회 */
int[] numbers = {1, 2, 3, 4, 5};
for(int num : numbers) {
System.out.println(num);
}
/* 리스트 순회 */
List<String> names = Arrays.asList("Koo", "Kim", "Park");
for(String name : names) {
System.out.println(name);
}
while (조건) {
// 실행할 코드
}
int i = 1; // 시작값
while(i <= 5) { // 조건: i가 5 이하인 동안
System.out.println(i); // 현재의 i값을 출력
i++; // i를 1씩 증가
}
do {
// 실행할 코드
} while (조건);
int i = 1;
int sum = 0;
do {
if(i % 2 != 0) { // 홀수인 경우에만 더함
sum += i;
}
i++;
} while (i <= 100);
System.out.println("1부터 100까지의 홀수 합 : " + sum);