Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

197
Vistas
Why switch statement in not comparing the int values?

**I wrote a simple code that have to compare to numbers, but when I run it compiler say me that has a error with boolean values. I dont understand why it doesnt work **

{
    public static void main(String[] args) {
        compare(8,22);
    }

    static void compare(int a, int b){
        switch (a) {
            case (a > b) -> System.out.println(a + " > " + b);
            case (b < a) -> System.out.println(a + " < " + b);
            case (a == b) -> System.out.println(a + " = " + b);
            default -> System.out.println("Something is wrong !");
        }
    }
}```
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Change it to:

{
    public static void main( String... args ) 
    {
        compare( 8, 22 );
    }

    static void compare( final int a, final int b )
    {
        switch( Integer.signum( Integer.compare( a, b ) ) ) 
        {
            case 1 -> System.out.println( a + " > " + b );
            case -1 -> System.out.println( a + " < " + b );
            case 0 -> System.out.println( a + " = " + b );
            default -> System.out.println( "Something is wrong !" );
        }
    }
}

And it should work!

case requires distinct constant expressions, and the terms that you use ((a > b), (b < a) and (a == b)) are no constants (not to mention that (a > b) and (b < a) are equivalent). They also return a boolean. switch does not handle a boolean switch selector directly.

In JShell, (only) this works for switch with "boolean":

boolean flag = …

switch( Boolean.toString( flag ) )
{
  case "true" -> …
  case "false" -> …
  default -> throw new Error( "Hä?" ); 
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda