02 - Operadores y Expresiones
Una introducción a operadores y expresiones en programación Java.
Los operadores son símbolos que realizan operaciones sobre variables y valores. Gracias a los operadores, el código puede realizar cálculos y modificaciones respecto al valor original.
Operadores aritméticos
Usado para operaciones matemáticas:
int a = 10;
int b = 5;
int suma = a + b; // Suma con resultado: 15
int resta = a - b; // Resta con resultado: 5
int producto = a * b; // Multiplicación con resultado: 50
int cociente = a / b; // División con resultado: 2
int resto = a % b; // Módulo, el resto de la división: 0When dividing integers, Java performs integer division, which means it discards any decimal part. For example, 7 / 2 would result in 3, not 3.5.
int x = 7 / 2; // 3 (not 3.5!) - Integer division
double y = 7.0 / 2; // 3.5 - At least one double gives double result
double z = (double) 7 / 2; // 3.5 - Casting works tooModulus (%) - The remainder Operator
The modulus operator returns the remainder of a division operation:
int remainder = 10 % 3; // 1 (because 10 divided by 3 is 3 with a remainder of 1)Compound Assignment Operators
These operators combine an arithmetic operation with assignment:
int a = 10;
a = a + 5; // The old way
a += 5; // a = a + 5
a -= 3; // a = a - 3
a *= 2; // a = a * 2
a /= 4; // a = a / 4
a %= 3; // a = a % 3Increment and Decrement Operators
Used to increase or decrease a variable's value by 1:
int a = 5;
a++; // Increment: a becomes 6
a--; // Decrement: a becomes 5 againint a = 5;
int b = a++; // b is 5, a is now 6
int c = ++a; // a is 7, c is now 7Comparison Operators
Used to compare two values, returning a boolean result (true or false):
int a = 10;
int b = 5;
a == b // false - Equal to
a != b // true - Not equal to
a > b // true - Greater than
a < b // false - Less than
a >= b // true - Greater than or equal to
a <= b // false - Less than or equal toLogical Operators
Used to combine multiple boolean expressions:
boolean x = true;
boolean y = false;
x && y // false - Logical AND
x || y // true - Logical OR
!x // false - Logical NOTCombining Logical Operators
boolean result = (a > b) && (b < 10); // true if both conditions are trueString Concatenation
The + operator can also be used to concatenate (join) strings:
String greeting = "Hello, " + "world!"; // "Hello, world!"
String name = "Alice";
String greetingWithName = "Hello, " + name + "!"; // "Hello, Alice!"Operator Precedence
Operator Precendence means which operator gets evaluated first in an line of code. Think of it like BODMAS/PEMDAS in math!
int result = 10 + 5 * 2; // result is 20, not 30