- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwitch.java
More file actions
Latest commit
91 lines (78 loc) · 2.51 KB
/
Copy pathSwitch.java
File metadata and controls
91 lines (78 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
importjava.util.scanner;
publicclassSwitch {
publicstaticvoidmain(String[] args){
System.out.println("Enter your option too know the reward");
Scannerobj = newScanner(System.in);
intchoice = obj.nextInt();
switch(choice){
case1:
System.out.println("you got a jackpot");
break;
case2:
System.out.println("your fined");
break;
case3:
System.out.println("null space");
break;
case4:
System.out.println("Welcome to the world of luck");
break;
default:
System.out.println("Try again later!!!");
}
}
}
JavaSwitch
JavaSwitchStatements
Insteadofwritingmanyif..elsestatements, youcanusetheswitchstatement.
Theswitchstatementselectsoneofmanycodeblockstobeexecuted:
SyntaxGetyourownJavaServer
switch(expression) {
casex:
// code block
break;
casey:
// code block
break;
default:
// code block
}
Thisishowitworks:
Theswitchexpressionisevaluatedonce.
Thevalueoftheexpressioniscomparedwiththevaluesofeachcase.
Ifthereisamatch, theassociatedblockofcodeisexecuted.
Thebreakanddefaultkeywordsareoptional, andwillbedescribedlaterinthischapter
Theexamplebelowusestheweekdaynumbertocalculatetheweekdayname:
Example
intday = 4;
switch (day) {
case1:
System.out.println("Monday");
break;
case2:
System.out.println("Tuesday");
break;
case3:
System.out.println("Wednesday");
break;
case4:
System.out.println("Thursday");
break;
case5:
System.out.println("Friday");
break;
case6:
System.out.println("Saturday");
break;
case7:
System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)
ThebreakKeyword
WhenJavareachesabreakkeyword, itbreaksoutoftheswitchblock.
Thiswillstoptheexecutionofmorecodeandcasetestinginsidetheblock.
Whenamatchisfound, andthejobisdone, it's time for a break. There is no need for more testing.
Abreakcansavealotofexecutiontimebecauseit"ignores"theexecutionofalltherestofthecodeintheswitchblock.
ThedefaultKeyword
Thedefaultkeywordspecifiessomecodetorunifthereisnocasematch: willgetexcuted!!