How do you read this syntax?
Hi everyone,
I am preparing for a Java exam at the moment and I came across the following syntax and don't understand how to read it or what exactly it does:
the whole code block where this is in is as follows:
Code Java:
int i, j=1;
i = (j>1)?2:1;
switch(i){
case 0: System.out.println(0); break;
case 1: System.out.println(1);
case 2: System.out.println(2); break;
case 3: System.out.println(3); break;
}
The print out from this is
1
2
Re: How do you read this syntax?
Please remember to include code tags.
Code:
Code java:
int i, j=1;
i = (j>1)?2:1;
switch(i){
case 0: System.out.println(0); break;
case 1: System.out.println(1);
case 2: System.out.println(2); break;
case 3: System.out.println(3); break;
}
Is there supposed to be a break statement after case 1: System.out.println(1);?
I'm not sure how to read i = (j>1)?2:1, so I'm curious what the answer is too.
But, if I had to take a guess, I would say this:
the statement (j>1) is a boolean, which would result in false since j==1.
the ? character probably indicates a decision for the value of the int based on the preceding boolean.
the statement 2:1 probably gives options based on the boolean result, where before the colon is the true value and after the colon is the false value.
Which means that i = (j>1)?2:1 will make i==1, which would work with your switch statement. Then, since case 1: System.out.println(1); doesnt include a break statement, it goes to the next switch statement afterwards, which is case 2: System.out.println(2); break;, which would give the printout:
If I'm right, then that is some damn good guessing. If I'm wrong, I think I did a good job justifying it.
Re: How do you read this syntax?
It seem silly to argue about what some lines of code do when you can compile and execute them to see.
If more info is needed, add println()s to show the values of variables as they change and to show execution flow.
Re: How do you read this syntax?
...is a shorthand way of writing if/else (aka ternary operator). If the condition on the left evaluates to true, it returns the value after the question mark, if false it returns the value after the colon.
Re: How do you read this syntax?
Hi,
thanks to everyone for your very helpful comments.
I hadn't seen this kind of notation before but it appeared in a practice test.
Many thanks!!
Re: How do you read this syntax?
Quote:
Originally Posted by
copeg
...is a shorthand way of writing if/else (aka ternary operator). If the condition on the left evaluates to true, it returns the value after the question mark, if false it returns the value after the colon.
I'm a little proud of myself now.