Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

System.out.prinln ...

 
sean cee
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I got an interesting Q for you ...
int y = 4;
System.out.println("Value is "+((y >4 )? 99.99:9));
this will print 9.0.
whereas
System.out.println("Value is "+((y >4 )? 99:9));
will print 9.
Why is this?
 
Harpal Singh
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by sean cee:
Hi,
I got an interesting Q for you ...
int y = 4;
System.out.println("Value is "+((y >4 )? 99.99:9));
this will print 9.0.
whereas
System.out.println("Value is "+((y >4 )? 99:9));
will print 9.
Why is this?

Sean,
That is an intresting observation....what happens is when even one of the variables is double the other gets converted to double automatically.....in the first case 9 is getting promoted to double...coz the other condition variable is of type double...for eg:
int y = 3;
System.out.println("Value is "+((y <4 )? 99:9.5));
The result will be 99.0.......
Correct me someone if I am wrong....
Thanks,
Harpal
 
Randall Twede
Ranch Hand
Posts: 4369
3
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That looks right to me. I guess because ? returns a value it has to return the same type either way and it has to choose the wider type.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic