Declare Double as int compile, not compile, but looks the same

(note: Double example)

When initializing Double, a value of Double or double is required as:

Double a = 0; //does not compile

if you do not press twice, or add 'd'

Double b = (double)0; //compiles
Double c = 0d; //compiles

When it becomes confusing, it ...
It compiles, although its value becomes 0 (int)

Double d = true ? 0 : 0d; //compiles, but always 0 (eclipse 'complains' on 0d calling it *Dead code*. So it knows it will return 0

How does it

Double e = false ? 0 : 0d; //compiles, always 0d

But they will not compile:

Double f = false ? 0 : 0; //cannot convert from int to Double
Double g = true ? 0 : 0; //cannot convert from int to Double

Why is this given an error for f and g, but not for d

ps. Using Java8 (don't expect the difference, but updates are happening)

+4
source share
2 answers

, Java ( §15.25), , ( §5.6.2):

(§5.1.2) , :

& emsp; double, double.

, double , .

:

Double e = false ? 0 : 0d; 
Double a = true ? 0 : 0d;

double - , :

Double f = false ? 0 : 0;

, condition ? 0 : 0 , §15.25 , :

( ), .

. , , , §5.6.2-1:

class Test {
    public static void main(String[] args) {
        int i = 0;
        float f = 1.0f;

        // Omitted code...

        // Here int:float is promoted to float:float:
        f = (b==0) ? i : 4.0f;
        System.out.println(1.0/f);
    }
}

, , ( vs) , :

int n = true ? 0 : 0d; // Cannot assign a double to an int
+5

, . int double, int double *, .

,

Double d = true ? 1 : 2.0;

Double d = true ? (double)1 : 2.0;

. int, - int, .

* long double int float, , , ,

+4

All Articles