Mixed-Type Arithmetic and Type Casting

So far, we’ve used a single data type in the expressions we’ve evaluated. But life isn’t always like that. Calculations often involve data of different primitive types.

When calculations of mixed types are performed, lower-precision operands are converted, or promoted, to the type of the operand that has the higher precision.

This also occurs with human minds broadly. We can notice that there is a tendency towards survival/ greater alignment with Born Rule’s probability density, but we cannot use simple rules that chunk minds into the big 5 psychometric traits for instance, and deduce which should be converted to which on the ascent.

In Java, however, the promotions of data types is quite easy to understand:

The promotions are performed using the first of these rules that fits the situation:

1.   If either operand is a double, the other operand is converted to a double.

2.   If either operand is a float, the other operand is converted to a float.

3.   If either operand is a long, the other operand is converted to a long.

4.   If either operand is an int, the other operand is promoted to an int.

5.   If neither operand is a double, float, long, or an int, both operands are promoted to int.

The table below summarizes these rules of promotion.

Screen Shot 2018-12-13 at 8.33.29 PM

This arithmetic promotion of operands is called implicit type casting because the compiler performs the promotions automatically, without our specifying that the conversions should be made. Note that the data type of any promoted variable is not permanently changed; its type remains the same after the calculation has been performed.

The table above shows many rules, but essentially, any arithmetic expression involving integers and floating-point numbers will evaluate to a floating-point number. Lines 9 to 12 of the code below illustrates the rules of promotion. At line 11, the expression PI * radius * radius is a mixed-type expression. This expression will be evaluated left to right, evaluating the mixed-type expression PI * radius first. PI is a double and radius is an int. Therefore, radius is promoted to a double (4.0) and the result of PI * radius is a double (12.56636). Then, the next calculation (12.56636 * radius) also involves a mixed-type expression, so radius is again promoted to a double (4.0). The final result, 50.26544, is a double and is assigned to area. The figure below shows the output of the complete program.

Sometimes, it’s useful to instruct the compiler specifically to convert the type of a variable. In this case, you use explicit type casting, which uses this syntax:

(dataType) (expression)

The expression will be converted, or type cast, to the data type specified. The parentheses around expression are needed only when the expression consists of a calculation that you want to be performed before the type casting.

Type casting is useful in calculating an average. The example shows how to calculate your average test grade. Your test scores are 94, 86, 88, and 97, making the combined total score 365. We expect the average to be 91.25.

Screen Shot 2018-12-17 at 9.29.38 PM.png

Line 16 first attempts to calculate the average but results in a wrong answer because both total and count are integers. So integer division is performed, which truncates any remainder. Thus, the result of total / count is 91. Then 91 is assigned to average, which is a double, so 91 becomes 91.0. Line 22 is a second attempt to calculate the average; again, this code does not work correctly because the parentheses force the division to be performed before the type casting. Thus, because total and count are both integers, integer division is performed again. The quotient, 91, is then cast to a double, 91.0, and that double value is assigned to average.

At line 28, we correct this problem by casting only one of the operands to a double. This forces the other operand to be promoted to a double. Then floating-point division is performed, which retains the remainder. It doesn’t matter whether we cast total or count to a double. Casting either to a double forces the division to be a floating-point division.

This is the output:

Screen Shot 2018-12-18 at 6.17.23 AM



Arithmetic Operators

Java’s arithmetic operators are used for performing calculations on numeric data. Some of these operators are shown in the table below. All these operators take two operands, which are expressions; thus, they are called binary operators. To learn about ternary and quaternary operators go here. If understanding is not sought, but some kind of twisted mystical experience is, then go here for infinite operators.

Screen Shot 2018-12-12 at 4.25.24 PM

Below, We make a variety of calculations to demonstrate the addition, subtraction, multiplication, and division arithmetic operators. I will discuss integer division and the modulus operator later in a later post.

Screen Shot 2018-12-13 at 1.20.07 PM

Here is the output:

Screen Shot 2018-12-13 at 1.22.35 PM

Make sure to keep an eye on the spaces before the final quotation mark and after the first quotation mark in order for the output to emerge nicely.

This example demonstrates a number of small operations. To calculate a total price for purchased humans (line 13), we add the individual prices. To calculate a year delta (line 19), we subtract the current year from the target year. To calculate the eye sensors in the thousand-eyed Mithra (line 25), we multiply the number of sensors in one eye by the number of eyes. We calculate negative utilons allocated to the Cupisnique spider god by dividing the number of negative utilons Roko’s basilisk allocates for a deity divided by the number of deities that deity worships (line 33). Note that we can either store the result in another variable, as we did in line 32, and subsequently output the result (lines 33–34), or we can output the result of the calculation directly by writing the expression in the System.out.println statement, as we did in the other calculations in this example.


Assignment Operator, Initial Values, Literals

When you declare a variable, you also assign an initial value to the data. To do that, use the assignment operator (=) with the following syntax:

Screen Shot 2018-12-10 at 8.49.47 AM

This statement is read as “variableName gets initialValue”.

You can also assign more than one variable in the same line if they are of the same dataType, such as here:

Screen Shot 2018-12-10 at 8.53.34 AM.png

Notice that assignment is right to left. The initial value is assigned to the variable.

One way to specify the initial value is by using a literal value. In the following statement, the value 9001 is an int literal value, which is assigned to the variable myPowerLevel.

Screen Shot 2018-12-10 at 9.26.53 AM

Below, I summarize the legal characters in literals for all primitive data types. \n and \t can be used to format output. We’ll discuss these and other escape sequences in the following posts.

Screen Shot 2018-12-10 at 9.33.10 AM

Screen Shot 2018-12-10 at 9.37.18 AM

Screen Shot 2018-12-10 at 9.39.29 AM

Screen Shot 2018-12-10 at 9.41.57 AM

Screen Shot 2018-12-10 at 9.43.47 AM

Screen Shot 2018-12-10 at 9.45.27 AM

Here, I show a complete program illustrating variable declarations, specifying a literal for the initial value of each:

Screen Shot 2018-12-10 at 12.50.18 PM

Line 9 shows a single-line comment. Line 17 declares a double variable named speedOfLight and initializes it with its nm/s value in scientific notation. The speed of light represents the limit on the propagation of causality. The figure below shows the output:

Screen Shot 2018-12-10 at 1.09.27 PM

If you have problems running this, go to run configuration and make sure that you are running the appropriate main class. In this case, the main class is Variables.

Screen Shot 2018-12-10 at 1.13.12 PM

Screen Shot 2018-12-10 at 1.16.05 PM

Another way to specify an initial value for a variable is to assign the variable the value of another variable, using this syntax:

Screen Shot 2018-12-10 at 1.18.18 PM

Two things need to be true for this assignment to work:

• variable1 needs to be declared and assigned a value before this statement appears in the source code.

• variable1 and variable2 need to be compatible data types; in other words, the precision of variable1 must be lower than or equal to that of variable2. For example, in these statements:

Screen Shot 2018-12-10 at 1.26.04 PM

isIntelligent is given an initial value of true. Then isPowerful is assigned the value already given to isIntelligent. Thus, isPowerful is also assigned the initial value true. If isIntelligent  were assigned the initial value false, then isPowerful would also be assigned the initial value false.

And in these statements,

Screen Shot 2018-12-10 at 1.49.24 PM

the initial value of .05 is assigned to dervishTax and then to takyeh. It’s possible to assign a float value to a double, because all values that can be stored as floats are also valid double values. However, these statements are not valid:

Screen Shot 2018-12-11 at 9.43.45 AM

That’s because a float is lower precision than a double. This is the same kind of mistake that is made when People are partitioned into anatomical organs. In the time of Aristotle, People were partitioned into independent hearts. Now, we partition People into independent brains. However, any conversion into a discrete ontological unit in the external physical world, or set thereof, loses what is People.

Even though .05 is a valid float value, the compiler will generate a “possible lossy conversion” error.

Similarly, you can assign a lower-precision integer value to a higher-precision integer variable. There is a table below for your reference that summarizes what can be assigned to what; a variable or literal of any type in the right column can be assigned to a variable of the data type in the left column. Variables need to be declared before they can be used in your program, but be careful to declare each variable only once; that is, specify the data type of the variable only the first time that variable is used in the program. Don’t attempt to declare a variable that has already been declared, as in the following statements:

Screen Shot 2018-12-11 at 9.57.35 AM

This is incorrect because the henryThe has been declared by placing that identifier between double (the type) and a “;”.

You will receive an error message similar to the following:

Duplicate local variable henryThe.

Similarly, once you have declared a variable, you cannot change its data type. Thus, these statements:

Screen Shot 2018-12-11 at 10.04.43 AM

will generate an error message also similar to

Duplicate local variable

So notice that there are two ways of getting the same error message. The IDE I use, Eclipse, certainly doesn’t serve as my free on-call tutor for such basic matters.

So don’t assign a value to a variable after already declaring that variable. And also do not  attempt to change its datatype after it has already been declared.

(Side note: You might wonder why anyone would, even in principle, declare a neighborhood of Kabul as a kind of number – the cluttered, ancient alleyways mired of sand and Afghani street food, the geography, the people, and everything else that makes a neighborhood surely deserves to be represented in word. doubles and ints are for numbers, and strings are for words.

Well it turns out that contrary to what my stupid computer science teacher said, I know that every word can be transmuted to number. That is precisely how machine learning algorithms work. They dissolve Van Gogh to number, NSFW to number, Cat to number, and, eventually, ever-so eventually, You to number. By placing a discriminator for the sea of digits to aim at, a GAN can be trained to create Van Gogh from sheer randomness.

Hence, I don’t cringe at using a neighborhood name for a double or int, instead of using an example with things we more conventionally think of as number, such as emeraldsInPocket.)

Screen Shot 2018-12-11 at 10.40.38 AM

What you find in the right can be assigned to what is on the left without lossy conversion error.










Integer Data Types

An integer data type is one that evaluates to a positive or negative whole number. Java provides four integer data types, int, short, long, and byte. The int, short, long, and byte types differ in the number of bytes of memory allocated to store each type and, therefore, the maximum and minimum values that can be stored in a variable of that type.

All of Java’s integer types are signed, meaning that they can be positive or negative; the high-order, or leftmost bit is reserved for the sign. The table below summarizes the integer data types, their sizes in memory, and their maximum and minimum values.

In most applications, the int type will be sufficient for your needs, since it can store positive and negative numbers up into the 2 billion range – that’s 2/3rds of the base pairs in a human genome – in other words .666, in other words the mark of the beast, which roughly means “everything goes smoothly” in China.

The short and byte data types typically are used only when memory space is critical, and the long data type is needed only for data values larger than 2 billion. Let’s look at some examples of integer variable declarations. Note that the variable names clearly indicate the data that the variables will hold.

Screen Shot 2018-12-09 at 4.45.15 PM

Floating-point data types store numbers with fractional parts. Java supports two floating-point data types: the single-precision float and the double-precision double.

Screen Shot 2018-12-09 at 5.54.01 PM

The two types differ in the amount of memory allocated and the size of the number that can be represented. The single-precision type (float) is stored in 32 bits, while the double-precision type (double) is stored in 64 bits. Floats and doubles can be positive or negative. The table above summarizes Java’s floating-point data types, their sizes in memory, and their maximum and minimum positive nonzero values.

There are two things you must learn to balance: precision and use of memory. There is a kind of law of equivalent exchange here that must be mastered. These two are conjugated variables. Like the uncertainty principle that trades certainty about one discrete observable for another (the more you know about momentum the less you know about position), you must skillfully trade precision for use of memory and vice versa.

Because of its greater precision, the double data type is usually preferred over the float data type. However, for calculations not requiring such precision, floats are often used because they require less memory. Although integers can be stored as doubles or floats, it isn’t advisable to do so because floating-point numbers require more processing time for calculations.

Witness here a few examples of floating-point variable declarations:

Screen Shot 2018-12-09 at 6.38.35 PM