+ 1

Why do we use switch function?

I mean in the following code couldn't we use IF function? what's the difference? thank YOU public class Program { public static void main(String[] args) { int day = 3; switch(day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; } } }

28th Jul 2017, 6:30 AM
Dariush Shiri
Dariush Shiri - avatar
3 ответов
+ 10
For certain cases, switch structures can keep things more organised and readable. Instead of 3 if else statements, you only need one switch structure to complete the task.
28th Jul 2017, 6:32 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
In real programs, the problem is that you don't know what day contains.
28th Jul 2017, 10:07 AM
Hatsy Rei
Hatsy Rei - avatar
0
but we do know that we want day 3 and can just execute in case day = 3; we can use: if day = 3; System.out.print("Wednesday"); why should we use 3 if else statement?
28th Jul 2017, 6:48 AM
Dariush Shiri
Dariush Shiri - avatar