Java의 if문은 굳이 정리할 필요가 없을 정도로 간단해서, 혹시라도 나중에 내 글을 보고 공부하는 사람이 있다면 적어두도록 하겠다. (아마 없겠지만..)
논리 연산에서 모든 항이 실행되지 않는 경우 - 단락 회로 평가 (short circuit evaluation)
논리 곱(&&)은 두 항의 결과가 모두 true일 때만 결과가 true
논리 합(||)은 두 항의 결과가 모두 false일 때만 결과가 false
package ch12;
public class ShortCircuit {
public static void main(String[] args) {
int num1 = 10;
int i = 2;
boolean value = ((num1 = num1 + 10 ) < 10) && ( ( i = i + 2 ) < 10);
System.out.println(value);
System.out.println(num1);
System.out.println(i);
value = ((num1 = num1 + 10 ) < 10) || ( ( i = i + 2 ) < 10);
System.out.println(value);
System.out.println(num1);
System.out.println(i);
}
}
조건식의 연산결과가 true 이면, 결과는 피연산자 1이고, 조건식의 연산결과가 false 이면 결과는 피연산자2
대입연산자와 다른 연산자가 함께 쓰인다.
마스크 : 특정 비트를 가리고 몇 개의 비트 값만 사용할 때
비트켜기 : 특정 비트들만을 1로 설정해서 사용하고 싶을 때
예) & 00001111 ( 하위 4비트 중 1인 비트만 꺼내기)
비트끄기 : 특정 비트들만을 0으로 설정해서 사용하고 싶을 때
예) | 11110000 ( 하위 4비트 중 0 인 비트만 0으로 만들기)
비트 토글 : 모든 비트들을 0은 1로, 1은 0으로 바꾸고 싶을 때
package ch13;
public class BitTest {
public static void main(String[] args) {
int num1 = 5; // 00000101
int num2 = 10; // 00001010
System.out.println(num1 | num2);
System.out.println(num1 & num2);
System.out.println(num1 ^ num2);
System.out.println(~num1);
System.out.println(num1 << 2);
System.out.println(num1);
System.out.println(num1 <<= 2);
System.out.println(num1);
}
}
switch문은 어떤 변수의 값에 따라서 문장을 실행할 수 있도록 하는 제어문이다. (비교 조건이 특정 값이나 문자열인 경우 사용한다.)
switch문에서 사용하는 키워드는 switch, case, default, break 이다.
자바 14부터 좀 더 간결해진 표현식이 지원된다. ( break 사용하지 않음 )
import java.util.Calendar;
public class SwitchExam {
public static void main(String[] args) {
// 오늘이 몇 월인지 month에 저장합니다.
int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
String season = "";
// 다음과 같이 case문을 한번에 사용하면 더 짧게 코드를 짤 수 있습니다.
switch(month) {
case 1:
case 2:
case 12:
season = "겨울";
break;
case 3:
case 4:
case 5:
season = "봄";
break;
case 6:
case 7:
case 8:
season = "여름";
break;
case 9:
case 10:
case 11:
season = "가을";
break;
}
System.out.println("지금은 " + month + "월이고, " + season + "입니다.");
}
}
이런식으로 쓰는 방법도 알아두자.
간단하게 쉼표(,)로 조건 구분
식으로 표현 하여 반환 값을 받을 수 있음. 리턴 값이 없는 경우는 오류가 생김
yield 키워드 사용
package ch16;
public class SwitchCaseUpTest {
public static void main(String[] args) {
int month = 3;
int day = switch (month) {
case 1, 3, 5, 7, 8, 10,12 -> {
System.out.println("한 달은 31일입니다.");
yield 31;
}
case 4,6,9,11 -> {
System.out.println("한 달은 30일입니다.");
yield 30;
}
case 2 ->{
System.out.println("한 달은 28일입니다.");
yield 28;
}
default->{
System.out.println("존재하지 않는 달 입니다.");
yield 0;
}
};
System.out.println(month + "월은 " + day + "일입니다.");
}
}
반복문은 실행문을 반복적으로 실행해야 할 때 사용 한다.
반복문의 종류는 while문, do-while문, for문 이 있다.
조건문의 실행 결과가 true일 동안 반복해서 실행한다.
while(조건문){
실행문;
}
while문의 경우 조건이 만족하지 않는다면 한번도 반복하지 않을 수 있다. 하지만, do while문의 경우 무조건 한번은 실행되는 반복문이다.
do{
실행문;
}while(조건문);
for(초기화식; 조건식; 증감식){
실행문;
실행문;
}