• Post Reply Bookmark Topic Watch Topic
  • New Topic

Floats in Java  RSS feed

 
puja mehta
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi I am new to Java and was working with Floats;

I typed float fltVar = 1.2; but got an error stating Java cannot convert from double to float; why does Java assume 1.2 to be double rather than float ?

-Puja
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

by default compiler assume decimal value as double.

so you have to assign like below

------------------------------------------------

float a=1.6f or float a=1.6F

--------------------------------------------------------
 
Purav Gandhi
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is right. But his question is why does compiler assume that this is double rather than a float.
 
madura shantha
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
compiler takes "double" for the default type for decimal numbers.
why dont you ask "why compiler takes int as default rather than long"?
you know the answer.that's compiler's choice.
decimal numbers are supposed to be larger than integers. so compiler takes 'double' as default rather than float.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Purav Gandhi:
But his question is why does compiler assume that this is double rather than a float.

The answer to that is: Because that is just how it works according to the Java Language Specification. See section 3.10.2: Floating-point literals.

Floating-point literals are defined to be of type double; if you want a float literal, you have to append an "f" or "F" behind the number.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just like non-floating point numbers are ints, and you have to append l or L to make it a long. It doesn't automatically become a long just because it doesn't fit in the int range.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!