Transforming if-else into switch case throws error [Java]

Tags: , ,



I tried to convert my if-else statements into a switch case but I had the following problem.

Old code:

if (properties.get("database").toString().equalsIgnoreCase("SQLSERVER")) {
    manager = new CManagingSQLServer();             
} else if (properties.get("database").toString().equalsIgnoreCase("ORACLE")){
    manager = new CManagingOracle();                        
} else if (properties.get("database").toString().equalsIgnoreCase("MYSQL")){
    manager = new CManagingMySQL();                         
} else {
    System.out.println("Not supported DB: " + properties.get("database").toString() + "n");
    System.out.println("Supported DB:");
    System.out.println("- ORACLE");
    System.out.println("- SQLSERVER");
    System.out.println("- MYSQL");
    System.exit(0);
}

New code:

String database = properties.get("database").toString();
switch (database) {
case database.equalsIgnoreCase("SQLSERVER"):
    manager = new CManagingSQLServer();
    break;
case database.equalsIgnoreCase("ORACLE"):
    manager = new CManagingOracle();  
    break;
case database.equalsIgnoreCase("MYSQL"):
    manager = new CManagingMySQL();
    break;

default:
    System.out.println(database + "is not a supported database.");
    System.exit(0);
    break;
}

First, the String database threw an error that I have to change setting/property (actually don’t know) into version 1.7?! After doing so, my cases are throwing now errors. They say: Type mismatch cannot convert from boolean to String.

I read other SO-thread and they said I have to try (String)something or something.ToString(). But both cases didn’t work and I don’t understand what changed with the above mentioned change to version 1.7. And how can I make my cases work again?

Answer

Change database variable to

String database = properties.get("database").toString().toUpperCase();

And switch case to

case "SQLSERVER":

Currently, you are getting error because database.equalsIgnoreCase("SQLSERVER") returns boolean but you are switching on database which is a String.

Also, you need to use minimum of Java 7 because Java versions before that don’t support switch case on String.



Source: stackoverflow