Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of having a suffix for Java Primitive Data Types?

Sorry for a beginners question! I am learning Java and I'm a bit confused on one topic.

For example, I am declaring and initializing a variable as a float such as:

float myVariable = 9.5;

In some tutorials online, I see floats being declared and initalized like that, but also with a suffix such as this:

float myVariable = 9.5F;

What is the purpose of the the suffix if I am already saying "float myVariable"?

Thanks!

like image 659
Jacob Avatar asked Dec 02 '22 19:12

Jacob


2 Answers

Floating point literals are by default of double type. So, 9.5 is double not float. To make it float we append an f at the end.

So, in first case:

float myVariable = 9.5;

You are trying to assign a double type literal to a float type variable, which requires an explicit typecasting. The statement won't compile. You need to add a cast there:

float myVariable = (float) 9.5;

While in 2nd case:

float myVariable = 9.5F;

there is no conversion.

like image 107
Rohit Jain Avatar answered Dec 22 '22 00:12

Rohit Jain


Java uses suffixes with these primitives types, here is a brief intro:

float

float fVariable = 5.5 is by default double while float fVariable = 5.5f makes it float

long

long lVariable = 55 here literal 55 is by default int type but long lVariable = 55l makes it long type.

double

double dVariable = 5.5 and double dVariable = 5.5d are similar but here d suffix is optional

like image 42
Kalher Avatar answered Dec 21 '22 23:12

Kalher