File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes about variable declaration 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 "about variable declaration" Watch "about variable declaration" New topic
Author

about variable declaration

wei liu
Ranch Hand

Joined: Dec 06, 2001
Posts: 56
Which of the following are legal statements?
1) float f=1/3;
2) int i=1/3;
3) float f=1.01;
4) double d=999d;
Answer to Question 1)
Objective 4.5)
1) float f=1/3;
2) int i=1/3;
4) double d=999d;
The fact that option 3 does not compile may be a surprise. The problem is because the default type for a number with a decimal component is a double and not a float. The additional trailing d in the option with 999 doesn't help, but it doesn't harm.
----------
i m confused about the 2nd ans,why is it correct? i suppose int should not be initialized like int i=1/3, since the result would be int i =0.333333......
Kaspar Dahlqvist
Ranch Hand

Joined: Jun 18, 2001
Posts: 128
Hello!
Have you tried executing any of these little snipplets? Isn't it strange that the result of
float f = 1/3;
is 0.0? The reason for this is also the reason why
int i = 1/3;
executes.
Actually, both 1 and 3 are integers. Right? And if you divide one int with another, the answer, too, will come in the shape of an int. In ordinary math, 1/3 yields 0.33333. But as an int cannot store the decimal part, the result will be 0. This result can then be stored in an int, in which case the int's value will be 0. The result can also be stored in a float, in which case the float's value will be 0.0...
I recommend reading RHE, chapter 2, "The Arithmetic Operators".
Hope this helps!
//Kaspar
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: about variable declaration