How to Change If-else statement into Switch Case?

Abhishek Mishra Source

How to change my if-else statement into Switch Case structure?

if (apiName.equals(APIUrlConstant.getIsRegistrationenabledUrl())) {
    IsRegistrationEnableModel isRegistrationEnableModel = gson.fromJson(responsedata, IsRegistrationEnableModel.class);
    listener.onTaskPostExecute(isRegistrationEnableModel, requestData, responsedata);
} else if (apiName.equals(APIUrlConstant.AboutUs)) {
    // do Something
}else if (apiName.equals(APIUrlConstant.AddContentRating)) {
    // do Something
}

apiName is a String type. How to do that?

javaandroidperformance

Answers

answered 3 months ago tomas #1

In the JDK 7 release, you can use a String object in the expression of a switch statement.

https://docs.oracle.com/javase/8/docs/technotes/guides/language/strings-switch.html

answered 3 months ago Hamed Momeni #2

Actually you can't. Switch case expressions must be constant expressions and APIUrlConstant.getIsRegistrationenabledUrl() is not a constant expression.

comments powered by Disqus