wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes int i = 1/3; Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "int i = 1/3;" Watch "int i = 1/3;" New topic
Author

int i = 1/3;

Soum Sark
Ranch Hand

Joined: May 31, 2002
Posts: 50
why does it compile without giving an error . Doesnt 1/3 produce a double no (0.3333) and thus it would be a loss of precision to push it into an int ?
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
No it does not (give 0.33333).
Do you have any Java books? If not there are some free ones available, and excellent tutorials are available here on JR. You may have to read some sections several times to get some topics clear.
If you are really, really stuck then please repost.
-Barry
[ August 17, 2002: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
The Java Tutorial at java.sun.com is very good.
Thinking in Java at bruceeckel.com is a free masterpiece.


SCJP2. Please Indent your code using UBB Code
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
If both operands are integers, the result will be an integer. Integer division truncates, so 1/3 is 0. If you want a double, you need to say 1/3.0 or 1.0/3 instead.


Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Hey Ron, you are too good.
Soum Sark
Ranch Hand

Joined: May 31, 2002
Posts: 50
Hey Barry, you should learn something from others
 
Consider Paul's rocket mass heater.
 
subject: int i = 1/3;