Java: Variables: float

In this tutorial I will explain the float. To do that I will use this file.


package net.tutorial.src;

public class Tutorial 
{
public static void main(String[] args)
{
System.out.println(“Hello World!”);
}
}


Like all other variables a float has to be created somewhere inside of a class.
The double and the float are the only 2 data types that are able to store numbers with decimals. So it can save the numbers 6, 6.5, 6.0005. However, it can’t store numbers with more than 8 numbers. For example if you try to store 6.1111119 it will save it as 6.111112. Also if you try to save numbers like 611111.19 it will save it as 611111.2. Lastly if you try to save a number in it that has more than 8 numbers it will also change it a little bit. For example if you try to store the number 123456789 it will save it as 1.23456792E8 or 123456792.
The reason why people want to use a float is that it stores decimals which most other data types can’t do. It is also faster than a double so if you are certain the numbers will never really get high, but it will have decimals a float is your best type.
One more important thing to note is that you have to add the character f or F behind a float number. If you don’t there is a big chance you will get errors.
If you want to use a float in java you need to code it like this.


float number = 6f;


The first part in this line is the type of variable. In this case a float.
The second part in this line of code is the name of the variable. In this case number.
The last part of this line of code is the thing number will be. In this case number will be 6.
Behind the 6 you also see an f which means that the 6 is a float.
If you want to print out a number in the console you have to use a line of code like this.


System.out.println(number);


Because this bit of the code is in the main method and the main method is static you have to add the word static in front of float. Why that is and how you should use that is something for a later tutorial though.


package net.tutorial.src;

public class Tutorial 
{
static float number = 6f;

public static void main(String[] args)
{
System.out.println(number);
}
}


 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">