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.

20 min read19 خولەک خوێندنەوە · 22 stepsهەنگاو

What you will learnچی فێر دەبیت

  • Replace a long else if ladder on one value with a switch of case labels, break and default.
  • 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 break or arrow labels.
  • Write a switch expression that gives a value, with yield for 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 یەکسانی دەپشکنێت: یەک بەرامبەر بە چەندین گونجاو.

A train labelled day = 3 reaches a switch box, switch (day). Four tracks leave it: case 1 to Sunday, case 2 to Monday, case 3 to Tuesday and default to any other day. The case 3 track is highlighted and the train takes it. Note: Java compares day with each case; no match sends it down the default track.شەمەندەفەرێک بە نیشانەی day = 3 دەگاتە سندووقی switch (day). چوار هێڵ لێی دەردەچن: case 1 بۆ یەکشەممە، case 2 بۆ دووشەممە، case 3 بۆ سێشەممە و default بۆ هەر ڕۆژێکی تر. هێڵی case 3 ڕۆشن کراوەتەوە و شەمەندەفەرەکە ئەو ڕێگایە دەگرێت. تێبینی: Java نرخی day لەگەڵ هەموو caseـێک بەراورد دەکات؛ ئەگەر هیچیان نەگونجا، ڕێگای default دەگرێت.
Like a railway switch, the value sends the program down one trackوەک گۆڕەری هێڵی شەمەندەفەر، دەنێرێتە سەر یەک هێڵCêIT

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ـێک دەبێت هەمان جۆری ناو کەوانەکانی هەبێت.

A switch on day with numbered lines. Line 1, switch (day) {, is marked the value to test; line 2, case 1:, is a case label, a constant to compare with; line 4, break;, jumps out of the switch; line 8, default:, runs when no case matched and is optional; line 10, the closing brace, ends the block that holds the whole switch.switchـێک لەسەر day بە دێڕی ژمارەدار. دێڕی 1، switch (day) {، ئەو نرخەیە کە دەپشکنرێت؛ دێڕی 2، case 1:، بەشی caseـە، نەگۆڕێک بۆ بەراوردکردن؛ دێڕی 4، break;، لە switch دەردەچێت؛ دێڕی 8، default:، کاتێک جێبەجێ دەبێت کە هیچ caseـێک نەگونجا و ئارەزوومەندانەیە؛ دێڕی 10، کەوانەی داخستن، ئەو بلۆکە تەواو دەکات کە هەموو switchـەکە لەخۆ دەگرێت.
The parts of a switch statementبەشەکانی CêIT

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 و لە خولدا.

SwitchExample.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

The value to test: an int.

کە دەپشکنرێت: intـێک.

Lineدێڕی 5-7

The matching case runs, then break leaves the switch.

caseـە گونجاوەکە جێبەجێ دەبێت، پاشان break لە switch دەردەچێت.

Lineدێڕی 14-15

default runs only when no case matches.

default تەنیا کاتێک جێبەجێ دەبێت کە هیچ caseـێک نەگونجێت.

An animated flowchart. With break: value = 10 enters, the test case 10? is true, println("Value is 10") runs and break; jumps to After the switch; the output shows Value is 10 and After the switch. Without break: case 10? is true again, but after Value is 10 the program falls into the boxes for 20, 30 and default without testing them, and the output shows Value is 10, Value is 20, Value is 30, Value is not 10, 20 or 30 and After the switch.
An animated flowchart. With break: value = 10 enters, the test case 10? is true, println("Value is 10") runs and break; jumps to After the switch; the output shows Value is 10 and After the switch. Without break: case 10? is true again, but after Value is 10 the program falls into the boxes for 20, 30 and default without testing them, and the output shows Value is 10, Value is 20, Value is 30, Value is not 10, 20 or 30 and After the switch.
break leaves the switch; without break the program falls throughbreak لە switch دەردەچێت؛ بێ break تێدەپەڕێتCêIT

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 ژمارەی ڕۆژێک دەخوێنێتەوە (نێوخستەی کیبۆرد) و ناوی یەکێک لە پێنج ڕۆژی خوێندن و کاری هەرێمی کوردستان چاپ دەکات، لە یەکشەممەوە تا پێنجشەممە:

SwitchDay.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
        }
    }
}
The taxi garageگەراجی تەکسی

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)⁩ کار دەکەن، ئەو وەشانەی و زیاد کرد.

Two panels for Java 17. Allowed: char, byte, short, int; Character, Byte, Short, Integer; String and enum, that is whole numbers, characters, text and enums. Not allowed: long, float, double, boolean. Note: String since Java 7, enums and wrapper classes since Java 5.دوو پانێڵ بۆ Java 17. ڕێگەپێدراو: char، byte، short، int؛ Character، Byte، Short، Integer؛ String و enum، واتە ژمارە تەواوەکان، نووسەکان، دەق و ئینەمەکان. ڕێگەپێنەدراو: long، float، double، boolean. تێبینی: String لە Java 7ـەوە، ئینەمەکان و کلاسە پێچەرەوەکان لە Java 5ـەوە.
The types a switch accepts in Java 17ئەو جۆرانەی لە ⁦Java 17⁩ـدا وەریان دەگرێتCêIT
AllowedTypes.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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;
        }
    }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 20

An Integer object: Java unboxes it to the int 4.

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 ناگونجێن:

SwitchLong.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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;
        }
    }
}

A 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ـی نییە:

Courses.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
        }
    }
}
courses = 3 and no break anywhere. The boxes case 1 Java and case 2 Python are dashed and marked skipped. An arrow from 3 starts here at case 3 Cloud computing; a line on the right runs on through case 4 Automation testing, case 5 Hadoop, case 6 Artificial intelligence and default There are no other courses, to the end of the switch. The output panel shows those five lines.courses = 3 و هیچ break نییە. سندووقەکانی case 1 Java و case 2 Python هێڵی پچڕپچڕیان هەیە و نیشانەی تێپەڕێنرا. تیرێک لە 3ـەوە لە case 3 Cloud computing دەست پێ دەکات؛ هێڵێک لە لای ڕاست بەردەوام دەبێت بە case 4 Automation testing، case 5 Hadoop، case 6 Artificial intelligence و default There are no other courses تا کۆتایی switch. پانێڵی دەرخستە ئەو پێنج دێڕە پیشان دەدات.
Fall-through: from the matching case to the end: لە caseـە گونجاوەکەوە تا کۆتاییCêIT

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ـی سەرووی تێی دەپەڕێت چاپ دەکات:

BASHType in a terminalلە تێرمیناڵدا بینووسە
javac -Xlint:fallthrough Courses.java

The 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: هەمان ئەنجام دەدەن.

SchoolWeek.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
        }
    }
}
A week strip: tiles 1 Sun, 2 Mon, 3 Tue, 4 Wed, 5 Thu in teal and 6 Fri, 7 Sat in orange. A bracket joins 1 to 5 to the code case 1, 2, 3, 4, 5: System.out.println("School day"); break; and another joins 6 and 7 to case 6, 7: … "Weekend" … break;. Note: the same as writing the five case labels one under the other.شریتی هەفتەیەک: خانەکانی 1 یەکشەممە، 2 دووشەممە، 3 سێشەممە، 4 چوارشەممە، 5 پێنجشەممە بە سەوزی تۆخ و 6 هەینی، 7 شەممە بە پرتەقاڵی. کەوانەیەک 1 تا 5 دەبەستێتەوە بە کۆدی case 1, 2, 3, 4, 5: System.out.println("School day"); break; و یەکێکی تر 6 و 7 بە case 6, 7: … "Weekend" … break;. تێبینی: هەمان شتە ئەگەر پێنج caseـەکە لە ژێر یەکتردا بنووسیت.
Five labels, one body; two labels, another bodyپێنج case، یەک بەش کۆد؛ دوو case، بەشێکی ترCêIT

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ـێک بەراوردی دەکات (بەراوردکردنی زنجیرەنووسەکان): ڕێک، پیت بە پیت و پیتی گەورەش گرنگە. پۆستەکانی تۆپی پێ نموونەیەکی باشن:

Positions.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
        }
    }
}
The typed text Striker and the case text striker as letter boxes: the first boxes, S and s, are marked different, so the switch goes to default. Note: S is not s, capital letters matter. Below, position.toLowerCase() gives striker, which matches the case.دەقی نووسراوی Striker و دەقی caseـەکە striker وەک سندووقی پیت: یەکەم سندووق، S و s، جیاوازن، بۆیە switch دەچێت بۆ default. تێبینی: S وەک s نییە، پیتی گەورە گرنگە. لە خوارەوە، position.toLowerCase() striker دەدات، کە لەگەڵ caseـەکە دەگونجێت.
String cases are exact and case-sensitiveبۆ String، ڕێکن و CêIT

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ـیش کار دەکەن (پیتی گەورە و بچووک):

Outputدەرئەنجام
$ 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 دەوەستێنێت:

NullPosition.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
        }
    }
}

<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 چاپ دەکات. (هەڵاوێردەکان خودی هەڵەکە ڕوون دەکاتەوە.)

Left: the variable position holds null, with no arrow; it goes into a switch box and a stop sign shows NullPointerException: no object, the program stops. Right: position points to an object "striker", with a tick: an object, the cases can be compared.لای چەپ: گۆڕاوی position بێنرخ هەڵدەگرێت، بێ تیر؛ دەچێتە ناو سندووقی switch و نیشانەیەکی وەستان NullPointerException پیشان دەدات: ئۆبجێکت نییە، بەرنامەکە دەوەستێت. لای ڕاست: position ئاماژە بۆ ئۆبجێکتێکی "striker" دەکات، لەگەڵ نیشانەی ڕاست: ئۆبجێکت هەیە، بەشەکانی case بەراورد دەکرێن.
A switch needs a real String object پێویستی بە String هەیەCêIT

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ـەکان گرنگ نییە: هەر ڕیزبەندییەک کە کێشەکە پێویستی بێت باشە.

Six cards. Allowed: case 1: and case 2:, different constants; final int LIMIT = 5; case LIMIT:, a final constant; case 30:, case 10:, case 20:, any order is fine. Not allowed: case 1: twice, duplicate case label; int y = 2; case y:, a variable; switch (x) on an int with case "one":, wrong type for an int.شەش کارت. ڕێگەپێدراو: case 1: و case 2:، نەگۆڕی جیاواز؛ final int LIMIT = 5; case LIMIT:، نەگۆڕێکی final؛ case 30:، case 10:، case 20:، هەر ڕیزبەندییەک باشە. ڕێگەپێنەدراو: case 1: دووجار، هەمان case دووجار؛ int y = 2; case y:، گۆڕاو؛ switch (x) لەسەر int لەگەڵ case "one":، جۆری هەڵە بۆ int.
What can stand after caseدوای case چی دەنووسرێتCêIT
CaseRules.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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;
        }
    }
}

A 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ـانە تێدەپەڕێت کە لە دوای نووسراون:

DefaultFirst.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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;
        }
    }
}
The DefaultFirst switch with numbered lines: default on line 2, case 1 on line 4, case 2 on line 6 and break on line 8. For x = 9 an arrow enters at default and runs down to break: output x: 9, default, one, two. For x = 1 an arrow enters at case 1: output x: 1, one, two. Note: no match for 9, so Java starts at default, wherever it is, and falls through.switchـی DefaultFirst بە دێڕی ژمارەدار: default لە دێڕی 2، case 1 لە دێڕی 4، case 2 لە دێڕی 6 و break لە دێڕی 8. بۆ x = 9 تیرێک لە defaultـەوە دەچێتە ژوورەوە و تا break دەڕوات: دەرخستە x: 9، default، one، two. بۆ x = 1 تیرێک لە case 1ـەوە دەچێتە ژوورەوە: دەرخستە x: 1، one، two. تێبینی: بۆ 9 هیچ caseـێک نەگونجا، بۆیە Java لە default دەست پێ دەکات (لە هەر شوێنێک بێت) و تێدەپەڕێت.
default first, without breakdefault لە سەرەتا، بێ breakCêIT

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 زیاتر ئەم شێوەیە بەکار دەهێنێت:

DayArrow.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
        }
    }
}
The same day switch twice. Colon labels (classic): case 1: … break;, then case 6: and case 7: stacked over one println and break;, then default:; it needs break and can fall through. Arrow labels (Java 14 and later): case 1 -> …, case 6, 7 -> …, default -> …; no break, never falls through, several values in one case, one statement or a block { }.هەمان switchـی ڕۆژەکان دووجار. شێوەی دوو خاڵ (کلاسیک): case 1: … break;، پاشان case 6: و case 7: لە ژێر یەکتردا لە سەر یەک println و break;، پاشان default:؛ پێویستی بە break هەیە و دەکرێت تێبپەڕێت. شێوەی تیر (لە Java 14ـەوە): case 1 -> …، case 6, 7 -> …، default -> …؛ break ناوێت، هەرگیز تێناپەڕێت، چەند نرخێک لە یەک caseـدا، یەک ڕستە یان بلۆکێکی { }.
Colon labels and arrow labelsشێوەی دوو خاڵ و شێوەی تیرCêIT

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 بەشێکە لە .

DayName.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
    }
}
Code: String name = switch (day) { case 1 -> "Sunday"; case 2 -> "Monday"; case 3 -> "Tuesday"; default -> "unknown"; }; with the case 3 line highlighted and the final }; marked. For day = 3 an arrow carries "Tuesday" into the String variable name. Notes: the switch gives a value, and the statement ends with a semicolon.کۆد: String name = switch (day) { case 1 -> "Sunday"; case 2 -> "Monday"; case 3 -> "Tuesday"; default -> "unknown"; }; کە دێڕی case 3 ڕۆشن کراوەتەوە و }; ـی کۆتایی نیشانە کراوە. بۆ day = 3 تیرێک "Tuesday" دەباتە ناو گۆڕاوی Stringـی name. تێبینی: switch نرخێک دەدات و ڕستەکەش بە ; کۆتایی دێت.
A switch expression gives its value to a variable دەداتە CêIT

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⁩. بلۆکەکە کارپێکەری سێیانی بەکار دەهێنێت:

MonthDays.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
    }
}
Code: int days = switch (month) { case 1, 3, 5, 7, 8, 10, 12 -> 31; case 4, 6, 9, 11 -> 30; case 2 -> { boolean leap = ...; yield leap ? 29 : 28; } default -> 0; }; The block of case 2 is highlighted and an arrow carries the value from the yield line to the int variable days, which holds 29. Notes: a block { } runs its statements, then yield gives the value; month 2 of 2028, a leap year.کۆد: int days = switch (month) { case 1, 3, 5, 7, 8, 10, 12 -> 31; case 4, 6, 9, 11 -> 30; case 2 -> { boolean leap = ...; yield leap ? 29 : 28; } default -> 0; }; بلۆکی case 2 ڕۆشن کراوەتەوە و تیرێک نرخەکە لە دێڕی yieldـەوە دەباتە گۆڕاوی intـی days کە 29 هەڵدەگرێت. تێبینی: بلۆکی { } ڕستەکانی ناو خۆی جێبەجێ دەکات، پاشان yield نرخەکە دەدات؛ مانگی 2ـی ساڵی 2028، ساڵێکی کەبیسە.
yield hands the value of a block to the switch expressionyield بلۆکەکە دەداتە CêIT

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)، سەر چەند ، و بەکار بهێنە. هەردووکیان دەتوانن زۆر کێشە چارەسەر بکەن؛ ئەوەیان هەڵبژێرە کە ڕوونتر دەخوێنرێتەوە.

A decision chart. Question: one value compared with fixed values, by equality? Yes leads to switch, with examples day: 1, 2, 3 … 7; op: +, -, *, /; city: "Hawler", "Duhok"; mark / 10: 10, 9, 8 …. No leads to if … else, with examples mark >= 90 (a range), x > 0 && y > 0 (two variables), price < 2.5 (a double) and if (raining) (a boolean).هێڵکارییەکی بڕیار. پرسیار: یەک نرخ بە یەکسانی لەگەڵ نرخە جێگیرەکان بەراورد دەکرێت؟ بەڵێ دەچێت بۆ switch، بە نموونەکانی day: 1، 2، 3 … 7؛ op: +، -، *، /؛ city: "Hawler"، "Duhok"؛ mark / 10: 10، 9، 8 …. نەخێر دەچێت بۆ if … else، بە نموونەکانی mark >= 90 (ماوەیەک)، x > 0 && y > 0 (دوو گۆڕاو)، price < 2.5 (double) و if (raining) (بوولیان).
Equality with fixed values: switch; everything else: if … elseیەکسانی لەگەڵ جێگیر: switch؛ هەموو شتێکی تر: ⁦if … else⁩CêIT

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:

GradeSwitch.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
        }
    }
}
A bar from 0 to 100 split into bands: 0 to 49 is default, Fail; 50 to 59 case 5, Pass; 60 to 69 case 6, Fair; 70 to 79 case 7, Good; 80 to 89 case 8, Very good; 90 to 100 case 10, 9, Excellent. An arrow shows 76 / 10 = 7 landing in case 7. A dashed arrow shows 101 / 10 = 10 landing in the Excellent band too. Notes: integer division drops the last digit, so 70 to 79 all give 7; check 0 to 100 first, because 101 / 10 is also 10 and prints Excellent.ستوونێک لە 0 تا 100 کە کراوە بە چەند پۆلێک: 0 تا 49 default، Fail؛ 50 تا 59 case 5، Pass؛ 60 تا 69 case 6، Fair؛ 70 تا 79 case 7، Good؛ 80 تا 89 case 8، Very good؛ 90 تا 100 case 10, 9، Excellent. تیرێک پیشان دەدات 76 / 10 = 7 دەکەوێتە سەر case 7. تیرێکی پچڕپچڕ پیشان دەدات 101 / 10 = 10 هەروەها دەکەوێتە ناو پۆلی Excellent. تێبینی: دابەشکردنی ژمارەی تەواو دوایین ژمارە فڕێ دەدات، بۆیە 70 تا 79 هەموویان 7 دەدەن؛ سەرەتا 0 تا 100 بپشکنە، چونکە 101 / 10 هەروەها دەکاتە 10 و Excellent چاپ دەکات.
mark / 10: one case for each band of tenmark / 10: یەک case بۆ هەر پۆلێکی دە نمرەییCêIT

101 / 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ـێک بێ breakthe next cases run too (no message)caseـەکانی دواتریش جێبەجێ دەبن (بێ پەیام)break; or case … ->break; یان case … ->
switch (code) // longconstant label of type int is not compatible with switch selector type longif … else, or (int) when it surely fitsif … else، یان (int) کاتێک دڵنیایت جێی دەبێتەوە
case 1: … case 1:duplicate case labeleach value onceهەر یەک جار
case y:constant expression requireda literal or a final constant یان final
case "one": // int switchincompatible types: String cannot be converted to inta value of the same type لە هەمان جۆر
Striker against case "striker"Striker بەرامبەر case "striker"default runsdefault جێبەجێ دەبێتswitch (s.toLowerCase())switch (s.toLowerCase())
a null StringStringـێکی NullPointerExceptionif (s == null) firstسەرەتا if (s == null)
case 1 -> … case 2: …different case kinds used in the switchone form per switchیەک شێوە بۆ هەر switchـێک
a switch expression without default بێ defaultthe switch expression does not cover all possible input valuesadd default ->default -> زیاد بکە
no ; after } of a switch expressionنەبوونی ; لە دوای }ـی ';' expectedend with };بە }; کۆتایی پێ بهێنە
a block without yieldبلۆکێک بێ yieldswitch rule completes without providing a valueyield value;yield value;

The real javac messages of the last four rows:

پەیامە ڕاستەقینەکانی javac بۆ چوار ڕیزی کۆتایی:

Outputدەرئەنجام
$ 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 error

Practiceڕاهێنان

ExerciseڕاهێنانA small calculatorحاسیبەیەکی بچووک

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وەڵامەکە پیشان بدە
Calculator.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
        }
    }
}

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ـێک لەخۆ دەگرێت.

ExerciseڕاهێنانSeasonsوەرزەکان

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وەڵامەکە پیشان بدە
Season.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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);
    }
}
ExerciseڕاهێنانPredict the fall-throughتێپەڕین پێشبینی بکە

Without running it, write down what this program prints. Then do the same with x = 4.

بەبێ جێبەجێکردن، بنووسە ئەم چی چاپ دەکات. پاشان هەمان شت بکە کاتێک x = 4.

Predict.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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ـە ڕایدەگرێت:

Outputدەرئەنجام
$ java Predict
B
C

x = 4 prints D, then falls into default and prints E:

x = 4 D چاپ دەکات، پاشان دەچێتە ناو default و E چاپ دەکات:

Outputدەرئەنجام
$ java Predict
D
E

More practiceڕاهێنانی زیاتر

ExerciseڕاهێنانFrom a ladder to a switchلە پەیژەوە بۆ switch

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وەڵامەکە پیشان بدە
MultiSwitch.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
        }
    }
}

Each i == … test becomes one case, and the final else becomes default.

هەر پشکنینێکی i == … دەبێت بە یەک case و elseـی کۆتایی دەبێت بە default.

ExerciseڕاهێنانFind two bugsدوو باگ بدۆزەرەوە

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 جێبەجێی بکە، هەردوو ڕوون بکەرەوە، پاشان چاکی بکەرەوە.

Answer.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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وەڵامەکە پیشان بدە
Outputدەرئەنجام
$ 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. چارەسەرەکە کۆپییەکی پیت بچووک بەراورد دەکات و تیر بەکار دەهێنێت:

Answer.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
        }
    }
}
ExerciseڕاهێنانA tea house menuمێنیوی چایخانەیەک

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وەڵامەکە پیشان بدە
TeaHouse.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
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");
        }
    }
}

default -> 0 gives a number that no drink costs, and the if after the switch checks for it.

default -> 0 ژمارەیەک دەدات کە هیچ خواردنەوەیەک ئەو نرخەی نییە و ifـەکەی دوای switch ئەوە دەپشکنێت.

Summaryکورتە

  • A switch compares one value with fixed case values for equality and runs the matching case; default catches the rest.
  • Java 17 allows char, byte, short, int, their wrappers, String and enums, not long, float, double or boolean.
  • Without break, execution falls through into the next cases; -Xlint:fallthrough warns. Grouped labels use fall-through on purpose.
  • Case values are unique constants of the right type. String cases are exact; a null String throws a NullPointerException.
  • Arrow labels case … -> never fall through. A switch expression gives a value, needs default and ends with };; yield gives 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 بلۆکێک دەدات.
Review questionsپرسیارەکانی پێداچوونەوە
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زاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

Strings and String Methodsزنجیرەنووسەکان و میتۆدەکانی String

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.

Appearanceڕووکار

Modeدۆخ
Styleشێواز
Coloursڕەنگەکان

Saved on this device only.تەنیا لەسەر ئەم ئامێرە پاشەکەوت دەکرێت.