Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if else or switch case [duplicate]

Tags:

java

I need to check a small piece of logic and would highly appreciate if someone can give me some valuable input.

I have two ways of checking my logic and want to know which is more efficient.

1st way:

if(url.equalsIgnoreCase("1")){
    url = "aaa";
}
else if(url.equalsIgnoreCase("2")){
    url = "bbb";
}
else if(url.equalsIgnoreCase("3")){
    url = "ccc";
}
else if(url.equalsIgnoreCase("4")){
    url = "ddd";
}
else if(url.equalsIgnoreCase("5")){
    url = "eee";
}
else if(url.equalsIgnoreCase("6")){
    url = "fff";
}

2nd Way:

int temp = Integer.parseInt(url);
switch (temp) {
case 1:
    url = "aaa";
    break;
case 2:
    url = "bbb";
    break;
case 3:
    url = "ccc";
    break;
case 4:
    url = "ddd";
    break;
case 5:
    url = "eee";
    break;
case 6:
    url = "fff";
    break;
}

Please let me know which is more efficient. Is it bad to use Integer.parseInt(string)?

like image 799
Sushil Avatar asked May 20 '26 14:05

Sushil


1 Answers

If your values really are 1-6, the clearest and most efficient way is using an array :

String[] URLS = {...};
url = URLS[Integer.parseInt(url) - 1];
like image 67
njzk2 Avatar answered May 23 '26 05:05

njzk2