The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes ?: operator Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "?: operator" Watch "?: operator" New topic
Author

?: operator

anchal jain
Greenhorn

Joined: May 03, 2007
Posts: 6
try this:
byte b=true?1:12345; //OK
b=false?1:12345; //Error at compiling
Look at JLS Chapter 15 about ?:, and my understanding
is neither of above should pass compiling.
It's a bug or something else?
MahaAdd
Greenhorn

Joined: Aug 28, 2000
Posts: 28
Hi,
the 2nd statement doesn't compile because when false it assigns a number 12345, which is out of the range for a byte ( -128 to 127 ).
the 1st statement compiles because when true it assigns 1 to b.(where the value is within the byte range)

and a boolean value can be assigned to a byte...both are 8 bits long.
Originally posted by learner:
try this:
byte b=true?1:12345; //OK
b=false?1:12345; //Error at compiling
Look at JLS Chapter 15 about ?:, and my understanding
is neither of above should pass compiling.
It's a bug or something else?

Ada Wang
Greenhorn

Joined: Aug 28, 2000
Posts: 23
My personal understanding is: the statement (a = x ? b : c) is directly equivalent to the textually longer version:
1. if (x) {
2. a=b;
3. }
4. else {
5. a=c;
6. }

For your case, (bype b = true ? 1 : 12345) is equivalent to :
if true {
bype b=1;}
else {
bype b=12345;
}
Hopefully, I answered your question.
Ada
 
IntelliJ Java IDE
 
subject: ?: operator
 
Threads others viewed
?: operator
IO question
Formating with printf() and format()
IO question
Formatting numbers for output (format and printf) was (regex)
IntelliJ Java IDE