float double error

public class test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
exByte();
	}
	
	public static void exByte(){
		float f=3.4444f;
		float f1=3.4444;
	}

}

Open in new window

i am trying above program. i am getting error like

Type mismatch: cannot convert from double to float

i wonder why i got this error. Please advise
LVL 7
gudii9Asked:
Who is Participating?
 
dpearsonCommented:
Decimal values like "3.44444" are by default treated as type "double" in Java.

If you add the "f" to the end, you're saying it's of type "float" (which has less precision).

So these are both fine:
float f=3.4444f;
double d1=3.4444;

but these are not allowed because you're trying to move a double (more precise value) into a float (less precise):
float f1 = d1 ;
f1 = 3.4444 ;

That's why the cast that CEHJ posted is needed.

The other way around is OK because you can move something with less precision (float) into a value with more precision (double) without losing anything:
double d1 = 3.4444f
d1 = f1 ;

Doug
0
 
ozoCommented:
incompatible types: possible lossy conversion from double to float
0
 
CEHJCommented:
Casting will make the error disappear
float f1=(float)3.4444;

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.