File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Automatic type promotion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Automatic type promotion" Watch "Automatic type promotion" New topic

Automatic type promotion

Amit Dhyani

Joined: Nov 15, 2010
Posts: 2
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;

Error is:
Possible loss of precision.
Required - float
Found - double
Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

2.0 is a double.
2.0f is a float.

[My Blog]
All roads lead to JavaRanch
Pratik D mehta
Ranch Hand

Joined: Jul 29, 2010
Posts: 121

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.

Understanding is Everything - Peter Lord
Amit Dhyani

Joined: Nov 15, 2010
Posts: 2
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

Joined: Oct 13, 2005
Posts: 46410
And welcome to the Ranch
I agree. Here's the link:
subject: Automatic type promotion
It's not a secret anymore!