javajshelltypecasting-operator

What is the difference between "int x = (int) x" and "x = (int) x" in java if I assign "double x = 2.3"?


if I assign "double x = 2.3", what is the difference between "int x = (int) x" and "x = (int) x" ? I'm new to java and use python before, in python, if I execute "x = 2.3; x = int(x); print(x)", x is 2.

java:

enter image description here

python:

enter image description here


Solution

  • You're re-declaring x, so in the line

    int x = (int)x
    

    The x on the right is not the same x you previously declared. So its value defaults to 0 so (int)x is 0. You normally wouldn't be able to have two x variables. That's a thing jshell lets you do, but in normal Java you couldn't do.

    See this:

    jshell> double x = 2.3
    x ==> 2.3
    
    jshell> int y = (int)x
    y ==> 2