Operators in the Java Language 21.

Advertisement

1. Introduction

Java is one of the most widely used programming languages in the world thanks to its robustness, portability, and syntax designed for gradual learning without sacrificing high-performance capabilities. Operators are the basic elements that allow for data and expression manipulation, and are the foundation upon which complex programs are built. This document aims to detail each category of operators in Java, providing examples and explanations of their features and nuances.

2. Complete table of operators in Java

Below is a table with all the operators in Java, along with their meaning and a simple example of use:

Operator TypeOperatorMeaningExample of Use
Arithmetic+-*/%Addition, subtraction, multiplication, division, modulusint resultado = 5 + 3;
Unary+-++--~Change sign, increment/decrement, bitwise complementint x = -5; x++;
Relational==!=><>=<=Comparison between two valuesboolean esMayor = (5 > 3);
Assignment=+=-=*=/=%=Assigns values to a variablex += 5; // Equivalente a x = x + 5;
Conditional?:Ternary operatorString mensaje = (x > 10) ? "Mayor" : "Menor";
InstanceofinstanceofChecks if an object is an instance of a classboolean resultado = obj instanceof String;
Access.[]()Access class members, arrays, methodsmiObjeto.miMetodo();
Cast (Conversion)(tipo)Converts a value to another typedouble valor = (double) 10;

Each of these operators plays a crucial role in writing Java code, allowing you to manipulate data, perform mathematical operations, evaluate conditions, and manage program logic.

3. Operators and Expressions in Java

In Java, a expression It is a set of operators and operands that, when evaluated, produce a value. Operators define the operations to be performed on one or more operands; they can range from simple addition to complex logical and comparison operations. A correct understanding of the relationship between expressions and operators is essential for writing clear and efficient code.

int a = 5;
int b = 10;
int resultado = a + b * 2; // Se evalúa primero b * 2 por la precedencia de la multiplicación.

4. Arithmetic Operators

Arithmetic operators are essential for any mathematical operation. They are divided into unary and binary operators.

4.1. Unary Arithmetic Operators

They work with a single operand and allow, for example, changing the sign of the variable or increasing and decreasing its value.

  • Positive operator (+) y negative (-): Indicate the sign of the operand.
  • Increase (++) and Decrement (--): Increase or decrease the value by one.

int x = 5;
x++;        // Post-incremento: usa el valor antes de incrementar.
++x;        // Pre-incremento: incrementa antes de usar el valor.
x--;        // Post-decremento: usa el valor antes de incrementar.
--x;        // Pre-decremento: incrementa antes de usar el valor.
int y = -x; // Inversión del signo.

4.2. Binary Arithmetic Operators

They include basic operations of addition, subtraction, multiplication, division and the modulus (remainder).

  • Addition (+): You can concatenate or add numeric numbers.
  • Subtraction (-).
  • Multiplication (*).
  • Division (/): Attention to integer division versus floating point division.
  • Module (%): Returns the remainder of the division.

int a = 10, b = 3;
System.out.println(a + b);  // 13
System.out.println(a - b);  // 7
System.out.println(a * b);  // 30
System.out.println(a / b);  // 3 (división entera)
System.out.println(a % b);  // 1 (residuo)

5. Relationship Operators

These operators allow you to compare two values or expressions, returning a Boolean value.

  • Equality (==) y Inequality (!=).
  • Greater than (>), less than (<), greater than or equal to (>=) y less than or equal to (<=).

int x = 8, y = 10;
System.out.println(x == y);  // false
System.out.println(x != y);  // true
System.out.println(x < y);   // true
System.out.println(x >= 8);  // true

6. Logical Operators

Used to combine or invert Boolean expressions, they are crucial in control flow and decision making.

  • Logical AND (&&): Returns true only if both operands are true.
  • Logical OR (||): Returns true if one of the operands is true.
  • Logical NOT (!): Inverts the Boolean value of an expression. That is, if the original expression is true, the operator ! makes it false; and if it is false, it makes it true.

boolean a = true, b = false;
System.out.println(a && b);  // false
System.out.println(a || b);  // true
System.out.println(!a);      // false

7. Assignment and Compound Operators

The simple assignment operator (=) assigns a value to a variable. Compound operators allow you to perform an operation and assignment in a single statement, making your code more concise.

  • Assignment (=)
  • Compound assignment with sum (+=), subtract (-=), multiplication (*=), division (/=), module (%=), among others.

int x = 10;
x += 5;  // Equivalente a: x = x + 5; ahora x es 15.
x *= 2;  // Equivalente a: x = x * 2; ahora x es 30.

8. Bitwise Operators

These operators allow direct manipulation of bits in integers, making them essential in low-level applications, optimization, and systems.

  • Bitwise AND (&)
  • Bitwise OR (|)
  • Bitwise XOR (^)
  • Bitwise complement (~)
  • Shift left (<<)
  • Shift right (>>)
  • Unsigned right shift (>>>)

int a = 5;      // En binario: 0101
int b = 3;      // En binario: 0011

System.out.println(a & b);  // Resultado: 1 (0001)
System.out.println(a | b);  // Resultado: 7 (0111)
System.out.println(a ^ b);  // Resultado: 6 (0110)
System.out.println(~a);     // Resultado: -6 (complemento a dos)
System.out.println(a << 1); // Resultado: 10 (1010)
System.out.println(a >> 1); // Resultado: 2  (0010)

9. Instanceof operator

The operator instanceof It is used to verify whether an object is an instance of a specific class or interface, helping in handling inheritance and runtime type checking.

class Animal {}
class Perro extends Animal {}

Animal miAnimal = new Perro();
if (miAnimal instanceof Perro) {
    System.out.println("miAnimal es una instancia de Perro");
}

10. Ternary Operator

The ternary operator is a shortcut for simple conditions and is written as follows:

condición ? expresión_si_verdadero : expresión_si_falso;

Example:

int numero = 8;
String resultado = (numero % 2 == 0) ? "Número par" : "Número impar";
System.out.println(resultado); // Imprime: Número par

11. Priority and Associativity in the Execution of Operators

Expression evaluation in Java depends on two key concepts:

  • Precedence (Priority): Determines which operators are evaluated first in the absence of parentheses. For example, multiplication (*) is evaluated before the sum (+).
  • Associativity: Defines the evaluation order between operators of the same precedence level. Most binary operators are evaluated from left to right, except for some unary and assignment operators.

It is advisable to use parentheses to clarify the order of evaluation and improve code readability.

11.1. Advanced Examples and Precedence Table

Common Operator Precedence Table in Java

LevelOperatorsDescription
1 (Major)()Parentheses to group and force order
2expr++expr-- (postfix)Increment and decrement in postfix form
3++expr--expr+expr-expr!~Unary operators (prefix)
4*/%Multiplication, division and modulus
5+-Addition and subtraction
6<<>>>>>Shift operators
7<<=>>=instanceofRelational operators
8==!=Equality operators
9&Bitwise AND
10^Bitwise XOR
12"&&" "||" "!"Logical AND (&&) Logical OR (||) Logical NOT (!)
14?:Ternary (conditional) operator
15 (Minor)=+=-=*=/=%= and othersAssignment and compound operators

Advanced Example 1: Arithmetic-Relational Expression

int a = 5, b = 10, c = 3, d = 2;
int resultado = a + b * c - d / a;

Assessment:

  1. Multiplications and divisions are performed first:
    • b * c10 * 3 = 30
    • d / a2 / 5 = 0 (integer division)
  2. Addition and subtraction are applied (from left to right):
    • a + 305 + 30 = 35
    • 35 - 035

Result: 35.

Advanced Example 2: Using the Ternary Operator in Nested Expressions

int x = 15, y = 20, z = 5;
int resultado = (x > y) ? x : (y > z ? y : z);

Assessment:

  1. It is evaluated x > y:
    • As 15 > 20 is false, move on to the next expression.
  2. It is evaluated (y > z ? y : z):
    • 20 > 5 is true, so it is selected y.

Result: 20.

Advanced Example 3: Combining Logical and Arithmetic Operators

boolean flag = false;
int valor = 4;
int resultado = flag ? (valor + 10) * 2 : (valor * 3) - 1;

Assessment:

  • Given that flag is false, is evaluated (valor * 3) - 1:
    • valor * 3 → 4 * 3 = 12
    • 12 - 1 = 11

Result: 11.

Advanced Example 4: Mixed Assessment Challenge

int a = 2, b = 3, c = 4, d = 5;
int resultado = a + b << c - d; // Sin paréntesis, puede ser confuso.

Evaluation without parentheses:

  1. It is evaluated a + b2 + 3 = 5.
  2. It is evaluated c - d4 - 5 = -1.
  3. The displacement is carried out: 5 << (-1) Note: Shifting with a negative number may result in unexpected behavior or an error.

Improvement by parentheses:

int resultadoCorrecto = (a + b) << (c - d);

With this explicit use of parentheses, the order of evaluation is clear, avoiding ambiguities.

These examples and the precedence table highlight the importance of understanding both operator precedence and associativity in Java to avoid errors and improve code readability and robustness.

12. The Internal Documentation of a Program

Good documentation is vital for maintenance and collaboration in software development. In Java, the following are used:

  • Line and block comments: They explain fragments or sections of the code.
  • Javadoc: Tool for documenting classes, methods, and fields in a structured manner, generating HTML documentation.

Javadoc comment example:

/**
 * Calcula el factorial de un número.
 *
 * @param n Número entero para el cual se calcula el factorial.
 * @return El factorial de n.
 */
public long factorial(int n) {
    if(n <= 1) return 1;
    return n * factorial(n - 1);
}

13. Enveloping Classes of Primitive Numeric Variables

The wrapper classes allow primitive types to be treated as objects. For example, int is associated with Integer y double with Double. These classes in the package java.lang facilitate conversions, comparisons and use in generic collections.

int num = 10;
Integer numObjeto = Integer.valueOf(num);  // Boxing
int numPrimitivo = numObjeto.intValue();     // Unboxing

// Con autoboxing (a partir de Java 5):
Integer autoboxed = num;     
int unboxed = autoboxed;

14. BigInteger and BigDecimal classes

For calculations that require precision greater than that of primitive types, Java offers:

  • BigInteger: For integers of arbitrary size.
  • BigDecimal: For high-precision decimal numbers, very useful in financial applications.

import java.math.BigInteger;
import java.math.BigDecimal;

BigInteger bigInt1 = new BigInteger("12345678901234567890");
BigInteger bigInt2 = new BigInteger("98765432109876543210");
BigInteger sumaBigInt = bigInt1.add(bigInt2);
System.out.println("Suma de BigInteger: " + sumaBigInt);

BigDecimal bigDec1 = new BigDecimal("12345.6789");
BigDecimal bigDec2 = new BigDecimal("0.0001");
BigDecimal sumaBigDec = bigDec1.add(bigDec2);
System.out.println("Suma de BigDecimal: " + sumaBigDec);

15. More examples of all operators in Java

1. Arithmetic Operators in Complex Expressions

Arithmetic operators can be combined in advanced expressions, taking into account precedence and associativity.

public class ExpresionCompleja {
    public static void main(String[] args) {
        int a = 5, b = 10, c = 3, d = 2;
        int resultado = (a + b * c) / (d + 1) - a % d;
        
        System.out.println("Resultado: " + resultado);
    }
}

Explanation:

  1. It is done b * c → 10 * 3 = 30.
  2. It adds up a + 30 → 35.
  3. It is divided 35 / (d + 1) → 35 / 3 = 11 (división entera).
  4. The module is obtained a % d → 5 % 2 = 1.
  5. It is subtracted 11 - 1 = 10.

2. Relation Operators in Data Filtering

Using comparison operators in lists and filters.

import java.util.List;
import java.util.stream.Collectors;
import java.util.Arrays;

public class FiltradoDatos {
    public static void main(String[] args) {
        List<Integer> numeros = Arrays.asList(10, 20, 30, 5, 50, 7);
        
        List<Integer> filtrados = numeros.stream()
                                         .filter(n -> n > 10 && n < 40)
                                         .collect(Collectors.toList());

        System.out.println("Números filtrados: " + filtrados);
    }
}

Explanation: Filter values within the range 10 < n < 40, using relational operators combined with &&.

3. Logical Operators in Complex Conditional Expressions

Logical operators can optimize conditions in control flows.

public class CondicionCompleja {
    public static void main(String[] args) {
        int edad = 25;
        boolean esMiembro = true;
        
        if ((edad >= 18 && edad <= 65) || esMiembro) {
            System.out.println("Acceso permitido.");
        } else {
            System.out.println("Acceso denegado.");
        }
    }
}

Explanation: Access is allowed if the age is within the range 18-65 or yes esMiembro is true.

4. Bitwise Operators for Permission Manipulation

Using bitwise operators in permission systems.

public class PermisosBit {
    public static void main(String[] args) {
        final int LECTURA = 1;     // 0001
        final int ESCRITURA = 2;   // 0010
        final int EJECUCION = 4;   // 0100
        
        int permisos = LECTURA | EJECUCION; // Combinación bit a bit

        System.out.println("Tiene permiso de lectura: " + ((permisos & LECTURA) != 0));
        System.out.println("Tiene permiso de escritura: " + ((permisos & ESCRITURA) != 0));
        System.out.println("Tiene permiso de ejecución: " + ((permisos & EJECUCION) != 0));
    }
}

Explanation: Permissions are combined with |. Then, it is checked if a permission is activated with &.

5. Instanceof Operator in Inheritance and Polymorphism

Advanced operator usage instanceof to check object types.

class Animal {}
class Perro extends Animal {}

public class PruebaInstanceof {
    public static void main(String[] args) {
        Animal miMascota = new Perro();
        
        if (miMascota instanceof Perro) {
            System.out.println("La mascota es un perro.");
        }
    }
}

Explanation: instanceof checks if an object belongs to a specific class.

6. Ternary Operator in Complex Expression

Use of ?: to reduce code.

public class OperadorTernario {
    public static void main(String[] args) {
        int temperatura = 28;
        
        String estado = (temperatura > 30) ? "Calor extremo" 
                     : (temperatura > 20) ? "Templado"
                     : "Frío";

        System.out.println("Estado del clima: " + estado);
    }
}

Explanation: Use nested expressions in the ternary operator to determine the temperature.

16. Java Lab: Practical Cases and Sample Code

This section presents practical examples using various operators to solve typical problems. It's recommended to run the code in a development environment to fully understand how it works.

Example 1: Average Calculation and Condition Check

public class LaboratorioOperadores {
    public static void main(String[] args) {
        int a = 15, b = 25, c = 35;
        // Uso de operadores aritméticos para calcular el promedio
        int promedio = (a + b + c) / 3;
        System.out.println("Promedio: " + promedio);
        
        // Uso de operadores de relación y lógicos
        String mensaje = (promedio > 20 && promedio < 30) ? 
                         "Promedio en rango aceptable" : "Promedio fuera de rango";
        System.out.println(mensaje);
    }
}

Example 2: Bitwise Operators in Low-Level Actions

public class ManipulacionBits {
    public static void main(String[] args) {
        int valor = 12; // En binario: 1100
        // Desplazamiento a la izquierda para multiplicar por 2
        int resultado = valor << 1;
        System.out.println("Resultado del desplazamiento: " + resultado);  // Salida: 24
    }
}

16. Conclusion, Summary and References

This document has analyzed in detail the operation of operators in Java, ranging from arithmetic and relational to logical, bitwise, and ternary operators. The extension in the section on Priority and Associativity With advanced examples and a descriptive table, it highlights the importance of understanding the order of evaluation in complex expressions. In addition, complementary topics such as internal documentation, the use of wrapper classes, and classes have been addressed. BigInteger y BigDecimal for high-precision calculations.

A deep understanding of these concepts is essential for writing clear, robust, and maintainable code. Future learning could include exploring how these techniques integrate into design patterns or the optimization of specific algorithms in Java.

17. References and Additional Resources:

  • Official Java Documentation
  • Javadoc Guide
  • Specialized books and tutorials on Java.
Our score
Click to rate this post!
(Votes: 0 Average: 0)
Advertisement
Share on social media...

Deja un comentario

Your email address will not be published. Required fields are marked *

Basic information on data protection
ResponsibleJavier Cachón Garrido +info...
PurposeManage and moderate your comments. +info...
LegitimationConsent of the concerned party. +info...
RecipientsAutomattic Inc., USA to spam filtering. +info...
RightsAccess, rectify and cancel data, as well as some other rights. +info...
Additional informationYou can read additional and detailed information on data protection on our page política de privacidad.

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.

Scroll al inicio

Descubre más desde javiercachon.com

Suscríbete ahora para seguir leyendo y obtener acceso al archivo completo.

Seguir leyendo