Mega Code Archive

 
Categories / Java Book / 001 Language Basics
 

0017 double type Literals

double type numbers have decimal values with a fractional component. They can be expressed in either standard or scientific notation. Standard notation consists of a whole number component followed by a decimal point followed by a fractional component. For example, 2.0, 3.14159, and 0.6667. public class Main { public static void main(String args[]) { double d = 3.14159; System.out.print(d);//3.14159 } } Scientific notation uses a standard-notation, floating-point number plus a suffix that specifies a power of 10 by which the number is to be multiplied. The exponent is indicated by an E or e followed by a decimal number, which can be positive or negative. For example, 6.02E23, 314159E-05, and 4e+100. public class Main { public static void main(String[] argv) { double d1 = 6.022E23; double d2 = 314159E-05; double d3 = 2e+100; System.out.println("d1 is " + d1); System.out.println("d2 is " + d2); System.out.println("d3 is " + d3); } } The output generated by this program is shown here: d1 is 6.022E23 d2 is 3.14159 d3 is 2.0E100 You can explicitly specify a double literal by appending a D or d. public class Main { public static void main(String args[]) { double d = 3.14159D; System.out.print(d);//3.14159 } } Java's floating-point calculations are capable of returning +infinity, -infinity, +0.0, -0.0, and NaN dividing a positive number by 0.0 returns +infinity. For example, System.out.println(1.0/0.0); outputs Infinity. public class Main{ public static void main(String[] args) { System.out.println(1.0/0.0); } }