Booleans and selection: if/else and logic
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 이 페이지는 최신 브라우저(SharedArrayBuffer 지원)가 필요합니다. Chrome, Edge, Firefox 또는 Safari를 최신 버전으로 업데이트해 주세요.
English
Booleans and selection
- A boolean is a value that is either
trueorfalse. - Programs make choices by testing a boolean and running different code.
- In this lesson you learn
if/else if/elseand how to build conditions.
한국어
부울리안 및 조건 선택
- 부울리안은 either
true또는false인 값입니다. - 프로그램은 부울리안을 테스트하여 다른 코드를 실행함으로써 결정을 내립니다.
- 이번 수업에서는
if/else if/else과 조건을 만드는 방법을 배웁니다.
English
Relational operators
- These compare two values and give a
boolean:<less than,>greater than<=less or equal,>=greater or equal==equal,!=not equal
- Note:
=puts a value into a variable, but==tests if two values are equal.
한국어
관계 연산자
- 이들은 두 값을 비교하여
boolean를 반환합니다:<보다 작음,>보다 큼<=이하,>=이상==와 같음,!=과 다름
- 주의:
=는 값을 변수에 할당하지만,==은 두 값이 같은지 테스트합니다.
public class Main {
public static void main(String[] args) {
int score = 75;
System.out.println(score > 50); // true
System.out.println(score == 100); // false
System.out.println(score != 75); // false
}
}
English
if / else if / else
ifruns a block only when its condition istrue.else ifchecks another condition when the ones before werefalse.elseruns when none of the conditions were true.
한국어
if / else if / else
if는 조건이true일 때만 해당 블록을 실행합니다.else if는 이전 조건들이 모두false이었을 때 다음 조건을 확인합니다.else는 모든 조건이 거짓일 때 실행됩니다.
public class Main {
public static void main(String[] args) {
int n = -4;
if (n > 0) {
System.out.println("positive");
} else if (n < 0) {
System.out.println("negative");
} else {
System.out.println("zero");
}
}
}
English
Logical operators
&&means and: true only when both sides are true.||means or: true when at least one side is true.!means not: it flipstruetofalseandfalsetotrue.
한국어
논리 연산자
&&는 and( Exception ): 양쪽이 모두 참일 때만 참입니다.||는 or: 최소 한 쪽이 참이면 참입니다.!는 not:true을false로,false을true로 바꿉니다.
public class Main {
public static void main(String[] args) {
int age = 16;
boolean teen = age >= 13 && age <= 19;
System.out.println(teen); // true
System.out.println(!teen); // false
System.out.println(age < 13 || age > 19); // false
}
}
English
Short-circuit
- Java reads
&&and||from left to right and stops early when it can. - With
&&, if the left side isfalse, the answer is alreadyfalse, so the right side is skipped. - With
||, if the left side istrue, the answer is alreadytrue, so the right side is skipped. - This lets you check something is safe before you use it.
한국어
단락 평가 (Short-circuit)
- Java는
&&와||을 왼쪽에서 오른쪽으로 읽으며, 결과를 알 수 있으면 일찍 멈춥니다. &&의 경우, 왼쪽 부분이false이면 결과가 이미false이므로 오른쪽 부분은 skip됩니다.||의 경우, 왼쪽 부분이true이면 결과가 이미true이므로 오른쪽 부분은 skip됩니다.- 이는 사용 전에 무언가가 안전한지를 확인하는 데 도움이 됩니다.
public class Main {
public static void main(String[] args) {
int x = 0;
// Left side is false, so x / x is never run (no error).
boolean ok = (x != 0) && (10 / x > 1);
System.out.println(ok); // false
}
}
English
The == vs .equals() String trap
- For
intandboolean,==works fine. - For
String,==checks if they are the same object in memory, not the same letters. - Two Strings with the same letters can still be different objects, so
==may befalse. - Always compare Strings with
.equals(...).
한국어
== vs .equals() String 함정
int와boolean을 비교할 때는==을 사용하면 됩니다.String의 경우,==은 동일한 문자열인지 아니라 메모리상의同一 객체인지 확인합니다.- 같은 문자를 가진 두 String도 다른 객체일 수 있으므로,
==는false이 될 수 있습니다. - 항상 Strings를
.equals(...)로 비교하세요.
public class Main {
public static void main(String[] args) {
String a = "cat";
String b = new String("cat");
System.out.println(a == b); // false (different objects)
System.out.println(a.equals(b)); // true (same letters)
}
}
English
Common mistakes
- A condition must be a
boolean;if (x = 5)does not compile. - Each
switchcase needs abreak;.
한국어
흔한 실수
- 조건에는 반드시
boolean가 필요합니다;if (x = 5)은 컴파일되지 않습니다. - 각
switch케이스에는 반드시break;이 필요합니다.
English
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- Press Run to compile and run, then Check answer.
- Your code compiles and runs on the server, so even the first run is fast.
한국어
이제 직접 해보기
- 각 과제는 클래스 골격을 미리 채워 놓으므로, 코드를 main 내부에 작성하거나 제시된 메서드를 완성하십시오.
- Run 버튼을 눌러 컴파일하고 실행한 후, Answer 확인 버튼을 누르세요.
- 코드는 서버에서 컴파일되고 실행되므로 첫 실행에서도 빠릅니다.
Explore · 탐색하기
Boolean logic (and/or/not)
&&, ||, ! combine true/false values — see the truth table.
The variable n is -4. Use if / else if / else to print exactly one word: positive if n > 0, negative if n < 0, or zero otherwise.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Complete equal(String a, String b) so it returns true when the two Strings have the same letters. Use .equals, not ==.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Complete inRange(int x) so it returns true when x is between 10 and 20, including both ends (10 and 20 count). Use &&.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.