Reputation: 467
I was basically playing with data types in order to learn java and here is what i am confused about.
double douVar = 30000000000.323262342134353;
int intVar = (int)douVar; // casting
System.out.println(intVar);
Now converting the douVar
to string i overwrite the double
variable:
douVar = 345839052304598; // returns an error: Integer number too long
System.out.println(Double.toString(douVar));
complete error:
Error:(20, 18) java: integer number too large: 345839052304598
I'm using IntellijIDEA compiler. I didnt try this over eclipse though but i assume the compiler would not be so different. Does this mean that casting would result in modifying the original variable as well?
Upvotes: 0
Views: 838
Reputation: 2729
Java interprets 345839052304598
as an integer.
In Java an Integer is 4 bytes long and therefore has a value range from –2 147 483 648
to 2 147 483 647
. (your number is obviously not in that range)
To make Java treat the number as a double, you must write:
double d = 345839052304598D;
/* or */
double d1 = 345839052304598.0;
(Same goes for a long
, you have to write L
instead of D
in that case)
Upvotes: 5
Reputation: 5712
When you declare number as 345839052304598 compiler tries to read it as a 32 bit integer. But since this exceed the range of int compiler throws the error. You can use d, D or L suffix or add decimal place like .0 to to handle this,
Upvotes: 2
Reputation: 6306
In Java, constant numbers without a decimal are ints by default. There are 2 ways to change the constant definition to a double:
d
or D
at the end..0
at the enddouVar = 345839052304598d;
douVar = 345839052304598.0;
Upvotes: 5
Reputation: 395
Just change douVar = 345839052304598;
to douVar = 345839052304598.00;
Upvotes: 1
Reputation: 5868
The literal 345839052304598 will be considered as an integer
by the compiler
, since this value is to large for an integer, a compile time error is thrown. Therefore you need to tell the compiler that the value you want to use is actually double value, that you can do the following way:
douVar =345839052304598D; // note D at the end which tells comipler that it is double
Upvotes: 3