• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

float- arithmatic

 
Teajl Shah
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried following code and expected that the output would be 3.0f instead it is 3.0.Does it mean that float addition gives result of type double
float f=1.0f;
float h=2.0f;
float d=f+h;
System.out.println("The value of float addition is " + d);
 
summer_gsr
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java considers a floating point number to be a double, unless it has suffix of an 'f' or 'F' charecter. Since you used that suffix the answer is given in float type.
Summer
 
Teajl Shah
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Summer
My qs is :why the output is not 3.0f?
 
summer_gsr
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I taught you were asking whether the result was given in a double format? Iam just a beginner in java so I don't know why but for discussion , I think the reason is that just because the variables h and f were defined with a suffix does'nt mean that the answer should be printed out as 3.0f. It just means that it is defined as a float type insead of double. Try to print the variable h the output will be 2.0 and not 2.0f.
Summer
 
Konda Balabbigari
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Teaji
Your doubt is absolutely right, but the problem is with Java.
Java follows certains rules when you try to define floating point numbers. While processing the floating point values Java does internal conversion. For full details on how does this conversion
, here is the link http://java.sun.com/docs/books/jls/html/3.doc.html#230798
Thanks
Konda Balabbigari
Contact: http://www.javacaps.com
 
sunil choudhary
Ranch Hand
Posts: 144
Java Redhat Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Consider the following example Tejal(I believe this to be a better spelling of your name then Teajl-correct me if I am worng)
and it will be clear to you that the value d is still a float.As explicit casting is needed at line A
Hope this helps
class Ash
{
public static void main(String args[]){
int f=1;
float h=2;
float d=f+h;
System.out.println("The value of float addition is " + d);
double f=5;
float e=d+f; //A
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic