numeric literals that include comma, beware of this
Gurpreet Singh
Ranch Hand
Joined: Oct 05, 2004
Posts: 34
posted
0
This is for all who are still prepareing for SCJP : We all know that integer literals that include comma won't compile in java, but look at the following code.
class Test { public static void main(String[] args) { int f = 0x20,df; System.out.println(f); } }
It WILL compile.
You know why?? Because, first the literal is a hexadecimal one, which is valid. Second d and f are also valid in hexadecimal. BUT, and this is the tricky one, here df is another variable and not a constant (which can go along with 0x20 as 0x20df). Got it. I guess so.
Louie van Bommel
Ranch Hand
Joined: Aug 17, 2004
Posts: 76
posted
0
int f = 0x20,df;
That's kinda kewl. It took me awhile to digest it until I realized it was like: int f = 0x20; int df;
A very similar (but much less confusing) example is
Which is creating two variables x and y, but initializing x.
Tx for the tip
Gurpreet Singh
Ranch Hand
Joined: Oct 05, 2004
Posts: 34
posted
0
The point here is, that integer literals generally don't include commas. But when used like given above, they surely can include comma, but that comma will not be a part of the literal. It will indicate a new variable of int.
Sounds like a Paradox.
It is
Joe Borderi
Ranch Hand
Joined: Oct 23, 2004
Posts: 151
posted
0
You can get part way to resolving your paradox by realizing that the , is used as a seperator in Java. Coming from C++ (where the , is also an operator) I had to stumble through this.
In Java, the following won't compile:
In C++, the code prints 10 times because operator,() evaluates to its right-most expression.
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
posted
0
Originally posted by Gurpreet Singh: The point here is, that integer literals generally don't include commas. But when used like given above, they surely can include comma, but that comma will not be a part of the literal. It will indicate a new variable of int.
Sounds like a Paradox.
It is
The "paradox" is only in the way you describe this. When I read int f = 0x20,df; I saw the comma and said this is a definitioon of two variables. One is explicitly initialized, the other not. The comma is in no way a hexadecimal digit (0123456789ABCDEF) so how can it be ever thought to be part of the literal?