C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programming language

Java - Difference between float and double

Learn: Difference between float and double in java? Here, we will learn about float and double data types in java? Compare float and double in java.
Submitted by Preeti Jain, on January 31, 2018

1) float data type in java

1) float is a data type (or in another words it is a keyword which has special meaning) in java.

2) float takes 4 bytes(i.e. 32 bits) in memory (or in another words we can represent (+,-) 3.40282347E + 38F Numbers).

Example 1: Here we are checking size of float.

class FloatSize {
	public static void main(String[] args){
		float a ;
		System.out.println(Float.SIZE/8 + " BYTES");
	}
}

Output

D:\Java Articles>java FloatSize
4 BYTES

3) In other words float is a single precision floating point decimal number (i.e. we can represent 7 places of decimal accuracy or in simple terms we can take 7 digits after decimal).

Example 2:

class FloatPrecision {
	public static void main(String[] args){
		float a = 2.3456784f ;
		System.out.println("Float Precision after decimal is " + a);
	}
}

Output:

D:\Java Articles>java FloatPrecision
Float Precision after decimal is 2.3456783

4) Default value of float is 0.0f.

5) float is basically used to save memory (better memory utilization) in large arrays of floating point decimal number.

6) float is not a default data type to represent decimal numbers.

7) float is recommended to be used for precise values (i.e. 7 digits to the right of the decimal places).

2) double data type in java

1) double is a data type (or in another words it is a keyword which has special meaning) in java.

2) double takes 8 bytes(i.e. 64 bits) in memory (or in another words we can represent (+,-)┬▒1.79769313486231570E+308 Numbers).

Example 1: Here we are checking size of float.

class DoubleSize {
	public static void main(String[] args){
		double a ;
		System.out.println(Double.SIZE/8 + " BYTES");
	}
}

Output

D:\Java Articles>java DoubleSize
8 BYTES

3) In other words double is a double precision floating point decimal number (i.e. we can represent 15 places of decimal accuracy or in simple terms we can take 15 digits after decimal).

Example 2:

class DoublePrecision {
	public static void main(String[] args){
		double a = 2.345678432433564 ;
		System.out.println("Double Precision after decimal is " + a);
	}
}

Output

D:\Java Articles>java DoublePrecision
Double Precision after decimal is 2.345678432433564

4) Default value of double is 0.0d.

5) double is basically used to represent double pr├ęcised floating numbers.

6) double is a default data type to represent decimal numbers.

7) double is recommended to be used for precise values (i.e. 15 digits to the right of the decimal places).



Liked this article? Do share with your friends :)


COMMENTS