Mostrando las entradas con la etiqueta Java. Mostrar todas las entradas
Mostrando las entradas con la etiqueta Java. Mostrar todas las entradas

miércoles, 17 de septiembre de 2025

Evitar un potencial NullPointerException en Java en comparaciones de String

 A continuación un pequeño tip para evitar un potencial NullPointerException, una de las excepciones más comunes al momento de desarrollar en Java, además una de las más difíciles de rastrear.

Imaginemos que tenemos una clase Llama, tiene una función que devuelve un String llamada saySomething(), ahora supongamos que queremos saber si la llama dice «Ola k ase?»

A manera de ejercicio mental… ¿Cómo desarrollarías la comparación?

El modo más común a primera vista sería:

Llama.saySomething().equals(«Ola k ase?»)

Ejemplo:

    
if (Llama.saySomething().equals("Ola k ase?"))
{
   System.out.println("La llama está saludando");
}
else
{
   System.out.println("La llama no está saludando");
}

Si la clase Llama es nula o Llama.saySomething() devuelve null, se generará un NullPointerException… Pero con un pequeño cambio podemos evitar dicha excepción, de la siguiente manera:

if ("Ola k ase?".equals(Llama.saySomething()))
{
   System.out.println("La llama está saludando");
}
else
{
   System.out.println("La llama no está saludando");
}

En este caso de prueba sí Llama.saySomething() es null no se generará una excepción sino que simplemente se ejecuta el código en el else.

lunes, 15 de septiembre de 2025

How to know what century a year belongs to in Java

 Let's code... Let's see how to know what century a year belongs to in Java.

Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc.

Example

For year = 1905, the output should be solution(year) = 20;

For year = 1700, the output should be solution(year) = 17.

Input/Output

[input] integer year

A positive integer, designating the year.

[output] integer

The number of the century the year is in.

Solution

    
int solution(int year) {
    
    // If year ends with 00 century is the first part
    // Example: 400 is 4. 1900 is 19.
    if (year % 100 == 0){
        return (year / 100);
    }
    else{
        // In any other case the century is that part of te year + 1
        return ((year / 100)+1);
    }  
} 
   
 

Conceptos básicos de Apache Kafka

Apache Kafka es una plataforma distribuida de mensajería y streaming diseñada para manejar grandes volúmenes de datos en tiempo real. Desar...