Java Reference
In-Depth Information
The value of all integral types ( int , long , byte , short , char ) and float can be assigned to a variable of the double
data type without using an explicit cast.
int num1 = 15000;
double salary = num1; // Ok. int to double assignment
salary = 12455; // Ok. int literal to double
double bigNum = Double.MAX_VALUE; // Assigns the maximum double value
bigNum = 1226L; // Ok, long literal to double
double justAChar = 'A'; // Ok. Assigns 65.0 to justAChar
// Ok. Assigns positive infinity to dInf variable
double dInf = Double.POSITIVE_INFINITY;
// Ok. Assigns Not-a-Number to dNan variable
double dNan = Double.NaN;
// A compile-time error. Cannot assign a double literal to a double variable
// greater than the maximum value of double (1.7E308 approx)
double dTooBig = 1.8E308;
// A compile-time error. Cannot assign a double literal to a double variable
// less than the minimum value (greater than zero) of double 4.9E-324
double dTooSmall = 4.9E-325;
A double value must be cast to the integral type before it is assigned to a variable of any integral data type
( int , long , byte , short , or char ).
int num1 = 10;
double salary = 10.0;
num1 = salary; // A compile-time error. Cannot assign double to int
num1 = (int)salary; // Now Ok.
Underscores in Numeric Literals
Beginning with Java 7, you can use any number of underscores between two digits in numeric literals. For example,
an int literal 1969 can be written as 1_969 , 19_69 , 196_9 , 1___969 , or any other forms using underscores between
two digits. The use of underscores is also allowed in octal, hexadecimal, and binary formats. Big numbers are harder
to read without any punctuation marks (e.g., a comma as a thousand-separator). Use of underscores in big numbers
makes them easier to read. The following examples show the valid uses of underscores in numeric literals:
int x1 = 1_969; // Underscore in deciaml format
int x2 = 1__969; // Multiple consecutive underscores
int x3 = 03_661; // Underscore in octal literal
int x4 = 0b0111_1011_0001; // Underscore in binary literal
int x5 = 0x7_B_1; // Underscores in hexadecimal literal
byte b1 = 1_2_7; // Underscores in decimal format
double d1 = 1_969.09_19; // Underscores in double literal
Underscores are allowed in numeric literals only between digits. This means that you cannot use underscores in
the beginning or end of a numeric literal. You cannot use underscores with prefixes such as 0x for hexadecimal format
 
Search WWH ::




Custom Search