Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Automatic type promotion

 
Amit Dhyani
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java Complete refernce, herbert schildt says:

Type promotion rules:
...
If one operand is a float, the entire expression is promoted to a float.
...

Then why I am i getting an error in this:

float f;
f=5/2.0;

Error is:
Possible loss of precision.
Required - float
Found - double
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
2.0 is a double.
2.0f is a float.
 
Pratik D mehta
Ranch Hand
Posts: 121
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you cannot assign a double value to a float .
The reason is here 2.0 is double , by default the precision is double ,
Here is an example we write float x = 3.2f and not float x = 3.2 , f indicates that value is float
If we write float x = 3.2 , here by default 3.2 is double .

Hence the problem
you can type cast it float = (float)(5/2.0) ;
And then assign it .
I hope this clears it.
And WELCOME to javaranch.

 
Amit Dhyani
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys.
My question is answered.

Experienced Java programmers always used to refer to coderanch. Now I can see why.
This was the fastest resolution I ever got on any forum.

Thanks again.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48961
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Ranch
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic