• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Ternary Operator?

 
Kasak Tahilramani
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1:

// Source

public class ObjectTest {

public static void main(String[] args) {
byte b = 0;
(true) ? b = b + 1 : b = 100;// at this line it is giving error why?

System.out.println("Output: " + b);
}
}

Please explain what can I do to make it compilable???
 
Anton Uwe
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about this?
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
De compilable code is

public class ObjectTest {

public static void main(String[] args) {
byte b = 0;
b = (true) ? (byte)(b + 1) : 100;

System.out.println("Output: " + b);
}
}

The ternary operation assigns a value to a variable depending on the conditional expression

x = (boolean expression) ? value to assign if true : value to assign if false

You have also to cast the value if true (b+1) because of a possible loss of precision error. You could count 128 + 1.
 
Sanjit Kumar
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,

Hello Mr. Kasak Tahilramani First thing is that the following expression (true) ? b = b + 1 : b = 100; is not correct.
There are following mistakes in the above expression.
1> The compiler treats the above expression as
((true) ? b = b+1 : b) = 100; // line

Note: Expressions are evaluated from left to right and assignments are made from right to left.
In assignment expression, values are always assigned to a variable i.e. laft hand side must be a variable that's why the above code is wrong.
2> Now if we change the code as follows:
(true) ? b = b+1 : (b = 100) ;
Again this is wrong as values must be assigned to a variable.

3> Now Mr Anton Uwe has changed the code as follows
int vv;
vv=(true) ? (b = b + 1) : (b = 100);

The above code will still generate error.
The problem is in int he expression
b = b + 1;


Here b is byte , when b+1 is executed the result converted to int type and int value can not be assigned to a byte as there is a loss of precision so we need explicit type casting.

so the expression:
vv=(true) ? (b = (byte)(b + 1)) : (b = 100);
or
vv=(true) ? b = (byte)(b + 1) : (b = 100);
are correct now.
 
Kasak Tahilramani
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Sanjit-

It is Miss Kasak Tahilramani NOT Mr Kasak Tahilramani....

Thanks a lot for the explanation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic