Booleans and selection: if/else and logic · Booleans e seleção: if/else e lógica
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.
Booleanos e seleção
- Um boolean é um valor que é ou
trueoufalse. - Programas fazem escolhas testando um boolean e executando códigos diferentes.
- Nesta lição você aprende
if/else if/elsee como construir condições.
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.
Operadores relacionais
- Estes comparam dois valores e retornam um
boolean:<menor que,>maior que<=menor ou igual,>=maior ou igual==igual,!=diferente
- Nota:
=atribui um valor a uma variável, mas==testa se dois valores são iguais.
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
}
}
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
ifexecuta um bloco apenas quando sua condição étrue.else ifverifica outra condição quando as anteriores foramfalse.elseexecuta quando nenhuma das condições foi verdadeira.
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");
}
}
}
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.
Operadores lógicos
&&significa and (e): verdadeiro apenas quando ambos os lados são verdadeiros.||significa or (ou): verdadeiro quando pelo menos um lado é verdadeiro.!significa not (não): ele invertetrueparafalseefalseparatrue.
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
}
}
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 lê
&&e||da esquerda para a direita e para cedo quando puder. - Com
&&, se o lado esquerdo éfalse, a resposta já éfalse, então o lado direito é pulsado. - Com
||, se o lado esquerdo étrue, a resposta já étrue, então o lado direito é pulsado. - Isso permite verificar se algo está seguro antes de usá-lo.
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
}
}
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(...).
A armadilha == vs .equals() String
- Para
inteboolean,==funciona bem. - Para
String,==verifica se são o mesmo objeto na memória, não as mesmas letras. - Duas Strings com as mesmas letras ainda podem ser objetos diferentes, então
==pode serfalse. - Sempre compare Strings com
.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)
}
}
Common mistakes
- A condition must be a
boolean;if (x = 5)does not compile. - Each
switchcase needs abreak;.
Erros comuns
- Uma condição deve ser um
boolean;if (x = 5)não compila. - Cada caso
switchprecisa de umbreak;.
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.
Agora você tenta
- Cada tarefa pré-preenche a estrutura da classe — escreva seu código dentro do main, ou complete o método mostrado.
- Pressione Run para compilar e executar, depois Check answer.
- Seu código compila e roda no servidor, então até a primeira execução é rápida.
Boolean logic (and/or/not) · Lógica booleana (and/or/not)
&&, ||, ! combine true/false values — see the truth table. · &&, ||, ! combinam valores true/false — veja a tabela-verdade.
The variable n is -4. Use if / else if / else to print exactly one word: positive if · se n > 0, negative if · se n < 0, or zero otherwise. · A variável n é -4. Use if / else if / else para imprimir exatamente uma palavra: positive se n > 0, negative se n < 0, ou zero caso contrário.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete equal(String a, String b) so it returns true when the two Strings have the same letters. Use .equals, not ==. · Complete equal(String a, String b) para que ele retorne true quando as duas Strings tiverem as mesmas letras. Use .equals, não ==.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete inRange(int x) so it returns true when x is between 10 and 20, including both ends (10 and 20 count). Use &&. · Complete inRange(int x) para que ele retorne true quando x estiver entre 10 e 20, incluindo ambas as extremidades (10 e 20 contam). Use &&.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.