if (조건문) {
<수행할 문장1>;
<수행할 문장2>;
...
} else {
<수행할 문장A>;
<수행할 문장B>;
...
}
조건문을 테스트해서 참이면 if 문에 속한 문장들(수행할 문장1, 수행할 문장2)을 수행
거짓이면 else 문에 속한 문장들(수행할 문장A, 수행할 문장B)을 수행
비교 연산자 | 설명 |
---|---|
x < y | x가 y보다 작다 |
x > y | x가 y보다 크다 |
x == y | x와 y가 같다 |
x != y | x와 y가 같지 않다 |
x >= y | x가 y보다 크거나 같다 |
x <= y | x가 y보다 작거나 같다 |
연산자 | 설명 |
---|---|
x && y | x와 y 모두 참이어야 참이다(and) |
x | |
!x | x가 거짓이면 참이다(not) |
if (조건문) {
<수행할 문장1>
<수행할 문장2>
...
}else if (조건문) {
<수행할 문장1>
<수행할 문장2>
...
} else {
<수행할 문장1>
<수행할 문장2>
...
}
switch(입력변수) {
case 입력값1: 수행문
break;
case 입력값2: 수행문
break;
...
default: 수행문
break;
}
while (조건문) {
<수행할 문장1>;
<수행할 문장2>;
<수행할 문장3>;
...
}
int a = 0;
while (a < 10) {
a++;
if (a % 2 == 0) {
continue; // 짝수인 경우 출력을 하지 않고 조건문으로 돌아간다.
}
System.out.println(a); // 홀수만 출력된다.
}
for (초기치; 조건문; 증가치) {
...
}
구구단 출력 예시
System.out.print
- 줄바꿈 문자를 포함하지 않고 출력System.out.println
- 마지막에 줄바꿈 문자를 포함하여 출력for (type 변수명: iterate) {
body-of-loop
}
예제
import java.util.ArrayList;
import java.util.Arrays;
public class Sample {
public static void main(String[] args) {
ArrayList<String> numbers = new ArrayList<>(Arrays.asList("one", "two", "three"));
for (String number : numbers) {
System.out.println(number);
}
}
}