JavaJava · Chapterبەش 5 · Lectureوانە 5.3
The switch Statementڕستەی switch
Choosing among many fixed values with Java's switch: case labels, break and default, the types a switch can test in Java 17 (not long, float, double or boolean), fall-through and the -Xlint:fallthrough warning, grouped cases, String cases and a null String, the rules for case labels, and the modern forms: arrow labels case … -> and switch expressions with yield.
هەڵبژاردن لە نێوان چەندین جێگیردا بە switchـی Java: ، break و default، ئەو جۆرانەی لە Java 17ـدا دەتوانێت بیانپشکنێت (نەک long، float، double یان boolean)، و -Xlint:fallthrough، caseـی کۆکراوە، caseـی String و Stringـی ، یاساکانی و شێوە نوێیەکان: شێوەی تیر case … -> و لەگەڵ yield.
What you will learnچی فێر دەبیت
- Replace a long
else ifladder on one value with aswitchofcaselabels,breakanddefault. - Know which values Java 17 can switch on, and read javac's messages for the ones it refuses.
- Predict fall-through, use it on purpose for grouped cases, and avoid it with
breakor arrow labels. - Write a switch expression that gives a value, with
yieldfor longer cases.
- پەیژەیەکی درێژی
else ifکە یەک دەپشکنێت بەswitchـێک بگۆڕیت کە ،breakوdefaultـی تێدایە. - بزانیت Java 17 دەتوانێت لەسەر چ switch بکات و javac بۆ ئەوانەی ڕەتیان دەکاتەوە بخوێنیتەوە.
- پێشبینی بکەیت، بە ئەنقەست بۆ caseـی کۆکراوە بەکاری بهێنیت و بە
breakیان شێوەی تیر خۆتی لێ بپارێزیت. - بنووسیت کە دەدات، لەگەڵ
yieldبۆ caseـی درێژتر.
One value, many casesیەک نرخ، چەندین case
A program often compares one value with a list of fixed values: day 1 means Sunday, day 2 means Monday, and so on. An else if ladder can do it (The else if ladder), but Java has a statement made for this job: the . It works out the value in its brackets once, then goes straight to the with the same value and runs the code there. So a switch tests equality: one value against many possible values.
زۆرجار یەک لەگەڵ لیستێک جێگیر بەراورد دەکات: ڕۆژی 1 واتە یەکشەممە، ڕۆژی 2 واتە دووشەممە و بەم شێوەیە. پەیژەیەکی else if دەتوانێت ئەم کارە بکات (پەیژەی else if)، بەڵام Java تایبەتی بۆ ئەم کارە هەیە: . ناو کەوانەکانی یەک جار دەدۆزێتەوە، پاشان ڕاستەوخۆ دەچێت بۆ ئەو کە هەمان هەیە و کۆدەکەی ئەوێ جێبەجێ دەکات. کەواتە switch یەکسانی دەپشکنێت: یەک بەرامبەر بە چەندین گونجاو.
The parts of a switchبەشەکانی switch
A switch has a value in brackets and a block in braces. Each case gives one value and a colon, followed by the statements for that case. break; ends the case and leaves the switch. The default: part runs when no case matches. A switch can have any number of cases; default is optional, and so is the break after the last part. Every case value must have the same type as the value in the brackets.
switch لە ناو کەوانەی بچووک و لە ناو کەوانەی { }ـدا هەیە. هەر caseـێک یەک و دوو خاڵ دەنووسێت، لە دوایدا ئەو caseـە دێن. break; caseـەکە کۆتایی پێ دەهێنێت و لە switch دەردەچێت. بەشی default: کاتێک جێبەجێ دەبێت کە هیچ caseـێک نەگونجێت. switch دەتوانێت هەر ژمارەیەک case لەخۆ بگرێت؛ default ئارەزوومەندانەیە، breakـی دوای دوایین بەشیش هەروەها. هەموو caseـێک دەبێت هەمان جۆری ناو کەوانەکانی هەبێت.
You may also put braces around the statements of one case (case 1: { … break; }), as some books do. They are allowed but not needed: a case runs from its label down to the break.
دەتوانیت کەوانەی { } بە دەوری یەک caseـیشدا دابنێیت (case 1: { … break; })، وەک هەندێک کتێب دەیکەن. ڕێگەپێدراون بەڵام پێویست نین: caseـێک لە تا break جێبەجێ دەبێت.
A first switch: value 10یەکەم switch: نرخی 10
Here value is 10. Java compares it with the cases from the top: case 10 matches, so it prints Value is 10, and break jumps to the first statement after the switch. The same break also ends loops: break in a switch and in a loop.
لێرەدا value دەکاتە 10. Java لە سەرەوە لەگەڵ caseـەکان بەراوردی دەکات: case 10 دەگونجێت، بۆیە Value is 10 چاپ دەکات و break بازدەدات بۆ یەکەم لە دوای switch. هەمان break کۆتایی پێ دەهێنێت: break لە switch و لە خولدا.
public class SwitchExample {
public static void main(String[] args) {
int value = 10;
switch (value) {
case 10:
System.out.println("Value is 10");
break;
case 20:
System.out.println("Value is 20");
break;
case 30:
System.out.println("Value is 30");
break;
default:
System.out.println("Value is not 10, 20 or 30");
}
System.out.println("After the switch");
}
}$ java SwitchExample Value is 10 After the switch
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
The value to test: an
int.کە دەپشکنرێت:
intـێک.- Lineدێڕی 5-7
The matching case runs, then
breakleaves the switch.caseـە گونجاوەکە جێبەجێ دەبێت، پاشان
breakلە switch دەردەچێت.- Lineدێڕی 14-15
defaultruns only when no case matches.defaultتەنیا کاتێک جێبەجێ دەبێت کە هیچ caseـێک نەگونجێت.


With value = 25 no case matches, so default prints Value is not 10, 20 or 30. The second half of the animation shows what happens when the breaks are missing: Forgetting break explains it.
کاتێک value = 25، هیچ caseـێک ناگونجێت، بۆیە default Value is not 10, 20 or 30 چاپ دەکات. نیوەی دووەمی وێنە جووڵاوەکە پیشان دەدات چی ڕوو دەدات کاتێک breakـەکان ون بن: لەبیرچوونی break ڕوونی دەکاتەوە.
Days of the week from the keyboardڕۆژەکانی هەفتە لە کیبۆردەوە
The value usually comes from the user. This program reads a day number with Scanner (Keyboard input) and prints the name of one of the five school and working days in the Kurdistan Region, Sunday to Thursday:
زۆرجار لە دێت. ئەم بە Scanner ژمارەی ڕۆژێک دەخوێنێتەوە (نێوخستەی کیبۆرد) و ناوی یەکێک لە پێنج ڕۆژی خوێندن و کاری هەرێمی کوردستان چاپ دەکات، لە یەکشەممەوە تا پێنجشەممە:
import java.util.Scanner;
public class SwitchDay {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Day number: ");
int day = input.nextInt();
switch (day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
default:
System.out.println("Enter a number from 1 to 5");
}
}
}$ java SwitchDay Day number: 3 Tuesday $ java SwitchDay Day number: 7 Enter a number from 1 to 5
In a city's taxi garage every lane has a sign with a city name. You walk straight to the lane whose sign matches your destination; for a town with no sign, you ask at the office. The signs are the cases and the office is default.
لە گەراجی تەکسیی شارێکدا هەر ڕیزێک تابلۆیەکی بە ناوی شارێک هەیە. ڕاستەوخۆ دەچیت بۆ ئەو ڕیزەی تابلۆکەی لەگەڵ شوێنی مەبەستت دەگونجێت؛ بۆ شارۆچکەیەک کە تابلۆی نییە، لە ئۆفیسەکە پرسیار دەکەیت. تابلۆکان caseـەکانن و ئۆفیسەکە defaultـە.
Where the analogy stops workingسنووری ئەم نموونەیە
A passenger stops at the right lane. Java does not stop by itself: without break it walks on into the next lanes.
سەرنشین لە ڕیزە دروستەکەدا دەوەستێت. Java بە خۆی ناوەستێت: بێ break بەردەوام دەبێت بۆ ناو ڕیزەکانی دواتر.
Which values can a switch test?switch چ نرخێک دەپشکنێت؟
In Java 17 the value in the brackets may be a char, byte, short or int, one of their Character, Byte, Short and Integer (Java takes the number out of the object; Wrapper classes explains them), a String, or an (Enums in a switch). String came in Java 7 (2011); enums and wrapper classes have worked since Java 5 (2004), the version that added enums and automatic boxing.
لە Java 17ـدا ناو کەوانەکان دەتوانێت char، byte، short یان int بێت، یان یەکێک لە ئەوان: Character، Byte، Short و Integer (Java ژمارەکە لە دەردەهێنێت؛ کلاسە پێچەرەوەکان ڕوونیان دەکاتەوە)، یان String، یان (ئینەمەکان لە switchـدا). String لە Java 7ـدا (2011) هات؛ و لە Java 5ـەوە (2004) کار دەکەن، ئەو وەشانەی و زیاد کرد.
public class AllowedTypes {
public static void main(String[] args) {
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("char: excellent");
break;
case 'B':
System.out.println("char: very good");
break;
}
byte floor = 2;
switch (floor) {
case 1:
System.out.println("byte: first floor");
break;
case 2:
System.out.println("byte: second floor");
break;
}
Integer seats = 4; // an Integer object
switch (seats) {
case 4:
System.out.println("Integer: a small car");
break;
case 7:
System.out.println("Integer: a family car");
break;
}
}
}$ java AllowedTypes char: very good byte: second floor Integer: a small car
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 20
An
Integerobject: Java unboxes it to theint4.Integer: Java دەیکاتەوە بەintـی 4.
Which values can a switch test?switch چ نرخێک دەپشکنێت؟
Not long, double or booleanنەک long، double یان boolean
A long, float, double or boolean cannot be the value of a switch in Java 17. javac's message is confusing: it first talks about patterns, a feature of newer Java versions, and then says that the int labels do not fit a long:
long، float، double یان boolean ناتوانن switch بن لە Java 17ـدا. javac سەرلێشێوێنەرە: سەرەتا باسی patterns دەکات، تایبەتمەندییەکی وەشانە نوێیەکانی Java، پاشان دەڵێت intـی ناو caseـەکان لەگەڵ long ناگونجێن:
public class SwitchLong {
public static void main(String[] args) {
long code = 2;
switch (code) {
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
}
}
}$ javac SwitchLong.java
SwitchLong.java:4: error: patterns in switch statements are a preview feature and are disabled by default.
switch (code) {
^
(use --enable-preview to enable patterns in switch statements)
SwitchLong.java:5: error: constant label of type int is not compatible with switch selector type long
case 1:
^
SwitchLong.java:8: error: constant label of type int is not compatible with switch selector type long
case 2:
^
3 errorsA double or a boolean gives the same kind of message. For such values write an if … else ladder; a boolean has only two values, so a plain if … else is the right tool. When a long surely holds a small number, a cast is possible: switch ((int) code) compiles and prints two (Narrowing).
double یان booleanـیش هەمان جۆرە پەیام دەدەن. بۆ ئەم پەیژەیەکی if … else بنووسە؛ boolean تەنیا دوو هەیە، بۆیە if … elseـێکی سادە ئامرازی دروستە. کاتێک دڵنیایت longـێک ژمارەیەکی بچووک هەڵدەگرێت، دەکرێت: switch ((int) code) کۆمپایل دەبێت و two چاپ دەکات (تەسککردنەوەی جۆر).
Forgetting break: fall-throughلەبیرچوونی break: تێپەڕین
break is optional. Without it, Java does not stop at the end of the matching case: it falls through and runs the statements of the following cases too, until it meets a break or the end of the switch. The cases above the matching one never run. This is called . Here courses is 3 and no case has a break:
break ئارەزوومەندانەیە. بەبێ ئەو، Java لە کۆتایی caseـە گونجاوەکەدا ناوەستێت: تێدەپەڕێت و caseـەکانی دواتریش جێبەجێ دەکات، تا دەگاتە breakـێک یان کۆتایی switch. caseـەکانی سەرووی caseـە گونجاوەکە هەرگیز جێبەجێ نابن. ئەمە پێی دەڵێن . لێرەدا courses دەکاتە 3 و هیچ caseـێک breakـی نییە:
public class Courses {
public static void main(String[] args) {
int courses = 3;
switch (courses) {
case 1:
System.out.println("Java");
case 2:
System.out.println("Python");
case 3:
System.out.println("Cloud computing");
case 4:
System.out.println("Automation testing");
case 5:
System.out.println("Hadoop");
case 6:
System.out.println("Artificial intelligence");
default:
System.out.println("There are no other courses");
}
}
}$ java Courses Cloud computing Automation testing Hadoop Artificial intelligence There are no other courses
Forgetting break: fall-throughلەبیرچوونی break: تێپەڕین
Let javac warn youبا javac ئاگادارت بکاتەوە
javac compiles a fall-through without a word, because sometimes it is wanted. Add the option -Xlint:fallthrough and javac prints a for every case that the case above it falls into:
javac بێ هیچ قسەیەک کۆمپایل دەکات، چونکە هەندێک جار مەبەستە. ئەگەر هەڵبژاردەی -Xlint:fallthrough زیاد بکەیت، javac بۆ هەر caseـێک کە caseـی سەرووی تێی دەپەڕێت چاپ دەکات:
javac -Xlint:fallthrough Courses.javaCourses.java:7: warning: [fallthrough] possible fall-through into case
case 2:
^
Courses.java:9: warning: [fallthrough] possible fall-through into case
case 3:
^
Courses.java:11: warning: [fallthrough] possible fall-through into case
case 4:
^
Courses.java:13: warning: [fallthrough] possible fall-through into case
case 5:
^
Courses.java:15: warning: [fallthrough] possible fall-through into case
case 6:
^
Courses.java:17: warning: [fallthrough] possible fall-through into case
default:
^
6 warningsThe program still compiles and runs the same; the warnings only point at the places to check. -Xlint on its own turns on all of javac's recommended warnings. When you want a fall-through, a comment such as // falls through on purpose tells the next reader, or use the grouped labels of the next screen.
هەر کۆمپایل دەبێت و وەک پێشوو کار دەکات؛ تەنیا ئەو شوێنانە پیشان دەدەن کە دەبێت بپشکنرێن. -Xlint بە تەنیا هەموو هۆشدارییە پێشنیارکراوەکانی javac چالاک دەکات. ئەگەر دەوێت، وەک // falls through on purpose خوێنەری داهاتوو ئاگادار دەکاتەوە، یان کۆکردنەوەی لە شاشەی داهاتوو بەکار بهێنە.
Fall-through on purpose: several cases, one answerتێپەڕین بە ئەنقەست: چەند case، یەک وەڵام
Fall-through helps when several values need the same code. Write their labels one under the other with no statements between them: days 1 to 5 all reach School day. Since Java 14 one label can also list several values: case 1, 2, 3, 4, 5: and case 6, 7: give the same results.
بەسوودە کاتێک چەند پێویستیان بە هەمان کۆد هەیە. ئەوان لە ژێر یەکتردا بنووسە بێ ئەوەی هیچ لە نێوانیاندا بێت: ڕۆژەکانی 1 تا 5 هەموویان دەگەنە School day. لە Java 14ـەوە یەک case دەتوانێت چەند بنووسێت: case 1, 2, 3, 4, 5: و case 6, 7: هەمان ئەنجام دەدەن.
import java.util.Scanner;
public class SchoolWeek {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Day number (1 = Sunday): ");
int day = input.nextInt();
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("School day");
break;
case 6:
case 7:
System.out.println("Weekend");
break;
default:
System.out.println("There is no such day");
}
}
}$ java SchoolWeek Day number (1 = Sunday): 2 School day $ java SchoolWeek Day number (1 = Sunday): 6 Weekend $ java SchoolWeek Day number (1 = Sunday): 9 There is no such day
Switching on textswitch لەسەر دەق
A String can be the value of a switch too. Java compares it with each case the way equals does (Comparing strings): exactly, letter by letter, and capital letters matter. Football positions make a good example:
Stringـیش دەتوانێت switch بێت. Java بە هەمان شێوەی equals لەگەڵ هەر caseـێک بەراوردی دەکات (بەراوردکردنی زنجیرەنووسەکان): ڕێک، پیت بە پیت و پیتی گەورەش گرنگە. پۆستەکانی تۆپی پێ نموونەیەکی باشن:
import java.util.Scanner;
public class Positions {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Position: ");
String position = input.next();
switch (position) {
case "goalkeeper":
System.out.println("Guards the goal and may catch the ball");
break;
case "defender":
System.out.println("Stops the other team's attacks");
break;
case "midfielder":
System.out.println("Links the defence and the attack");
break;
case "striker":
System.out.println("Tries to score goals");
break;
default:
System.out.println("No such position");
}
}
}$ java Positions Position: striker Tries to score goals $ java Positions Position: Striker No such position
Striker with a capital S matches no case. Compare a lower-case copy instead: with switch (position.toLowerCase()), Striker and GOALKEEPER work too (Upper and lower case):
Striker بە Sـی گەورە لەگەڵ هیچ caseـێک ناگونجێت. لە جیاتی ئەوە کۆپییەکی پیت بچووک بەراورد بکە: بە switch (position.toLowerCase())، Striker و GOALKEEPERـیش کار دەکەن (پیتی گەورە و بچووک):
$ java Positions Position: Striker Tries to score goals $ java Positions Position: GOALKEEPER Guards the goal and may catch the ball
Switching on textswitch لەسەر دەق
A null String stops the programStringـی بێنرخ بەرنامەکە دەوەستێنێت
A String variable can also hold : no object at all. To compare a String, the switch has to use the object, so a null stops the program with a NullPointerException:
String دەتوانێت هەڵبگرێت: هیچ نییە. switch بۆ بەراوردکردنی Stringـێک دەبێت بەکار بهێنێت، بۆیە null بە NullPointerException دەوەستێنێت:
public class NullPosition {
public static void main(String[] args) {
String position = null; // no String object at all
switch (position) {
case "striker":
System.out.println("Tries to score goals");
break;
default:
System.out.println("No such position");
}
}
}$ java NullPosition Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.hashCode()" because "<local2>" is null at NullPosition.main(NullPosition.java:4)
<local2> is a hidden copy of position that javac made; line 4 is the switch. Check for null first: if (position == null) { … } else { switch (position) { … } } prints No position given instead. (Exceptions explains the error itself.)
<local2> کۆپییەکی شاراوەی positionـە کە javac دروستی کردووە؛ دێڕی 4 switchـەکەیە. سەرەتا بپشکنە: if (position == null) { … } else { switch (position) { … } } لە جیاتی ئەوە No position given چاپ دەکات. (هەڵاوێردەکان خودی هەڵەکە ڕوون دەکاتەوە.)
The rules for case labelsیاساکانی بەشەکانی case
javac checks every label: a case value must be a , either a such as 1, 'A' or "Hawler" or a final variable that holds one. It must fit the type of the switch value, and no value may appear twice. The order of the cases does not matter: any order the problem needs is fine.
javac هەموو caseـێک دەپشکنێت: case دەبێت بێت: یان وەک 1، 'A' یان "Hawler"، یان final کە یەکێکی وای هەڵگرتبێت. دەبێت لەگەڵ جۆری switch بگونجێت و هیچ دووجار نەیەت. ڕیزبەندیی caseـەکان گرنگ نییە: هەر ڕیزبەندییەک کە کێشەکە پێویستی بێت باشە.
public class CaseRules {
public static void main(String[] args) {
int x = 1;
int y = 2;
switch (x) {
case 1:
System.out.println("one");
break;
case 1:
System.out.println("one again");
break;
case y:
System.out.println("the value of y");
break;
}
}
}$ javac CaseRules.java
CaseRules.java:9: error: duplicate case label
case 1:
^
CaseRules.java:12: error: constant expression required
case y:
^
2 errorsA String label in an int switch gives incompatible types: String cannot be converted to int. A final constant is fine: with final int LIMIT = 5;, the label case LIMIT: compiles and prints limit for 5.
caseـێکی String لە switchـێکی intـدا incompatible types: String cannot be converted to int دەدات. final باشە: بە final int LIMIT = 5;، case LIMIT: کۆمپایل دەبێت و بۆ 5 limit چاپ دەکات.
The rules for case labelsیاساکانی بەشەکانی case
default can stand anywheredefault لە هەر شوێنێک دەبێت
default is optional, and it may stand anywhere in the block, even first. Java still tries every case first and goes to default only when none matches. But default is a label like the others: without a break it falls through into the cases written after it:
default ئارەزوومەندانەیە و دەتوانێت لە هەر شوێنێکی بلۆکەکەدا بێت، تەنانەت یەکەمیش. Java هەر سەرەتا هەموو caseـەکان تاقی دەکاتەوە و تەنیا کاتێک دەچێت بۆ default کە هیچیان نەگونجێت. بەڵام default وەک ئەوانی تر بەشێکە: بێ break بەرەو ئەو caseـانە تێدەپەڕێت کە لە دوای نووسراون:
import java.util.Scanner;
public class DefaultFirst {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("x: ");
int x = input.nextInt();
switch (x) {
default:
System.out.println("default");
case 1:
System.out.println("one");
case 2:
System.out.println("two");
break;
}
}
}$ java DefaultFirst x: 9 default one two $ java DefaultFirst x: 1 one two
The arrow form: case … ->شێوەی تیر: case … ->
Since Java 14 a case can use an arrow: case 3 -> statement;. An arrow case runs only its own statement, so it never falls through and needs no break. Several values share one arrow with commas, and default -> catches the rest. New Java code mostly uses this form:
لە Java 14ـەوە caseـێک دەتوانێت تیر بەکار بهێنێت: case 3 -> statement;. caseـی تیر تەنیا خۆی جێبەجێ دەکات، بۆیە هەرگیز تێناپەڕێت و پێویستی بە break نییە. چەند بە فاریزە یەک تیر بەش دەکەن و default -> ئەوانی تر دەگرێت. کۆدی نوێی Java زیاتر ئەم شێوەیە بەکار دەهێنێت:
import java.util.Scanner;
public class DayArrow {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Day number: ");
int day = input.nextInt();
switch (day) {
case 1 -> System.out.println("Sunday");
case 2 -> System.out.println("Monday");
case 3 -> System.out.println("Tuesday");
case 4 -> System.out.println("Wednesday");
case 5 -> System.out.println("Thursday");
case 6, 7 -> System.out.println("Weekend");
default -> System.out.println("Enter a number from 1 to 7");
}
}
}$ java DayArrow Day number: 3 Tuesday $ java DayArrow Day number: 7 Weekend $ java DayArrow Day number: 9 Enter a number from 1 to 7
For several statements, put a block after the arrow: case 2 -> { … }. One switch must use one form: mixing -> and : labels gives different case kinds used in the switch.
بۆ چەند ، بلۆکێک لە دوای تیرەکە دابنێ: case 2 -> { … }. هەر switchـێک دەبێت یەک شێوە بەکار بهێنێت: تێکەڵکردنی -> و : هەڵەی different case kinds used in the switch دەدات.
A switch that gives a valueswitchـێک کە نرخێک دەدات
A switch can also be a : it produces a value that you store or print. Each arrow gives the value for its case, and the whole switch stands on the right of =. Mind the ; after the closing brace: the switch is part of an assignment statement.
switch دەتوانێت بێت: بەرهەم دەهێنێت کە هەڵیدەگریت یان چاپی دەکەیت. هەر تیرێک caseـەکەی خۆی دەدات و هەموو switchـەکە لە لای ڕاستی = دادەنرێت. ئاگاداری ; بە لە دوای کەوانەی داخستن: switch بەشێکە لە .
import java.util.Scanner;
public class DayName {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Day number: ");
int day = input.nextInt();
String name = switch (day) {
case 1 -> "Sunday";
case 2 -> "Monday";
case 3 -> "Tuesday";
case 4 -> "Wednesday";
case 5 -> "Thursday";
case 6 -> "Friday";
case 7 -> "Saturday";
default -> "unknown";
};
System.out.println("Day " + day + " is " + name);
}
}$ java DayName Day number: 3 Day 3 is Tuesday $ java DayName Day number: 9 Day 9 is unknown
A switch expression must give a value for every possible input, so it needs a default (unless it switches on an enum and lists every constant). Without one, javac stops: the switch expression does not cover all possible input values.
دەبێت بۆ هەموو گونجاو بدات، بۆیە پێویستی بە default هەیە (مەگەر لەسەر بێت و هەموو بنووسێت). بەبێ ئەو، javac دەوەستێت: the switch expression does not cover all possible input values.
A switch that gives a valueswitchـێک کە نرخێک دەدات
Longer cases: yieldcaseـی درێژتر: yield
When a case needs some statements before its value, give it a block and finish with yield value;. yield belongs to switch expressions; a switch statement uses break. February needs a decision: 29 days in a leap year (divisible by 4 but not by 100, or by 400), otherwise 28. The block uses the ternary operator:
کاتێک caseـێک پێش پێویستی بە چەند هەیە، بلۆکێکی بدەرێ و بە yield value; کۆتایی پێ بهێنە. yield هی ؛ break بەکار دەهێنێت. شوبات پێویستی بە بڕیارێک هەیە: لە ساڵی کەبیسەدا 29 ڕۆژ (دابەشی 4 دەبێت بەڵام نەک دابەشی 100، یان دابەشی 400 دەبێت)، ئەگەر نا 28. بلۆکەکە کارپێکەری سێیانی بەکار دەهێنێت:
import java.util.Scanner;
public class MonthDays {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Month and year: ");
int month = input.nextInt();
int year = input.nextInt();
int days = switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9, 11 -> 30;
case 2 -> {
boolean leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
yield leap ? 29 : 28;
}
default -> 0;
};
System.out.println("Days: " + days);
}
}$ java MonthDays Month and year: 2 2028 Days: 29 $ java MonthDays Month and year: 2 2026 Days: 28 $ java MonthDays Month and year: 9 2026 Days: 30
A block that ends without yield does not compile: switch rule completes without providing a value. yield also works with colon labels inside a switch expression, but arrows are the usual choice.
بلۆکێک کە بێ yield کۆتایی بێت کۆمپایل نابێت: switch rule completes without providing a value. yield لەگەڵ شێوەی دوو خاڵیشدا لە ناو کار دەکات، بەڵام تیر هەڵبژاردنی باوە.
switch or if?switch یان if؟
Use switch when one value is compared with fixed values for equality: day numbers, menu choices, operator characters, words. Use if … else for ranges (mark >= 90), conditions on several variables, decimal numbers and booleans. Both can solve many problems; pick the one that reads more clearly.
switch بەکار بهێنە کاتێک یەک لەگەڵ جێگیر بۆ یەکسانی بەراورد دەکرێت: ژمارەی ڕۆژ، هەڵبژاردنی ، نیشانەی ، وشە. if … else بۆ ماوە (mark >= 90)، سەر چەند ، و بەکار بهێنە. هەردووکیان دەتوانن زۆر کێشە چارەسەر بکەن؛ ئەوەیان هەڵبژێرە کە ڕوونتر دەخوێنرێتەوە.
switch or if?switch یان if؟
A range turned into casesماوەیەک کە دەکرێت بە case
Sometimes a range can become cases. Marks come in bands of ten, and mark / 10 uses integer division: 76 / 10 is 7, so every mark from 70 to 79 lands on case 7:
هەندێک جار ماوەیەک دەکرێت بە case. نمرەکان دە بە دە پۆل دەکرێن و mark / 10 دابەشکردنی ژمارەی تەواو بەکار دەهێنێت: 76 / 10 دەکاتە 7، بۆیە هەموو نمرەیەک لە 70 تا 79 دەکەوێتە سەر case 7:
import java.util.Scanner;
public class GradeSwitch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Mark (0-100): ");
int mark = input.nextInt();
switch (mark / 10) {
case 10, 9 -> System.out.println("Excellent");
case 8 -> System.out.println("Very good");
case 7 -> System.out.println("Good");
case 6 -> System.out.println("Fair");
case 5 -> System.out.println("Pass");
default -> System.out.println("Fail");
}
}
}$ java GradeSwitch Mark (0-100): 95 Excellent $ java GradeSwitch Mark (0-100): 76 Good $ java GradeSwitch Mark (0-100): 50 Pass $ java GradeSwitch Mark (0-100): 49 Fail $ java GradeSwitch Mark (0-100): 101 Excellent
mark / 10: یەک case بۆ هەر پۆلێکی دە نمرەییCêIT101 / 10 is also 10, so a mark of 101 prints Excellent: test the range first with if (mark < 0 || mark > 100), as the grade ladder does. The trick works only when every band has the same width.
هەروەها 101 / 10 دەکاتە 10، بۆیە نمرەی 101 Excellent چاپ دەکات: سەرەتا ماوەکە بە if (mark < 0 || mark > 100) بپشکنە، وەک پەیژەی نمرەکان دەیکات. ئەم فێڵە تەنیا کاتێک کار دەکات کە پانیی هەموو پۆلەکان وەک یەک بێت.
Common mistakesهەڵە باوەکان
| You wroteنووسیت | javac or the run saysjavac یان جێبەجێکردن دەڵێت | Fixچارەسەر |
|---|---|---|
a case without breakcaseـێک بێ break | the next cases run too (no message)caseـەکانی دواتریش جێبەجێ دەبن (بێ پەیام) | break; or case … ->break; یان case … -> |
switch (code) // long | constant label of type int is not compatible with switch selector type long | if … else, or (int) when it surely fitsif … else، یان (int) کاتێک دڵنیایت جێی دەبێتەوە |
case 1: … case 1: | duplicate case label | each value onceهەر یەک جار |
case y: | constant expression required | a literal or a final constant یان final |
case "one": // int switch | incompatible types: String cannot be converted to int | a value of the same type لە هەمان جۆر |
Striker against case "striker"Striker بەرامبەر case "striker" | default runsdefault جێبەجێ دەبێت | switch (s.toLowerCase())switch (s.toLowerCase()) |
a null StringStringـێکی | NullPointerException | if (s == null) firstسەرەتا if (s == null) |
case 1 -> … case 2: … | different case kinds used in the switch | one form per switchیەک شێوە بۆ هەر switchـێک |
a switch expression without default بێ default | the switch expression does not cover all possible input values | add default ->default -> زیاد بکە |
no ; after } of a switch expressionنەبوونی ; لە دوای }ـی | ';' expected | end with };بە }; کۆتایی پێ بهێنە |
a block without yieldبلۆکێک بێ yield | switch rule completes without providing a value | yield value;yield value; |
The real javac messages of the last four rows:
پەیامە ڕاستەقینەکانی javac بۆ چوار ڕیزی کۆتایی:
$ javac Mixed.java
Mixed.java:6: error: different case kinds used in the switch
case 2:
^
1 error
$ javac NoDefault.java
NoDefault.java:4: error: the switch expression does not cover all possible input values
String name = switch (day) {
^
1 error
$ javac NoSemicolon.java
NoSemicolon.java:7: error: ';' expected
}
^
1 error
$ javac NoYield.java
NoYield.java:7: error: switch rule completes without providing a value
}
^
(switch rules in switch expressions must either provide a value or throw)
1 errorPracticeڕاهێنان
Read two whole numbers with an operator between them, such as 12 * 4, and switch on the operator (input.next().charAt(0)) to print the result for +, -, * and /. For /, print the whole quotient and the remainder, and refuse to divide by zero. Any other operator gets a message.
دوو بخوێنەوە کە لە نێوانیاندایە (وەک 12 * 4) و switch لەسەر بکە (input.next().charAt(0)) بۆ ئەوەی ئەنجام بۆ +، -، * و / چاپ بکەیت. بۆ /، بەشی تەواو و چاپ بکە و دابەشکردن بەسەر سفردا ڕەت بکەرەوە. هەر تر پەیامێک وەردەگرێت.
Hintئاماژە
Read a, then the operator with next().charAt(0) (A word or a whole line), then b.
سەرەتا a بخوێنەوە، پاشان بە next().charAt(0) (وشەیەک یان هەموو دێڕێک)، پاشان b.
Show answerوەڵامەکە پیشان بدە
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Calculation (for example 12 * 4): ");
int a = input.nextInt();
char op = input.next().charAt(0);
int b = input.nextInt();
switch (op) {
case '+' -> System.out.println(a + b);
case '-' -> System.out.println(a - b);
case '*' -> System.out.println(a * b);
case '/' -> {
if (b == 0) {
System.out.println("Cannot divide by zero");
} else {
System.out.println(a / b + " remainder " + a % b);
}
}
default -> System.out.println("Unknown operator: " + op);
}
}
}$ java Calculator Calculation (for example 12 * 4): 12 * 4 48 $ java Calculator Calculation (for example 12 * 4): 17 / 5 3 remainder 2 $ java Calculator Calculation (for example 12 * 4): 9 / 0 Cannot divide by zero $ java Calculator Calculation (for example 12 * 4): 2 ^ 3 Unknown operator: ^
17 / 5 is 3 with remainder 2 because both numbers are ints (Integer division). The block after case '/' -> holds an if … else.
17 / 5 دەکاتە 3 و 2، چونکە هەردوو ژمارەکە intـن (دابەشکردنی ژمارەی تەواو). بلۆکی دوای case '/' -> if … elseـێک لەخۆ دەگرێت.
Read a month number and use a switch expression with grouped labels to print the season: 12, 1, 2 Winter; 3, 4, 5 Spring; 6, 7, 8 Summer; 9, 10, 11 Autumn; anything else not a month.
ژمارەی مانگێک بخوێنەوە و بە caseـی کۆکراوە بەکار بهێنە بۆ چاپکردنی وەرز: 12، 1، 2 Winter؛ 3، 4، 5 Spring؛ 6، 7، 8 Summer؛ 9، 10، 11 Autumn؛ هەر شتێکی تر not a month.
Show answerوەڵامەکە پیشان بدە
import java.util.Scanner;
public class Season {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Month (1-12): ");
int month = input.nextInt();
String season = switch (month) {
case 12, 1, 2 -> "Winter";
case 3, 4, 5 -> "Spring";
case 6, 7, 8 -> "Summer";
case 9, 10, 11 -> "Autumn";
default -> "not a month";
};
System.out.println(season);
}
}$ java Season Month (1-12): 1 Winter $ java Season Month (1-12): 4 Spring $ java Season Month (1-12): 10 Autumn $ java Season Month (1-12): 13 not a month
Without running it, write down what this program prints. Then do the same with x = 4.
بەبێ جێبەجێکردن، بنووسە ئەم چی چاپ دەکات. پاشان هەمان شت بکە کاتێک x = 4.
public class Predict {
public static void main(String[] args) {
int x = 2;
switch (x) {
case 1:
System.out.println("A");
case 2:
System.out.println("B");
case 3:
System.out.println("C");
break;
case 4:
System.out.println("D");
default:
System.out.println("E");
}
}
}Show answerوەڵامەکە پیشان بدە
x = 2 enters at case 2, prints B, falls into case 3, prints C, and that break stops it:
x = 2 لە case 2ـەوە دەچێتە ژوورەوە، B چاپ دەکات، دەچێتە ناو case 3، C چاپ دەکات و ئەو breakـە ڕایدەگرێت:
$ java Predict B C
x = 4 prints D, then falls into default and prints E:
x = 4 D چاپ دەکات، پاشان دەچێتە ناو default و E چاپ دەکات:
$ java Predict D E
More practiceڕاهێنانی زیاتر
Rewrite the MultiIf program of the else if ladder (i is 20; it tests 10, 15 and 20) as a switch with arrow labels.
MultiIfـی پەیژەی else if (i دەکاتە 20؛ 10، 15 و 20 دەپشکنێت) وەک switchـێک بە شێوەی تیر بنووسەرەوە.
Show answerوەڵامەکە پیشان بدە
public class MultiSwitch {
public static void main(String[] args) {
int i = 20;
switch (i) {
case 10 -> System.out.println("i is 10");
case 15 -> System.out.println("i is 15");
case 20 -> System.out.println("i is 20");
default -> System.out.println("i is not present");
}
}
}$ java MultiSwitch i is 20
Each i == … test becomes one case, and the final else becomes default.
هەر پشکنینێکی i == … دەبێت بە یەک case و elseـی کۆتایی دەبێت بە default.
This program should print one answer for Yes or yes and another for No or no. Run it with Yes and with yes, explain both outputs, then fix it.
ئەم دەبێت بۆ Yes یان yes یەک وەڵام و بۆ No یان no وەڵامێکی تر چاپ بکات. بە Yes و بە yes جێبەجێی بکە، هەردوو ڕوون بکەرەوە، پاشان چاکی بکەرەوە.
import java.util.Scanner;
public class Answer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Continue? ");
String answer = input.next();
switch (answer) {
case "Yes":
System.out.println("Let's go on");
case "No":
System.out.println("Goodbye");
break;
default:
System.out.println("Please answer Yes or No");
}
}
}Show answerوەڵامەکە پیشان بدە
$ java Answer Continue? Yes Let's go on Goodbye $ java Answer Continue? yes Please answer Yes or No
Bug 1: case "Yes" has no break, so Yes falls into Goodbye. Bug 2: String cases are case-sensitive, so yes reaches default. The fix compares a lower-case copy and uses arrows:
باگی 1: case "Yes" breakـی نییە، بۆیە Yes دەچێتە ناو Goodbye. باگی 2: caseـەکانی String ، بۆیە yes دەگاتە default. چارەسەرەکە کۆپییەکی پیت بچووک بەراورد دەکات و تیر بەکار دەهێنێت:
import java.util.Scanner;
public class Answer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Continue? ");
String answer = input.next();
switch (answer.toLowerCase()) {
case "yes" -> System.out.println("Let's go on");
case "no" -> System.out.println("Goodbye");
default -> System.out.println("Please answer Yes or No");
}
}
}$ java Answer Continue? Yes Let's go on $ java Answer Continue? yes Let's go on $ java Answer Continue? NO Goodbye
Show the menu 1 Tea 2 Coffee 3 Juice, read a choice, and use a switch expression to find the price: tea 500, coffee 1500, juice 1000 dinars. Print the price, or We do not have that for any other number.
1 Tea 2 Coffee 3 Juice پیشان بدە، هەڵبژاردنێک بخوێنەوە و بەکار بهێنە بۆ دۆزینەوەی نرخ: چا 500، قاوە 1500، شەربەت 1000 دینار. نرخەکە چاپ بکە، یان بۆ هەر ژمارەیەکی تر We do not have that.
Show answerوەڵامەکە پیشان بدە
import java.util.Scanner;
public class TeaHouse {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("1 Tea 2 Coffee 3 Juice");
System.out.print("Your choice: ");
int choice = input.nextInt();
int price = switch (choice) {
case 1 -> 500;
case 2 -> 1500;
case 3 -> 1000;
default -> 0;
};
if (price == 0) {
System.out.println("We do not have that");
} else {
System.out.println("Please pay " + price + " dinars");
}
}
}$ java TeaHouse 1 Tea 2 Coffee 3 Juice Your choice: 1 Please pay 500 dinars $ java TeaHouse 1 Tea 2 Coffee 3 Juice Your choice: 3 Please pay 1000 dinars $ java TeaHouse 1 Tea 2 Coffee 3 Juice Your choice: 5 We do not have that
default -> 0 gives a number that no drink costs, and the if after the switch checks for it.
default -> 0 ژمارەیەک دەدات کە هیچ خواردنەوەیەک ئەو نرخەی نییە و ifـەکەی دوای switch ئەوە دەپشکنێت.
Summaryکورتە
- A
switchcompares one value with fixed case values for equality and runs the matching case;defaultcatches the rest. - Java 17 allows
char,byte,short,int, their wrappers,Stringand enums, notlong,float,doubleorboolean. - Without
break, execution falls through into the next cases;-Xlint:fallthroughwarns. Grouped labels use fall-through on purpose. - Case values are unique constants of the right type. String cases are exact; a
nullString throws aNullPointerException. - Arrow labels
case … ->never fall through. A switch expression gives a value, needsdefaultand ends with};;yieldgives the value of a block.
switchیەک بۆ یەکسانی لەگەڵ جێگیرەکانی case بەراورد دەکات و caseـە گونجاوەکە جێبەجێ دەکات؛defaultئەوانی تر دەگرێت.- Java 17 ڕێگە بە
char،byte،short،int، ،Stringو دەدات، نەکlong،float،doubleیانboolean. - بێ
break، جێبەجێکردن بەرەو caseـەکانی دواتر تێدەپەڕێت؛-Xlint:fallthroughئاگادار دەکاتەوە. caseـی کۆکراوە بە ئەنقەست بەکار دەهێنن. - case بێ دووپاتە و لە جۆری دروستن. caseـی String ڕێکە؛ Stringـێکی
NullPointerExceptionدەدات. - شێوەی تیر
case … ->هەرگیز تێناپەڕێت. دەدات، پێویستی بەdefaultهەیە و بە};کۆتایی دێت؛yieldبلۆکێک دەدات.
Why is long not allowed in a Java 17 switch?بۆچی long لە switchـی Java 17ـدا ڕێگەپێنەدراوە؟
The language rules list only char, byte, short, int, their wrappers, String and enums. javac says constant label of type int is not compatible with switch selector type long.
یاساکانی زمانەکە تەنیا char، byte، short، int، ، String و دەژمێرن. javac دەڵێت constant label of type int is not compatible with switch selector type long.
What does courses = 3 print when no case has a break?courses = 3 چی چاپ دەکات کاتێک هیچ caseـێک breakـی نییە؟
Everything from case 3 to the end: five lines. Cases 1 and 2 never run.
هەموو شتێک لە case 3ـەوە تا کۆتایی: پێنج دێڕ. caseـەکانی 1 و 2 هەرگیز جێبەجێ نابن.
When do you need yield?کەی پێویستت بە yield هەیە؟
In a switch expression, when a case is a block { … }: yield gives that block's value.
لە ، کاتێک caseـێک بلۆکێکی { … }ـە: yield ئەو بلۆکە دەدات.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Strings and String Methodsزنجیرەنووسەکان و میتۆدەکانی String
Related lecturesوانە پەیوەندیدارەکان
- Comparisons, Booleans and if…elseبەراوردکردن، بوولیانەکان و if…else
- Strings and String Methodsزنجیرەنووسەکان و میتۆدەکانی String
- Abstract Classes, Interfaces, Inner Classes and Enumsکلاسە ڕووتەکان، نێوبەستەکان، کلاسە ناوەکییەکان و ئینەمەکان
- break and continueڕستەی break و ڕستەی continue
- Keyboard Input with Scanner and Formatted Outputنێوخستە لە کیبۆردەوە بە Scanner و دەرخستەی ڕێکخراو
- Logical Operators and Nested ifکارپێکەرە لۆجیکییەکان و ڕستەی ifـی ناوەکی
- The switch Statementڕستەی switch
- Conditional Statements: if, else, elseif and switchڕستە مەرجییەکان: if و else و elseif و switch
- Dart Basics: Variables, Types and Control Flowبنەماکانی Dart: گۆڕاوەکان، جۆرەکان و ڕێڕەوی کۆنترۆڵ
- Algorithms, Pseudocode and Flowchartsئەلگۆریزمەکان، نیمچەکۆد و هێڵکارییەکانی ڕەوت
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- W3Schools: Java Switch
- Java Language Specification (Java SE 17), §14.11 The switch Statement
- Java SE 17 Language Guide: Switch Expressions
- JEP 361: Switch Expressions (JDK 14)
- JEP 441: Pattern Matching for switch (JDK 21)
- JDK 27 (JEP 532: Primitive Types in Patterns, instanceof, and switch, fifth preview)
- Java version history (Java SE 5 enums and autoboxing; Java SE 7 strings in switch)
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.