Learn Programming in Java


<<Previous | ToC | Next >>

Lesson #2n: Variables & Expressions (Numbers)

So far we have been working only with text strings, but computers also (or especially) do numbers. We did numbers in Chomp. There are basically two kinds of numbers a computer can calculate, integers and floating point. Floating point is scientific notation, some fraction times a power of two (instead of ten). It's a lot more complicated than adding or subtracting integers, so I will save that for a little later. Here's a program to illustrate integer data types and operations:
int boyz = 7, gulz = 3;
System.out.println("There are " + boyz + " boys and " + gulz + " girls.");
System.out.println("That's " + boyz+gulz + " kids.");


So if there are seven boys and three girls, how many kids total, ten or 73? Yup, that's a problem. I think it's a mistake in Java to use the "+" operator for two very different (but common) operations, but they didn't ask my opinion. Remember the parentheses in Chomp? Change that last line to:

System.out.println("That's " + (boyz+gulz) + " kids.");


and it works correctly. Why is that? The Java compiler looks at the type of the value to the left of the "+" symbol to decide whether to do this as an integer add or as a string concatenate, but consecutive operators of the same precedence evaluate left-to-right, so the first "+" sees a string on the left and converts the integer to a string and concatenates them. Then it sees a string on the left and another plus, so it converts the second integer to string and concatenates again. Parentheses override operator sequence by forcing the plus inside the parentheses to be evaluated first, and in that case it's an integer on the left, so it adds them numerically. After that, string concatenation works properly. You will probably see wrong results on many printouts before you get in the habit of adding a lot of extra parentheses. That's OK, you learn by doing. Like a bicycle, you fall off a lot before you get the hang of it.

In addition to the four mathematical operations you learned in grade school, Java supports numerous strange operations on binary numbers, which we will look at later.

Operator precedence refers to which operators get evaluated first when they are mixed without parentheses. Parentheses always take precedence, but other than multiply/divide taking precedence over add and subtract, the rest of the precedence rules are illogical, so you should always use parentheses rather than trying to remember.

Java has a character type "char" which (again like C) is really just another integer. Finally, there is a "boolean" type which has values "false" and "true". You get a boolean result when you compare two values of the same type, like this:

boolean rez = false;
int i = 3, j = 5, k = 0;
k = i+j;
res = k>7;
System.out.println("The value of k = " + k + " and the result rez = " + rez);


You should experiment with different integer operators (+ - * /), and also with different comparisons (<  >  ==  >=  <=  !=). Can you figure out what each one is? Notice that to compare for equality we must use the equal-compare operator ('==') and not the assignment operator ('='). It's easy to type the wrong operator, and Java will not always help you.
 

Floating Point

You don't need to know how the computer hardware does floating point to use it, but there are a few things you should understand. First and most important, floating point is designed for numbers that cannot be represented exactly in the computer. Many numbers are exact, but you should not depend on it. Zero is always exact, but when stepping up or down to a limit, you should always test for ">=" or "<=" rather than just "==". We call the differences roundoff error, and although the standard hardware minimizes such errors, they are not completely avoidable. The IEEE (now ISO) standard calls for two sizes, but the hardware folks just do everything in double precision, so Java also does all their math functions in "double"; nobody uses "float" (also known as "single precision") any more, but it's there in Java if you want it.

You declare variables to be floating point by using the type name double (or float) insted of int. Floating point constants have a decimal point or an explicit exponent (like 100.0 or 1e2 = 1*102 for one hundred). You can convert a floating point number to integer (discarding the fractional part) by casting it (using the result type name in parentheses in front of the value) thus: int i = (int)x; (where x is double or float). You also use casting to convert from double to float or back.

Most of the heavy-duty mathematical functions are in Java class Math, which you can look up online if you need them. The four operators that we have been using with integers also work with double and give reasonably accurate results. If you mix integer and floating point values, the integer will be converted to whatever size floating point you are using, because integer addition is fundamentally different (and slightly faster) than float or double. The conversion costs you a step in the computation, so you should try not to mix the modes of arithmetic. If you try to do something the hardware is not designed for, it might give you odd-looking values like infinity or "NaN" (Not a Number). You get NaNs from illegal operations like 0.0/0.0, and they have the peculiar property that they are never equal to anything, not even themselves. You get infinity from dividing a very tiny number by a very large number; it's not the exactly correct answer (which would require more bits than the computer has allocated for it), but I told you the results are often not exact. Mostly you won't run into these problems -- except when your program has errors.

Oh, by the way, I was on the original IEEE-754 committee that defined the standard used in every modern computer, and because I was the only person with a home computer capable of editing it, I was the draft editor. The mathematical theory was the work of Prof.William Kahan at Berkeley, supported by his student Jerome Coonen, who later went to Apple. John Palmer supervised the first implementation at Intel, where he worked. Because we insisted on mathematical correctness (ideological purity) some of the less enthusiastic members of the larger working group referred to us as "The Gang of Four" after the Chinese hit squad during the Maoist revolution. We wore the badge with honor, it's a good standard.
 

Bitwise Operators

There's a computer geek T-shirt joke that goes like this:
There are 10 kinds of people in the world,
Those who understand binary,
And those who don't.
If you understand binary, then after you see that there are only two kinds of people described, you realize that "10" is meant to be understood as binary (two). If you don't, then the joke doesn't make sense, which is what makes it funny to the geeks.

Computers do all their computations in binary, and if you want to be a really good programmer, you need to be able to think in binary. However, there are a lot of programs you can write that don't depend on you knowing any binary at all: do everything in decimal, and the compiler will make the necessary conversions, no harm, no foul. So all the esoteric stuff about binary numbers and the special operators Java has for operating on individual bits, I put them in a separate section "Binary Operations," which you can read now or later or not at all, depending on how deep you want to get into this. None of the exercise programs we have planned for you require you to know the binary operations, but some of them may have an optional segment where you can make your program more efficient if you use the special operations.

Next: Conditionals & Input

Optional: Binary Operations

Optional: Chomp in Java (this needs revision)

<<Previous | ToC | Next >>

Revised: 2020 September 17