+ 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; } } }
3 Answers
+ 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.
+ 5
In real programs, the problem is that you don't know what day contains.
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?