The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. 
Home Methods Floatingpoint  
Search the VIAS Library  Index  
Floatingpoint
In the last chapter we had some problems dealing with numbers that were not integers. We worked around the problem by measuring percentages instead of fractions, but a more general solution is to use floatingpoint numbers, which can represent fractions as well as integers. In Java, the floatingpoint type is called double. You can create floatingpoint variables and assign values to them using the same syntax we used for the other types. For example: double pi;pi = 3.14159; It is also legal to declare a variable and assign a value to it at the same time: int x = 1;String empty = ""; double pi = 3.14159; In fact, this syntax is quite common. A combined declaration and assignment is sometimes called an initialization. Although floatingpoint numbers are useful, they are often a source of confusion because there seems to be an overlap between integers and floatingpoint numbers. For example, if you have the value 1, is that an integer, a floatingpoint number, or both? Strictly speaking, Java distinguishes the integer value 1 from the floatingpoint value 1.0, even though they seem to be the same number. They belong to different types, and strictly speaking, you are not allowed to make assignments between types. For example, the following is illegal: int x = 1.1;because the variable on the left is an int and the value on the right is a double. But it is easy to forget this rule, especially because there are places where Java will automatically convert from one type to another. For example: double y = 1;should technically not be legal, but Java allows it by converting the int to a double automatically. This leniency is convenient, but it can cause problems; for example: double y = 1 / 3;You might expect the variable y to be given the value 0.333333, which is a legal floatingpoint value, but in fact it will get the value 0.0. The reason is that the expression on the right appears to be the ratio of two integers, so Java does integer division, which yields the integer value 0. Converted to floatingpoint, the result is 0.0. One way to solve this problem (once you figure out what it is) is to make the righthand side a floatingpoint expression: double y = 1.0 / 3.0;This sets y to 0.333333, as expected. All the operations we have seen so faraddition, subtraction, multiplication, and divisionalso work on floatingpoint values, although you might be interested to know that the underlying mechanism is completely different. In fact, most processors have special hardware just for performing floatingpoint operations.


Home Methods Floatingpoint 