This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "about variable declaration" Watch "about variable declaration" New topic

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
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;
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!
I agree. Here's the link:
subject: about variable declaration
It's not a secret anymore!