-3

I have the following variables and I am trying to turn myInt into a double, however, I am getting a "Cannot convert from double to int' error. I noticed that I can turn a double to an int without incident, but am unsure as to why this fails. Please bear with me as I am new to programming.

    double myDouble = 4;
    int myInt;


    myInt = myDouble;

    System.out.println(myInt);

Thank you!

La-comadreja
  • 5,627
  • 11
  • 36
  • 64
user2917239
  • 898
  • 3
  • 12
  • 27
  • 1
    The answers here are all correct, but I think you have a conceptual gap. Once you've declared a variable, you can't change its type. If you assign a different value to it, the type of the variable doesn't change - but the value may have to be "cast" to be compatible to the variable you're assigning it to. This casting might be automatic (which will happen if you cast an int to a double, to store an int value in a double variable), or it might be something that you have to explicitly tell Java to do (which will happen if you cast a double to an int, to store a double value in an int variable). – Dawood ibn Kareem Apr 29 '14 at 21:21
  • Thank you, this question is more for academic purposes than anything else – user2917239 Apr 29 '14 at 21:26
  • However, the variable may not be accessible to the whole program. The section of the program the variable is accessible in is called the variable scope. You can declare a variable with the same name and different type outside a given variable's scope. You don't want to, though--code written that way is confusing to read. – La-comadreja Apr 29 '14 at 21:34

3 Answers3

6

The assignment double myDouble = 4 contains a "primitive widening conversion", which takes the int literal 4 and widens it to a double, specifically, 4.0. Java usually doesn't allow implicit "primitive narrowing conversion" (the opposite), which is what myInt = myDouble; is attempting to do.

However, you can make it explicit with a cast to int:

myInt = (int) myDouble;
rgettman
  • 176,041
  • 30
  • 275
  • 357
4

Java does widening conversions without help (e.g. int to double) but for a narrowing conversion you need an explicit cast.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
1

Write this:

myInt = (int) myDouble;
La-comadreja
  • 5,627
  • 11
  • 36
  • 64
  • Thanks, so under this code, myInt is now a double type? correct? – user2917239 Apr 29 '14 at 21:12
  • nope, it's an int. If you want it to be a double call it "double myInt" but that becomes very confusing given what the variable would be called. – La-comadreja Apr 29 '14 at 21:12
  • I understand, I chose these names for my question so users can have a better time understanding. – user2917239 Apr 29 '14 at 21:15
  • 1
    @user2917239 Your code said `int myInt;`, and that's the type that that variable will now be, forever. Variables can't change types in at runtime like they can in PHP or some other languages. – ajb Apr 29 '14 at 21:31