JavaJava · Chapterبەش 5 · Lectureوانە 5.2
Logical Operators, Nested and Multi-way ifکارپێکەرە لۆجیکییەکان، ڕستەکانی ifـی ناوەکی و ifـی فرە ڕێگا
Combining conditions with &&, || and ! (booleans only), truth tables, precedence, short-circuit evaluation and the non-short-circuit & and |, De Morgan's laws, nested ifs and when && can replace them, the multi-way if … else if … else ladder with a 0–100 grade example, the dangling else, avoiding duplicate code, and the conditional operator ?:.
بەستنی بە &&، || و ! (تەنیا )، ، پێشینەیی، و & و |ـی بێ کورتبڕ، ، و کەی && دەتوانێت جێیان بگرێتەوە، پەیژەی فرە ڕێگای if … else if … else بە نموونەیەکی نمرەی 0 تا 100، ، دووربوون لە کۆدی دووپاتە و ?:.
What you will learnچی فێر دەبیت
- Combine conditions with
&&,||and!, read their truth tables, and use short-circuit evaluation as a guard. - Choose between nested ifs and an
else ifladder, order the tests, and test the boundary values. - Avoid the dangling else and duplicate code, and write simple choices with
?:.
- بە
&&،||و!ببەستیت، بخوێنیتەوە و وەک پاسەوان بەکار بهێنیت. - لە نێوان و پەیژەی
else ifـدا هەڵبژێریت، پشکنینەکان ڕیز بکەیت و سنوور تاقی بکەیتەوە. - خۆت لە و کۆدی دووپاتە بپارێزیت و هەڵبژاردنی سادە بە
?:بنووسیت.
Two conditions at once: &&, || and !دوو مەرج پێکەوە: &&، || و !
Logical operators combine conditions. Is an age between 18 and 65? That is two comparisons that must both be true. Java has three ; with a = true and b = false:
پێکەوە دەبەستن. ئایا تەمەنێک لە نێوان 18 و 65دایە؟ ئەمە دوو بەراوردە کە دەبێت هەردووکیان ڕاست بن. Java سێ هەیە؛ کاتێک a = true و b = false:
| Operator | Nameناو | True when …ڕاستە کاتێک … | Exampleنموونە | Resultئەنجام |
|---|---|---|---|---|
&& | AND | both sides are trueهەردوو لا ڕاست بن | a && b | false |
|| | OR | at least one side is trueلانیکەم لایەک ڕاست بێت | a || b | true |
! | NOT | its operand is false (it flips the value) هەڵە بێت ( پێچەوانە دەکاتەوە) | !(a && b) | true |
public class AgeRange {
public static void main(String[] args) {
int age = 20;
System.out.println(age >= 18 && age <= 65);
age = 70;
System.out.println(age >= 18 && age <= 65);
System.out.println(age < 18 || age > 65);
}
}$ java AgeRange true false true
Comparisons are worked out before && and ||, so age >= 18 && age <= 65 needs no brackets. Python writes the same operators as words: and, or, not (Combining conditions).
بەراوردەکان پێش && و || دەژمێردرێن، بۆیە age >= 18 && age <= 65 پێویستی بە کەوانە نییە. Python هەمان بە وشە دەنووسێت: and، or، not (بەستنی مەرجەکان).
Two conditions at once: &&, || and !دوو مەرج پێکەوە: &&، || و !
Only booleans, never numbersتەنیا بوولیان، هەرگیز ژمارە نا
In C, a number can be a condition: zero means false and any other number true, and some tables describe && in those words. Java is stricter: the operands of &&, || and ! must be booleans, and numbers are a compile error:
لە Cـدا ژمارە دەتوانێت بێت: سفر واتە هەڵە و هەر ژمارەیەکی تر واتە ڕاست، هەندێک خشتەش && بەو شێوەیە وەسف دەکەن. Java توندترە: &&، || و ! دەبێت بن و ژمارە :
public class LogicalOnInts {
public static void main(String[] args) {
int a = 1;
int b = 0;
System.out.println(a && b);
}
}$ javac LogicalOnInts.java
LogicalOnInts.java:5: error: bad operand types for binary operator '&&'
System.out.println(a && b);
^
first type: int
second type: int
1 errorThe maths chain 18 <= age <= 65 fails for the same reason: 18 <= age is a boolean, and a boolean cannot be compared with 65. Write age >= 18 && age <= 65. (Python allows both: Truthiness, Chained comparisons.)
زنجیرەی بیرکاریی 18 <= age <= 65 بە هەمان هۆ سەرناکەوێت: 18 <= age و ناتوانرێت لەگەڵ 65دا بەراورد بکرێت. بنووسە age >= 18 && age <= 65. (Python ڕێگە بە هەردووکیان دەدات: ڕاستیی نرخەکان، بەراوردی زنجیرەیی.)
public class AgeChain {
public static void main(String[] args) {
int age = 20;
System.out.println(18 <= age <= 65);
}
}$ javac AgeChain.java
AgeChain.java:4: error: bad operand types for binary operator '<='
System.out.println(18 <= age <= 65);
^
first type: boolean
second type: int
1 errorAll combinations: truth tablesهەموو حاڵەتەکان: خشتەکانی ڕاستی
Two booleans have four combinations. A lists every one with its result. Java can print its own truth tables; %-7b prints a boolean in seven places, on the left (Width and flags):
دوو چوار حاڵەتیان هەیە. هەموویان لەگەڵ ئەنجامەکانیان ڕیز دەکات. Java دەتوانێت خۆی چاپ بکات؛ %-7b لە حەوت شوێندا، لە لای چەپ، چاپ دەکات (پانی و نیشانەکان):
public class TruthTables {
public static void main(String[] args) {
System.out.println("a b a && b a || b");
System.out.printf("%-7b%-7b%-8b%b%n", false, false, false && false, false || false);
System.out.printf("%-7b%-7b%-8b%b%n", false, true, false && true, false || true);
System.out.printf("%-7b%-7b%-8b%b%n", true, false, true && false, true || false);
System.out.printf("%-7b%-7b%-8b%b%n", true, true, true && true, true || true);
System.out.println();
System.out.println("a !a");
System.out.printf("%-7b%b%n", false, !false);
System.out.printf("%-7b%b%n", true, !true);
}
}$ java TruthTables a b a && b a || b false false false false false true false true true false false true true true true true a !a false true true false
These are the tables of the logic gates in digital circuits: the AND gate, the OR gate and the NOT gate. Maths writes AND as , OR as and NOT as (The same ideas in code).
ئەمانە خشتەکانی لە سووڕە دیجیتاڵییەکاندا: گەیتی AND، گەیتی OR و گەیتی NOT. بیرکاری AND بە ، OR بە و NOT بە دەنووسێت (هەمان بیرۆکەکان لە کۆددا).
Which goes first?کامیان یەکەم؟
! is worked out first, then arithmetic, then comparisons, then &&, and || last of the three (Operator precedence). So true || false && false means true || (false && false):
! یەکەم دەژمێردرێت، پاشان ، پاشان بەراوردەکان، پاشان && و لە کۆتاییدا || (پێشینەیی کارپێکەرەکان). بۆیە true || false && false واتە true || (false && false):
public class LogicalOrder {
public static void main(String[] args) {
System.out.println(true || false && false);
System.out.println((true || false) && false);
System.out.println(!true || true);
System.out.println(!(true || true));
}
}$ java LogicalOrder true false true false
Brackets make a mix of && and || easier to read, even when they change nothing: (year % 4 == 0 && year % 100 != 0) || year % 400 == 0.
کەوانە تێکەڵەی && و || ئاسانتر دەکات بۆ خوێندنەوە، تەنانەت کاتێک هیچ ناگۆڕن: (year % 4 == 0 && year % 100 != 0) || year % 400 == 0.
Stop as soon as the answer is knownوەستان هەر کە وەڵامەکە زانرا
&& and || work from left to right and stop as soon as the result is certain. If the left side of && is false, the right side is never evaluated; if the left side of || is true, the right side is skipped. This is , and it lets the left side protect the right side. With d = 0:
&& و || لە چەپەوە بۆ ڕاست کار دەکەن و هەر کە ئەنجامەکە دڵنیا بوو دەوەستن. ئەگەر لای چەپی && هەڵە بێت، لای ڕاست هەرگیز ناژمێردرێت؛ ئەگەر لای چەپی || ڕاست بێت، لای ڕاست تێدەپەڕێنرێت. ئەمە و ڕێگە دەدات لای چەپ لای ڕاست بپارێزێت. کاتێک d = 0:
public class SafeDivision {
public static void main(String[] args) {
int d = 0;
boolean bigShare = d != 0 && 10 / d > 1;
System.out.println(bigShare);
}
}$ java SafeDivision false


Put the guard first. In the wrong order the division runs before the check:
پاسەوانەکە بخە پێشەوە. بە ڕیزبەندیی هەڵە، دابەشکردنەکە پێش پشکنینەکە جێبەجێ دەبێت:
public class UnsafeDivision {
public static void main(String[] args) {
int d = 0;
boolean bigShare = 10 / d > 1 && d != 0;
System.out.println(bigShare);
}
}$ java UnsafeDivision Exception in thread "main" java.lang.ArithmeticException: / by zero at UnsafeDivision.main(UnsafeDivision.java:4)
|| guards the same way: people == 0 || bread / people < 2 never divides when there are no people: with people = 0 the left side is already true, so the whole condition is true and the division is skipped.
|| بە هەمان شێوە پاسەوانی دەکات: people == 0 || bread / people < 2 هەرگیز دابەش ناکات کاتێک کەس نییە: بە people = 0 لای چەپ پێشتر ڕاستە، بۆیە هەموو ڕاستە و دابەشکردنەکە تێدەپەڕێنرێت.
Stop as soon as the answer is knownوەستان هەر کە وەڵامەکە زانرا
& and |: no shortcut& و |: بێ کورتبڕ
On booleans, & and | give the same results as && and ||, but they always evaluate both sides. A counter shows the difference: ++checks runs only when its side is evaluated, which is a :
لەسەر ، & و | هەمان ئەنجامی && و || دەدەن، بەڵام هەمیشە هەردوو لا دەژمێرن. جیاوازییەکە پیشان دەدات: ++checks تەنیا کاتێک جێبەجێ دەبێت کە لاکەی دەژمێردرێت، کە ئەمە :
public class AndVersusAmpersand {
public static void main(String[] args) {
int checks = 0;
boolean a = (5 > 10) && (++checks > 0);
System.out.println(a + ", checks = " + checks);
boolean b = (5 > 10) & (++checks > 0);
System.out.println(b + ", checks = " + checks);
boolean c = (5 < 10) || (++checks > 0);
System.out.println(c + ", checks = " + checks);
boolean e = (5 < 10) | (++checks > 0);
System.out.println(e + ", checks = " + checks);
}
}$ java AndVersusAmpersand false, checks = 0 false, checks = 1 true, checks = 1 true, checks = 2
So & is no guard: d != 0 & 10 / d > 1 still divides by zero and stops with ArithmeticException. Use && and || in conditions; & and | are mainly for bits (AND gate).
کەواتە & پاسەوان نییە: d != 0 & 10 / d > 1 هەر بەسەر سفردا دابەش دەکات و بە ArithmeticException دەوەستێت. لە && و || بەکار بهێنە؛ & و | زیاتر بۆ بیتن (گەیتی AND).
Turning a not around: De Morgan's lawsسەلمێنراوەکانی دی مۆرگان
A ! in front of brackets can be moved inside with : flip each part and swap && and ||. !(a && b) is !a || !b, and !(a || b) is !a && !b. A student must resit when it is not true that the mark is at least 50 and the attendance at least 75. Both forms agreed in all four runs:
!ـێک لە پێش کەوانەوە دەتوانرێت بە ببرێتە ناوەوە: هەر بەشێک پێچەوانە بکەرەوە و && و || ئاڵوگۆڕ بکە. !(a && b) دەبێتە !a || !b و !(a || b) دەبێتە !a && !b. قوتابییەک دەبێت دووپاتە تاقیکردنەوە بکات کاتێک ڕاست نییە کە نمرەکەی لانیکەم 50 و ئامادەبوونی لانیکەم 75 بێت. هەردوو شێوەکە لە هەر چوار جێبەجێکردنەکەدا وەک یەک بوون:
import java.util.Scanner;
public class Resit {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Mark and attendance: ");
int mark = input.nextInt();
int attendance = input.nextInt();
boolean resitA = !(mark >= 50 && attendance >= 75);
boolean resitB = mark < 50 || attendance < 75; // De Morgan
System.out.println(resitA + " " + resitB);
}
}$ java Resit Mark and attendance: 80 90 false false $ java Resit Mark and attendance: 80 60 true true $ java Resit Mark and attendance: 40 90 true true $ java Resit Mark and attendance: 40 60 true true
The second form reads like a sentence: the mark is low, or the attendance is low. Remember that the opposite of >= is <, not <=. The same laws are proved for gates in De Morgan in programs.
شێوەی دووەم وەک ڕستەیەک دەخوێنرێتەوە: نمرەکە کەمە، یان ئامادەبوون کەمە. لەبیرت بێت پێچەوانەی >= <ـە، نەک <=. هەمان یاساکان بۆ گەیتەکان لە دی مۆرگان لە بەرنامەکاندا دەسەلمێنرێن.
An if inside an ififـێک لەناو ifـێکی تردا
An if can stand inside the block of another if: a . There is an outer if and an inner if; the inner one is checked only when the outer condition is true. The inner if can hold another if, with no limit to the depth:
ifـێک دەتوانێت لەناو بلۆکی ifـێکی تردا بێت: . ifـێکی دەرەوە و ifـێکی ناوەوە هەیە؛ ناوەوەکە تەنیا کاتێک دەپشکنرێت کە دەرەوە ڕاست بێت. ifـی ناوەوە دەتوانێت ifـێکی تری تێدا بێت، بێ هیچ سنوورێک بۆ قووڵی:
if (condition1) {
// runs when condition1 is true
if (condition2) {
// runs when condition1 and condition2 are true
}
}public class BloodDonor {
public static void main(String[] args) {
int age = 20;
int weight = 80;
if (age >= 18) {
if (weight > 50) {
System.out.println("You are eligible to donate blood");
}
}
}
}$ java BloodDonor You are eligible to donate blood
Age 18 and weight over 50 kg is a simplified classroom rule: real blood-donation rules (age, weight, health) are set by each country's blood service.
تەمەنی 18 و کێشی زیاتر لە 50 کیلۆ یاسایەکی سادەکراوی پۆلە: یاسا ڕاستەقینەکانی خوێنبەخشین (تەمەن، کێش، تەندروستی) خزمەتگوزاریی خوێنی هەر وڵاتێک دایدەنێت.
An if inside an ififـێک لەناو ifـێکی تردا
An else at each levelelse لە هەر ئاستێکدا
With an else at both levels the program can say which check failed. Each else belongs to the if directly above it, at the same indentation:
بە elseـێک لە هەردوو ئاستدا دەتوانێت بڵێت کام پشکنین سەرنەکەوت. هەر elseـێک سەر بەو ifـەیە کە ڕاستەوخۆ لە سەرەوەیەتی، لە هەمان :
import java.util.Scanner;
public class DonorCheck {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Age: ");
int age = input.nextInt();
System.out.print("Weight in kg: ");
int weight = input.nextInt();
if (age >= 18) {
if (weight > 50) {
System.out.println("You can donate blood.");
} else {
System.out.println("Sorry: you must weigh more than 50 kg.");
}
} else {
System.out.println("Sorry: you must be 18 or older.");
}
}
}$ java DonorCheck Age: 20 Weight in kg: 80 You can donate blood. $ java DonorCheck Age: 20 Weight in kg: 45 Sorry: you must weigh more than 50 kg. $ java DonorCheck Age: 16 Weight in kg: 80 Sorry: you must be 18 or older.
An if inside an ififـێک لەناو ifـێکی تردا
Test the boundariesسنوورەکان تاقی بکەرەوە
This nested program sorts a whole number into three ranges. A first version printed i is greater than 30 for the input 30, although 30 is not greater than 30: the inner else really means 30 or more. With the messages corrected:
ئەم بە لە سێ مەودادا دادەنێت. وەشانێکی یەکەم بۆ 30 i is greater than 30ـی چاپ دەکرد، هەرچەندە 30 لە 30 گەورەتر نییە: elseـی ناوەوە لە ڕاستیدا واتە 30 یان زیاتر. بە پەیامە چاککراوەکان:
import java.util.Scanner;
public class RangeTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer number: ");
int i = input.nextInt();
if (i >= 20) {
if (i < 30)
System.out.println("i is from 20 to 29");
else
System.out.println("i is 30 or more");
} else
System.out.println("i is smaller than 20");
}
}$ java RangeTest Enter an integer number: 19 i is smaller than 20 $ java RangeTest Enter an integer number: 20 i is from 20 to 29 $ java RangeTest Enter an integer number: 29 i is from 20 to 29 $ java RangeTest Enter an integer number: 30 i is 30 or more
The first version's run for 30 printed:
جێبەجێکردنی وەشانی یەکەم بۆ 30 ئەمەی چاپ کرد:
$ java RangeTest Enter an integer number: 30 i is greater than 30
Mistakes like this hide at the boundaries, so test the values on both sides of every limit: here 19 and 20, 29 and 30 (Test with answers you know).
هەڵەی لەم جۆرە لە سنوورەکاندا خۆیان دەشارنەوە، بۆیە نرخەکانی هەردوو لای هەر سنوورێک تاقی بکەرەوە: لێرەدا 19 و 20، 29 و 30 (تاقیکردنەوە بە وەڵامی ناسراو).
An if inside an ififـێک لەناو ifـێکی تردا
Nested if or &&?ڕستەی ifـی ناوەکی یان &&؟
Two nested ifs without any else do the same job as one if with &&. With an else they no longer do: this else belongs to the outer if and runs when i > k is false. Both versions in one program:
دوو ifـی ناوەکی بەبێ هیچ elseـێک هەمان کاری یەک if بە && دەکەن. بە elseـێک ئیتر وا نییە: ئەم elseـە سەر بە ifـی دەرەوەیە و کاتێک i > k هەڵە بێت جێبەجێ دەبێت. هەردوو وەشان لە یەک :
import java.util.Scanner;
public class NestedOrAnd {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("i, j and k: ");
int i = input.nextInt();
int j = input.nextInt();
int k = input.nextInt();
System.out.print("Nested: ");
if (i > k) {
if (j > k)
System.out.print("i and j are greater than k");
} else
System.out.print("i is less than or equal to k");
System.out.println();
System.out.print("With &&: ");
if (i > k && j > k)
System.out.print("i and j are greater than k");
System.out.println();
}
}$ java NestedOrAnd i, j and k: 5 6 1 Nested: i and j are greater than k With &&: i and j are greater than k $ java NestedOrAnd i, j and k: 0 6 1 Nested: i is less than or equal to k With &&: $ java NestedOrAnd i, j and k: 5 0 1 Nested: With &&:
Many options: the else if ladderزۆر هەڵبژاردن: پەیژەی else if
When one value decides among several options, chain else if parts, each an . Java tests the conditions from the top down. As soon as one is true, its statement runs and the rest of the ladder is skipped; if none is true, the final else runs. Write every else if under the first if: indenting each one further, like a staircase, is the same code but harder to read.
کاتێک یەک لە نێوان چەند هەڵبژاردنێکدا بڕیار دەدات، بەشەکانی else if بە دوای یەکدا بنووسە، هەریەکەیان . Java لە سەرەوە بۆ خوارەوە دەپشکنێت. هەر کە یەکێکیان ڕاست بوو، جێبەجێ دەبێت و بەشەکانی تری پەیژەکە تێدەپەڕێنرێن؛ ئەگەر هیچیان ڕاست نەبوو، elseـی کۆتایی جێبەجێ دەبێت. هەموو else ifـێک لە ژێر یەکەم ifـدا بنووسە: بۆشایی زیاتر بۆ هەریەکەیان، وەک پلیکانە، هەمان کۆدە بەڵام خوێندنەوەی قورسترە.
public class MultiIf {
public static void main(String[] args) {
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}$ java MultiIf i is 20


When every test compares the same value with a fixed value, as here, the switch of the next lesson is often clearer.
کاتێک هەموو پشکنینەکان، وەک لێرە، هەمان لەگەڵ جێگیر بەراورد دەکەن، ڕستەی switchـی وانەی داهاتوو زۆرجار ڕوونترە.
Many options: the else if ladderزۆر هەڵبژاردن: پەیژەی else if
A grade ladderپەیژەی نمرە
A realistic ladder turns a mark from 0 to 100 into a grade, with the common bands 90, 80, 70, 60 and 50 (the pass mark is 50). The first test refuses marks outside 0 to 100 with ||:
پەیژەیەکی واقیعی نمرەیەک لە 0 تا 100 دەکات بە پلەیەک، بە ماوە باوەکانی 90، 80، 70، 60 و 50 (نمرەی دەرچوون 50ـە). یەکەم پشکنین بە || ئەو نمرانە ڕەت دەکاتەوە کە لە دەرەوەی 0 تا 100ن:
import java.util.Scanner;
public class Grade {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Mark (0-100): ");
int mark = input.nextInt();
if (mark < 0 || mark > 100) {
System.out.println("Invalid mark");
} else if (mark >= 90) {
System.out.println("Excellent");
} else if (mark >= 80) {
System.out.println("Very good");
} else if (mark >= 70) {
System.out.println("Good");
} else if (mark >= 60) {
System.out.println("Fair");
} else if (mark >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}$ java Grade Mark (0-100): 76 Good $ java Grade Mark (0-100): 50 Pass $ java Grade Mark (0-100): 49 Fail $ java Grade Mark (0-100): 101 Invalid mark
Each test needs only a lower limit: when mark >= 70 is reached, Java already knows the mark is below 80. The Python track builds the same idea (The grade decision).
هەر پشکنینێک تەنیا سنووری خوارەوەی پێویستە: کاتێک دەگاتە mark >= 70، Java پێشتر دەزانێت نمرەکە لە 80 کەمترە. ڕێڕەوی Python هەمان بیرۆکە دروست دەکات (بڕیاری نمرە).
Many options: the else if ladderزۆر هەڵبژاردن: پەیژەی else if
The order of the tests mattersڕیزبەندیی پشکنینەکان گرنگە
Because only the first true test runs, the order decides the answer. Here the tests are upside down:
چونکە تەنیا یەکەم پشکنینی ڕاست جێبەجێ دەبێت، ڕیزبەندییەکە وەڵامەکە دیاری دەکات. لێرەدا پشکنینەکان پێچەوانەن:
import java.util.Scanner;
public class GradeWrongOrder {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Mark (0-100): ");
int mark = input.nextInt();
if (mark >= 50) {
System.out.println("Pass");
} else if (mark >= 70) {
System.out.println("Good");
} else if (mark >= 90) {
System.out.println("Excellent");
} else {
System.out.println("Fail");
}
}
}$ java GradeWrongOrder Mark (0-100): 95 Pass $ java GradeWrongOrder Mark (0-100): 30 Fail
95 passes the first test, mark >= 50, so it never reaches the others: a with no message. With >= tests, start at the highest limit and go down (The order matters).
95 یەکەم پشکنین، mark >= 50، تێدەپەڕێنێت، بۆیە هەرگیز ناگاتە ئەوانی تر: بێ پەیام. بە پشکنینی >=، لە بەرزترین سنوورەوە دەست پێ بکە و دابەزە (ڕیزبەندی گرنگە).
Many options: the else if ladderزۆر هەڵبژاردن: پەیژەی else if
Nested ifs or a ladder?ڕستەکانی ifـی ناوەکی یان پەیژە؟
The same grades can be written with nested ifs: each else holds the next if. The results are the same (95 Excellent, 76 Good, 50 Pass, 49 Fail), but every level moves further right and the code grows to 23 lines. The ladder is the same logic written flat. Use nesting when the inner test is about something else, like the weight after the age.
هەمان پلەکان دەکرێت بە بنووسرێن: هەر elseـێک ifـی داهاتوو لەخۆ دەگرێت. ئەنجامەکان وەک یەکن (95 Excellent، 76 Good، 50 Pass، 49 Fail)، بەڵام هەر ئاستێک زیاتر بەرەو ڕاست دەچێت و کۆدەکە دەگاتە 23 دێڕ. پەیژەکە هەمان لۆجیکە بە ڕێکی نووسراو. ناوەکی بەکار بهێنە کاتێک پشکنینی ناوەوە لەبارەی شتێکی ترە، وەک کێش لە دوای تەمەن.
Which if owns the else?else هی کام ifـە؟
This code has two ifs and one else. The indentation suggests that the else belongs to the first if, but Java ignores indentation: an else always belongs to the nearest if above it, in the same block, that has no else yet. This is the problem. With i = 1, j = 2 and k = 3:
ئەم کۆدە دوو if و یەک elseـی هەیە. وا نیشان دەدات کە elseـەکە سەر بە یەکەم ifـە، بەڵام Java گوێ بە نادات: else هەمیشە سەر بە نزیکترین ifـە لە سەرووییەوە، لە هەمان بلۆکدا، کە هێشتا elseـی نییە. ئەمە کێشەی . کاتێک i = 1، j = 2 و k = 3:
public class DanglingElse {
public static void main(String[] args) {
int i = 1, j = 2, k = 3;
if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");
System.out.println("end");
}
}$ java DanglingElse end $ javac -Xlint:all DanglingElse.java
i > j (1 > 2) is false, so the whole inner if … else is skipped and only end appears; javac -Xlint:all gives no warning at all. To give the else to the outer if, put braces around the inner if:
i > j (1 > 2) هەڵەیە، بۆیە هەموو if … elseـی ناوەوە تێدەپەڕێنرێت و تەنیا end دەردەکەوێت؛ javac -Xlint:all هیچ نادات. بۆ دانی elseـەکە بە ifـی دەرەوە، کەوانە بە دەوری ifـی ناوەوەدا دابنێ:
public class DanglingFixed {
public static void main(String[] args) {
int i = 1, j = 2, k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
} else
System.out.println("B");
System.out.println("end");
}
}$ java DanglingFixed B end
Do not repeat code in both branchesهەمان کۆد لە هەردوو لقدا دووپاتە مەکەرەوە
Some buildings have no 13th floor: the lift buttons jump from 12 to 14, so above 12 a button shows one more than the real floor. This program prints the actual floor, but the same println appears in both branches:
هەندێک باڵەخانە نهۆمی 13یان نییە: دوگمەکانی ئاسانسۆرەکە لە 12ەوە بازدەدەن بۆ 14، بۆیە لە سەرووی 12ەوە دوگمەیەک یەک زیاتر لە نهۆمی ڕاستەقینە پیشان دەدات. ئەم نهۆمی ڕاستەقینە چاپ دەکات، بەڵام هەمان println لە هەردوو لقدا هەیە:
import java.util.Scanner;
public class ActualFloor {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Floor button: ");
int floor = input.nextInt();
int actualFloor;
if (floor > 13) {
actualFloor = floor - 1;
System.out.println("Actual floor: " + actualFloor);
} else {
actualFloor = floor;
System.out.println("Actual floor: " + actualFloor);
}
}
}$ java ActualFloor Floor button: 10 Actual floor: 10 $ java ActualFloor Floor button: 20 Actual floor: 19
Code that is the same in every case belongs after the if … else, in one place. Then a change to the message is made once, not twice:
ئەو کۆدەی لە هەموو حاڵەتێکدا وەک یەکە، لە دوای if … else دێت، لە یەک شوێندا. ئەوسا گۆڕینی پەیامەکە یەک جار دەکرێت، نەک دوو جار:
import java.util.Scanner;
public class ActualFloor {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Floor button: ");
int floor = input.nextInt();
int actualFloor;
if (floor > 13) {
actualFloor = floor - 1;
} else {
actualFloor = floor;
}
System.out.println("Actual floor: " + actualFloor);
}
}$ java ActualFloor Floor button: 10 Actual floor: 10 $ java ActualFloor Floor button: 20 Actual floor: 19 $ java ActualFloor Floor button: 14 Actual floor: 13
Choosing a value in one line: ?:هەڵبژاردنی نرخێک لە یەک دێڕدا: ?:
When an if … else only chooses between two values, the conditional operator is shorter: condition ? valueIfTrue : valueIfFalse. It has three operands, so it is also called the . Only the chosen value is worked out, so d != 0 ? 100 / d : 0 is safe:
کاتێک if … elseـێک تەنیا لە نێوان دوو هەڵدەبژێرێت، کورتترە: condition ? valueIfTrue : valueIfFalse. سێ هەیە، بۆیە پێی دەوترێت . تەنیا دەژمێردرێت، بۆیە d != 0 ? 100 / d : 0 سەلامەتە:
public class Ternary {
public static void main(String[] args) {
int mark = 72;
String result = mark >= 50 ? "Pass" : "Fail";
System.out.println(result);
int a = 8, b = 13;
int larger = a > b ? a : b;
System.out.println("Larger: " + larger);
int messages = 1;
System.out.println("You have " + messages + (messages == 1 ? " message" : " messages"));
int d = 0;
int share = d != 0 ? 100 / d : 0; // 100 / d is not worked out
System.out.println("Share: " + share);
}
}$ java Ternary Pass Larger: 13 You have 1 message Share: 0
?: groups from right to left, so n > 0 ? "positive" : n < 0 ? "negative" : "zero" chooses among three (for n = -4 it gives negative); use that only for short choices. ?: is an expression, not a statement: written alone, mark >= 50 ? System.out.println("Pass") : … gives not a statement, as A value nobody uses explains. Python writes a if condition else b (Choosing a value in one line).
?: لە ڕاستەوە بۆ چەپ گرووپ دەبێت، بۆیە n > 0 ? "positive" : n < 0 ? "negative" : "zero" لە نێوان سێدا هەڵدەبژێرێت (بۆ n = -4 negative دەدات)؛ تەنیا بۆ هەڵبژاردنی کورت بەکاری بهێنە. ?: ، نەک : بە تەنیا نووسراو، mark >= 50 ? System.out.println("Pass") : … not a statement دەدات، وەک لە نرخێک کە کەس بەکاری ناهێنێتـدا ڕوون کراوەتەوە. Python دەنووسێت a if condition else b (هەڵبژاردنی نرخ لە یەک دێڕدا).
Common mistakesهەڵە باوەکان
| You wroteنووسیت | javac or the run saysjavac یان جێبەجێکردن دەڵێت | Fixچارەسەر |
|---|---|---|
if (a && b) // ints | bad operand types for binary operator '&&' | Compare: a != 0 && b != 0بەراورد بکە: a != 0 && b != 0 |
18 <= age <= 65 | bad operand types for binary operator '<=' | age >= 18 && age <= 65 |
day == 5 || 6 | bad operand types for binary operator '||' | day == 5 || day == 6 |
!x == 5 | bad operand type int for unary operator '!' | x != 5 or !(x == 5)x != 5 یان !(x == 5) |
10 / d > 1 && d != 0 | ArithmeticException: / by zero | The guard first: d != 0 && …سەرەتا پاسەوانەکە: d != 0 && … |
d != 0 & 10 / d > 1 | ArithmeticException: / by zero | &&, not &&&، نەک & |
>= 50 first in a grade ladder>= 50 یەکەم لە پەیژەی نمرەدا | 95 gives Pass, no message95 Pass دەدات، بێ پەیام | Highest limit first.سەرەتا بەرزترین سنوور. |
else under two ifs without braceselse لە ژێر دوو ifـدا بەبێ کەوانە | it belongs to the inner ifسەر بە ifـی ناوەوەیە | Braces around the inner if.کەوانە بە دەوری ifـی ناوەوەدا. |
nested ifs with an else → &&ifـی ناوەکی بە else ← && | a different program جیاواز | Keep the nesting, or keep the else.ناوەکییەکە بهێڵەوە، یان elseـەکە. |
mark >= 50 ? System.out.println("Pass") : …; | not a statement | if … else, or print the result of ?:if … else، یان ئەنجامی ?: چاپ بکە |
The real messages of four of them: three from javac, the last one at run time:
پەیامە ڕاستەقینەکانی چواریان: سێیان لە javacـەوە و دوایینیان لە کاتی جێبەجێکردندا:
$ javac Weekend.java
Weekend.java:4: error: bad operand types for binary operator '||'
if (day == 5 || 6) {
^
first type: boolean
second type: int
1 error
$ javac NotFirst.java
NotFirst.java:4: error: bad operand type int for unary operator '!'
if (!x == 5) {
^
1 error
$ javac TernaryStatement.java
TernaryStatement.java:4: error: not a statement
mark >= 50 ? System.out.println("Pass") : System.out.println("Fail");
^
1 error
$ java AmpersandGuard
Exception in thread "main" java.lang.ArithmeticException: / by zero
at AmpersandGuard.main(AmpersandGuard.java:4)Practiceڕاهێنان
A year is a leap year if it is divisible by 4 but not by 100, or if it is divisible by 400. Read a year and say whether it is a leap year. Test 2024, 1900, 2000 and 2026.
ساڵێک کەبیسەیە ئەگەر بەسەر 4دا دابەش ببێت بەڵام بەسەر 100دا نا، یان ئەگەر بەسەر 400دا دابەش ببێت. ساڵێک بخوێنەوە و بڵێ کەبیسەیە یان نا. 2024، 1900، 2000 و 2026 تاقی بکەرەوە.
Show answerوەڵامەکە پیشان بدە
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Year: ");
int year = input.nextInt();
boolean leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
System.out.println(year + (leap ? " is a leap year" : " is not a leap year"));
}
}$ java LeapYear Year: 2024 2024 is a leap year $ java LeapYear Year: 1900 1900 is not a leap year $ java LeapYear Year: 2000 2000 is a leap year $ java LeapYear Year: 2026 2026 is not a leap year
1900 is divisible by 100 but not by 400, so it is not a leap year; 2000 is.
1900 بەسەر 100دا دابەش دەبێت بەڵام بەسەر 400دا نا، بۆیە کەبیسە نییە؛ 2000 کەبیسەیە.
Three sides make a triangle only if each pair together is longer than the third side. Read three sides and decide.
سێ لا تەنیا کاتێک سێگۆشەیەک دروست دەکەن کە هەر دوو لایەک پێکەوە لە لای سێیەم درێژتر بن. سێ لا بخوێنەوە و بڕیار بدە.
Show answerوەڵامەکە پیشان بدە
import java.util.Scanner;
public class Triangle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Three sides: ");
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
if (a + b > c && a + c > b && b + c > a) {
System.out.println("These sides make a triangle.");
} else {
System.out.println("No triangle.");
}
}
}$ java Triangle Three sides: 3 4 5 These sides make a triangle. $ java Triangle Three sides: 1 2 3 No triangle.
1 + 2 is not longer than 3, so 1, 2 and 3 lie on one line (Triangle inequality).
1 + 2 لە 3 درێژتر نییە، بۆیە 1، 2 و 3 لەسەر یەک هێڵ دەکەون (لاسەنگەی سێگۆشەیی).
Children under 6 enter free; under 18 or 60 and over pay 1,000 dinars; everyone else pays 2,000. Use an else if ladder with ||.
منداڵی خوار 6 ساڵ بێبەرانبەر دەچنە ژوورەوە؛ خوار 18 یان 60 و سەرووتر 1,000 دینار دەدەن؛ هەموو کەسێکی تر 2,000 دەدات. پەیژەیەکی else if بە || بەکار بهێنە.
Show answerوەڵامەکە پیشان بدە
import java.util.Scanner;
public class Museum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Age: ");
int age = input.nextInt();
if (age < 6) {
System.out.println("Free");
} else if (age < 18 || age >= 60) {
System.out.println("1,000 dinars");
} else {
System.out.println("2,000 dinars");
}
}
}$ java Museum Age: 4 Free $ java Museum Age: 12 1,000 dinars $ java Museum Age: 30 2,000 dinars $ java Museum Age: 65 1,000 dinars
The first test catches the youngest children, so age < 18 in the second test only meets ages 6 to 17.
یەکەم پشکنین بچووکترین منداڵان دەگرێت، بۆیە age < 18 لە پشکنینی دووەمدا تەنیا تەمەنی 6 تا 17 دەبینێت.
Rewrite with one if and &&: if (temperature > 20) { if (!raining) { System.out.println("Picnic!"); } }
بە یەک if و && دووپاتە بینووسەوە: if (temperature > 20) { if (!raining) { System.out.println("Picnic!"); } }
Show answerوەڵامەکە پیشان بدە
public class Picnic {
public static void main(String[] args) {
int temperature = 24;
boolean raining = false;
if (temperature > 20 && !raining) {
System.out.println("Picnic!");
}
}
}$ java Picnic Picnic!
Neither if has an else, so && keeps the meaning.
هیچ کام لە دوو ifـەکە elseـی نییە، بۆیە && واتاکە دەپارێزێت.
What does this print?
ئەمە چی چاپ دەکات؟
int x = 5, y = 1;
if (x > 3)
if (y > 3)
System.out.println("both are big");
else
System.out.println("x is small");
System.out.println("end");Show answerوەڵامەکە پیشان بدە
public class PredictElse {
public static void main(String[] args) {
int x = 5, y = 1;
if (x > 3)
if (y > 3)
System.out.println("both are big");
else
System.out.println("x is small");
System.out.println("end");
}
}$ java PredictElse x is small end
x > 3 is true, so the inner if (y > 3) is tested; it is false, and the else, which belongs to it, prints x is small, a misleading message.
x > 3 ڕاستە، بۆیە if (y > 3)ـی ناوەوە دەپشکنرێت؛ هەڵەیە و ئەو elseـەی سەر بەوە x is small چاپ دەکات، کە پەیامێکی هەڵخەڵەتێنەرە.
Read three whole numbers and print the largest, once with two ifs and once with ?:.
سێ بخوێنەوە و گەورەترینیان چاپ بکە، جارێک بە دوو if و جارێک بە ?:.
Show answerوەڵامەکە پیشان بدە
import java.util.Scanner;
public class LargestOfThree {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Three whole numbers: ");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
int largest = a;
if (b > largest) {
largest = b;
}
if (c > largest) {
largest = c;
}
System.out.println("Largest: " + largest);
int largest2 = a >= b && a >= c ? a : b >= c ? b : c;
System.out.println("With ?: " + largest2);
}
}$ java LargestOfThree Three whole numbers: 7 19 4 Largest: 19 With ?: 19 $ java LargestOfThree Three whole numbers: 8 8 3 Largest: 8 With ?: 8 $ java LargestOfThree Three whole numbers: 2 5 9 Largest: 9 With ?: 9
Test ties (8 8 3) and the largest in each position. Compare Largest of three.
یەکسانبوون (8 8 3) و گەورەترین لە هەر شوێنێکدا تاقی بکەرەوە. بەراوردی بکە بە گەورەترینی سێ ژمارە.
Write the grade program with nested ifs instead of else if, and check that it gives the same grades.
نمرە بە لە جیاتی else if بنووسە و دڵنیا بە کە هەمان پلەکان دەدات.
Show answerوەڵامەکە پیشان بدە
import java.util.Scanner;
public class GradeNested {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Mark (0-100): ");
int mark = input.nextInt();
if (mark >= 90) {
System.out.println("Excellent");
} else {
if (mark >= 80) {
System.out.println("Very good");
} else {
if (mark >= 70) {
System.out.println("Good");
} else {
if (mark >= 60) {
System.out.println("Fair");
} else {
if (mark >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}
}
}
}
}$ java GradeNested Mark (0-100): 95 Excellent $ java GradeNested Mark (0-100): 76 Good $ java GradeNested Mark (0-100): 50 Pass $ java GradeNested Mark (0-100): 49 Fail
Same results, but 23 lines that drift right: the ladder is easier to read.
هەمان ئەنجام، بەڵام 23 دێڕ کە بەرەو ڕاست دەڕۆن: پەیژەکە ئاسانتر دەخوێنرێتەوە.
Summaryکورتە
&&is true when both sides are true,||when at least one is,!flips a boolean. Operands must be booleans.&&and||short-circuit: put the guard on the left.&and|always evaluate both sides.- De Morgan:
!(a && b)is!a || !b;!(a || b)is!a && !b. - A nested if asks the inner question only when the outer one is true;
&&replaces it only withoutelse. - An
else ifladder: the first true test wins; order the tests, and test the boundaries. - An
elsebelongs to the nearest unmatchedif; braces decide.?:chooses one of two values.
&&ڕاستە کاتێک هەردوو لا ڕاست بن،||کاتێک لانیکەم یەکێکیان،!پێچەوانە دەکاتەوە. دەبێت بن.&&و||کورتبڕن: پاسەوانەکە بخە لای چەپ.&و|هەمیشە هەردوو لا دەژمێرن.- دی مۆرگان:
!(a && b)دەبێتە!a || !b؛!(a || b)دەبێتە!a && !b. - پرسیاری ناوەوە تەنیا کاتێک دەکات کە دەرەوەکە ڕاست بێت؛
&&تەنیا بەبێelseجێگەی دەگرێتەوە. - پەیژەی
else if: یەکەم پشکنینی ڕاست دەیباتەوە؛ پشکنینەکان ڕیز بکە و سنوورەکان تاقی بکەرەوە. elseسەر بە نزیکترینifـی بێelseـە؛ کەوانەکان بڕیار دەدەن.?:یەکێک لە دوو هەڵدەبژێرێت.
Why is d != 0 && 10 / d > 1 safe when d is 0?بۆچی d != 0 && 10 / d > 1 سەلامەتە کاتێک d سفرە؟
The left side is false, so && never evaluates the division.
لای چەپ هەڵەیە، بۆیە && هەرگیز دابەشکردنەکە ناژمێرێت.
What does if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); print for i = 1, j = 2, k = 3?if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); بۆ i = 1، j = 2، k = 3 چی چاپ دەکات؟
Nothing: the else belongs to the inner if, which is never reached.
هیچ: elseـەکە سەر بە ifـی ناوەوەیە، کە هەرگیز پێی ناگات.
Write !(mark >= 50 && attendance >= 75) without the !.!(mark >= 50 && attendance >= 75) بەبێ ! بنووسە.
mark < 50 || attendance < 75.
mark < 50 || attendance < 75.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
The switch Statementڕستەی switch
Related lecturesوانە پەیوەندیدارەکان
- The AND Gateگەیتی AND
- The OR Gateگەیتی OR
- Logic Gates, Truth Tables and the NOT Gateگەیتە لۆجیکییەکان، خشتەکانی ڕاستی و گەیتی NOT
- The 12 Rules of Boolean Algebraدوازدە یاساکەی جەبری بوول
- De Morgan's Theoremsسەلمێنراوەکانی دی مۆرگان
- Logic Symbols and Boolean Algebraهێماکانی لۆجیک و جەبری بوول
- Logical Operators and Nested ifکارپێکەرە لۆجیکییەکان و ڕستەی ifـی ناوەکی
- The switch Statementڕستەی switch
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- W3Schools: Java Logical Operators
- W3Schools: Java Logical Operators in Conditions
- W3Schools: Java Else If
- W3Schools: Java Nested If
- W3Schools: Java Short Hand If … Else (ternary operator)
- The Java Tutorials: Equality, Relational, and Conditional Operators
- The Java Tutorials: The if-then and if-then-else Statements
- Java Language Specification (Java SE 17), §15.22.2–§15.25: &, |, ^, &&, || and ?:
- Java Language Specification (Java SE 17), §14.5: the dangling else
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.