Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading