+ 2

Can any one please explain me the meaning of 4th and 5th line. That- Question mark and colon ?

public class Program { public static void main(String [ ] args) { boolean b = 20%10 == 1; int i = b? 5: 2; System.out.print(i); } }

6th May 2020, 8:26 AM
NIKHIL JOSHI
NIKHIL JOSHI - avatar
6 Answers
+ 3
NIKHIL JOSHI Sure here is the explanation : '%' is used to find the remainder after division. So, when you divide 20 by 10 you get 2 as the result and 0 as the remainder. Like : 10)20(2 20 ------- 0 And then we are saying 20%10 == 1. It is false, because 20%10 is 0. And 0 is not equal to 1. Therefore, boolean b = false; Now, int i = b ? 5 : 2; It is a fancy way to write if-else statement. For example, the equivalent code is : if (b == true) { i = 5; } else { i = 2; } As our b is false, the value of 'i' will be 2. Therefore the answer is 2!
6th May 2020, 8:31 AM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
+ 2
Boolean stores True or False value and 20%10 results in 0 and 0==1 is False so b is False now and That's ternary operator ? If the condition is true 5 will be the answer otherwise 2 Since b is False the answer will be 2
6th May 2020, 8:33 AM
Abhay
Abhay - avatar
+ 1
NIKHIL JOSHI ? with : is called as Ternary operator which is a short form of if else. For example 10 > 5 ? true : false here 10 > 5 is true so it will print the value before : else will print the value after : we can write this using if else also: if(10 > 5) { //true; } else { //false; }
6th May 2020, 8:35 AM
A͢J
A͢J - avatar
8th May 2020, 9:14 AM
NIKHIL JOSHI
NIKHIL JOSHI - avatar