-3
   public class Second {

   public static void main(String[] args) {


    System.out.println(1>2?22:43);
    int a,b;
    a=11;
    b=(a==116)?22:33;
    System.out.println(b);

}

}

I am java beginner i am having hard time on understanding this code it does prints 22 but i'm not getting the logic behind it and what are these called if i have to know more about them.

Are there any similar types of logic that i should keep my eye any suggestions will help.Thank you !!

Saurav
  • 1
  • 3

2 Answers2

1

This 1>2?22:43 is equivalent to

if (1>2) then return 22 else return 43
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

That code is using the ternary operator to assign a variable based on a boolean expression. The ternary operator is a simple inline form of Java if-else statement. Here is the structure of ternary operator.

<boolean expression> ? <value if true> : <value if false>

Now, let us look at your code:

System.out.println(1>2 ? 22 : 43);

That line will print out 43 because the boolean expression 1>2 is false.

Then, look at this part:

int a,b;
a = 11;
b = (a==116) ? 22 : 33;
System.out.println(b);

That code will print out 33 because the boolean expression 11==116 is false.

So, the final output of that code is not 22. Here is the final output:

43
33