Booleans and selection: if/else and logic · Booleanos y selección: if/else y 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.
Booleans y selección
- Un booleano es un valor que es
true(verdadero) ofalse(falso). - Los programas toman decisiones probando un booleano y ejecutando diferente código.
- En esta lección aprenderás
if/else if/elsey cómo construir condiciones.
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 relacionales
- Estos comparan dos valores y devuelven un
boolean:<menor que,>mayor que<=menor o igual,>=mayor o igual==igual a,!=no igual a
- Nota:
=asigna un valor a una variable, pero==prueba si dos valores son iguales.
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
ifejecuta un bloque solo cuando su condición estrue.else ifverifica otra condición cuando las anteriores fueronfalse.elsese ejecuta cuando ninguna de las condiciones fue verdadera.
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 y: verdadero solo cuando ambos lados son verdaderos.||significa o: verdadero cuando al menos uno de los lados es verdadero.!significa no: inviertetrueafalseyfalseatrue.
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.
Cortocircuito
- Java lee
&&y||de izquierda a derecha y se detiene temprano cuando puede. - Con
&&, si el lado izquierdo esfalse, la respuesta ya esfalse, por lo que el lado derecho se omite. - Con
||, si el lado izquierdo estrue, la respuesta ya estrue, por lo que el lado derecho se omite. - Esto te permite verificar que algo sea seguro antes de usarlo.
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(...).
La trampa de == vs .equals() con Strings
- Para
intyboolean,==funciona bien. - Para
String,==verifica si son el mismo objeto en memoria, no las mismas letras. - Dos Strings con las mismas letras pueden ser objetos diferentes, por lo que
==podría serfalse. - Siempre compara Strings con
.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;.
Errores comunes
- Una condición debe ser un
boolean;if (x = 5)no compila. - Cada caso
switchnecesita unbreak;.
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.
Ahora tú intentas
- Cada tarea prellena la estructura básica de la clase — escribe tu código dentro de main, o completa el método mostrado.
- Presiona Run para compilar y ejecutar, luego Check answer.
- Tu código se compila y ejecuta en el servidor, así que incluso la primera ejecución es rápida.
Boolean logic (and/or/not) · Lógica booleana (and/or/not)
&&, ||, ! combine true/false values — see the truth table. · &&, ||, ! combinan valores verdadero/falso — consulta la tabla de verdad.
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. · La variable n es -4. Usa if / else if / else para imprimir exactamente una palabra: positive si n > 0, negative si n < 0, o zero en caso contrario.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete equal(String a, String b) so it returns true when the two Strings have the same letters. Use .equals, not ==. · Completa equal(String a, String b) para que devuelva true cuando las dos cadenas tengan las mismas letras. Usa .equals, no ==.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete inRange(int x) so it returns true when x is between 10 and 20, including both ends (10 and 20 count). Use &&. · Completa inRange(int x) para que devuelva true cuando x esté entre 10 y 20, incluyendo ambos extremos (10 y 20 cuentan). Usa &&.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.