Java: Variables: double

In this tutorial I will explain the double. 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 double 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 an endles amount of decimals. It can store up to 16 numbers. So for example 1.123456789012345 and 12.12345678901234. If you try to save more numbers it will start rounding of the numbers.
You also can’t save a number higher or lower than the maximum of an int which means somewhere between -2^31 and 2^31 – 1. If you try to give a higher full number it will crash.
The reason why people want to save a double is that they can store a lot of decimals in the numbers. It is slower than a float, but it can also save more. This is the most exact number of decimals you can get in Java.
If you want to use a double in java you need to code it like this.


double number = 6;


The first part in this line is the type of variable. In this case a double.
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.
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 double. Why that is and how you should use that is something for a later tutorial though.


package net.tutorial.src;

public class Tutorial 
{
static double 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="">