Working with Operators - Java eLearning Kit For Dummies (2014)

Java eLearning Kit For Dummies (2014)

Chapter 5. Working with Operators

· Assigning data to a variable will store the information while the application runs.

· Use arithmetic operators to modify the data value using various types of math.

· Rely on unary operators to perform self-contained data modification.

· Employ relational operators to check how data items compare.

· Exercise operator precedence to determine which operators have priority in your application.

lingo_fmt.tif

1. Do primitive types and objects use assignment operators in the same way?

Primitive types tend to provide straightforward use of assignments, while objects use assignment in context, as described on page 132

2. How do integer types deal with uneven division?

Integer types have access to a special operator that outputs the remainder of a division, as described on page 134

3. What do I do when a variable contains precisely what I don’t want?

You rely either on negation or on the Not operator, as described on page 145

4. Is it possible to make one type of data into another?

Casting lets you transform one data type into another, as shown on page 148

5. How can I determine whether two variables are of the same type?

You can perform a special check on the type of a variable and use the output of this check to compare it with another variable, as described on page 152

6. Which happens first, addition or multiplication?

Java always performs multiplication first, unless you enclose the addition in parenthesis, as described on page 157

Operators are an essential part of Java application development. They do precisely as their name implies — they operate on the value contained within a primitive type or object in some way. Precisely how it operates on the value depends on the operator. In some cases, an operator will change the value in the variable, but in other cases, the operator simply uses the value to perform a specialized task, such as comparing two values. Java provides a wealth of operators that perform every task imaginable.


EXTRA INFO

Java 8 adds one new operator that meets the traditional meaning of the term, the arrow operator (->). This operator is used in a special circumstance to work with lambda expressions (a method of creating functions), and you see it covered in Chapter 9. In the meantime, because the -> is used only for this special purpose, you don’t need to worry about it. In addition, some people are calling the Optional object type an operator. It actually is a type that helps you avoid certain types of errors. This object is discussed in Chapter 8. Again, you don’t need to worry about it until later. Otherwise, Java 8 operators behave just like those found in previous versions of Java.


remember.eps The best way to understand how operators work and what they do is to group them into categories and then look at each category individually. That’s precisely how this chapter approaches the topic. Each of the following sections describes a different operator category and shows how to use the operators within that category to your advantage. Here’s a quick overview of the operators in this chapter:

· Assignment operators place the value you define into the variable. The basic assignment operator replaces the value in the variable. Combined assignment operators perform a math-related task and update the value in the variable. It’s nearly impossible to write an application without making variable assignments of some sort.

· Arithmetic operators perform any math-related task, including addition, subtraction, multiplication, and division. Most applications need to perform math-related tasks, even if the user is unaware of the math functionality. You’ll discover as the book progresses that math is an inescapable part of programming.

· Unary operators cause the variable to interact with its own content in some way, such as incrementing (adding to) or decrementing (subtracting from) the variable’s value. In many respects, unary operators provide a shorthand that makes application code easier to understand and faster to write.

· Relational and conditional operators perform a comparison of some type and provide a result that reflects that comparison. These operators make it possible for applications to make decisions based on the content of variables.

If every operator had precisely the same precedence (priority), chaos would result because the computer wouldn’t know which task to perform first. Because computers are logical and require well-ordered instructions, the developers of Java had to create an order in which operators are used when more than one of them appears in a single line of code. The order of precedence helps determine which task to do first, even if the order isn’t clear from the way the code is written. You need to understand precedence in order to write good code. Otherwise, you may end up with code that assumes that the computer will be working with one operator first and only find out later that the computer really worked with another operator first.


LINGO

Precedence defines the order in which tasks are performed on a computer. Think priority when you see precedence. Just as you prioritize the work you need to do, the computer must also prioritize the work it must do. The order of precedence is essentially the same for all computer languages, and this order is borrowed from mathematicians. In short, the rules you learned for performing math tasks in school are the same rules that the computer uses to perform tasks. As a result, you’ll likely find it easier to learn the order of precedence than you might initially think.


Storing Data Using Assignment Operators

You’ve already used assignment operators quite a bit in this book so far. In fact, almost every example has some type of assignment operator in it because it’s nearly impossible to write an application without one.

Performing a simple assignment

The kind of assignment operator you’ll use most often is a simple assignment. Simple assignments rely on the equal sign (=). In this exercise, you use a simple assignment to place a value in a primitive type and display it onscreen.

Files needed: SimpleAssignment.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

public class SimpleAssignment
{
public static void main(String[] args)
{
// Create a variable to hold the value.
int MyInt;

// Assign a value to the variable.
MyInt = 2;

// Display the content of the variable.
System.out.println("MyInt = " + MyInt);
}
}

In this example, the application begins by creating a storage container of type int with the name MyInt. At this point, MyInt doesn’t contain anything — it’s an empty storage container. In fact, if you were to try to do anything with MyInt, the Java compiler would report that you hadn’tinitialized the variable — you hadn’t actually put anything in the storage container, in other words.

The next step places a value of 2 into MyInt using the assignment operator, =. This is a simple assignment. Nothing happens except that MyInt now contains a value. After MyInt contains something, you can display what it contains using the System.out.println() method.

3. Save the code to disk using the filename SimpleAssignment.java.

4. In your command prompt, type javac SimpleAssignment.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java SimpleAssignment and press Enter.

You see the expected output of MyInt = 2 as shown in Figure 5-1. The point here is that the application has made an assignment using the assignment operator.

9781118098783-fg0501.tif

Figure 5-1:

Performing a combined assignment

A combined assignment complicates the process by first performing a special operation on a value and only then performing a simple assignment. As a result, the content of the variable is updated in a specific way. The following list shows the common combined assignment operators.

· *=: Performs multiplication of the value within the variable by the number supplied to the right of the operator. The result is assigned to the variable.

· /=: Performs division of the value within the variable by the number supplied to the right of the operator. The result is assigned to the variable. When used with an integer type, the remainder is discarded.

· +=: Performs addition of the value within the variable with the number supplied to the right of the operator. The result is assigned to the variable.

· -=: Performs subtraction of the number supplied to the right of the operator from the number within the variable. The result is assigned to the variable.

· %=: Performs division of the value within the variable by the number supplied to the right of the operator. The remainder is assigned to the variable. This operator is used only with integer type variables.


LINGO

The % operator has a special name of modulus.


Each of these operators performs a math operation followed by an assignment. In the following exercise, you use a simple assignment to place a value in a primitive type. The application then performs a number of combined assignments and places the result of each assignment onscreen.

Files needed: CombinedAssignment.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

public class CombinedAssignment
{
public static void main(String[] args)
{
// Create the initial variable and display
// its value onscreen.
int MyInt = 15;
System.out.println("Initial value = " + MyInt);

// Perform a multiply assignment.
MyInt *= 3;
System.out.println("Multiply assignment = " + MyInt);

// Perform a divide assignment.
MyInt /= 2;
System.out.println("Divide assignment = " + MyInt);

// Perform an addition assignment.
MyInt += 6;
System.out.println("Addition assignment = " + MyInt);

// Perform a subtraction assignment.
MyInt -= 12;
System.out.println("Subtraction assignment = "
+ MyInt);

// Perform a remainder assignment.
MyInt %= 7;
System.out.println("Remainder assignment = " + MyInt);
}
}

The application begins by creating a variable and initializing it. If you try to use the variable without initializing it, the compiler will display an error message.

warning.eps It’s impossible to use a combined assignment operator without first initializing the variable. Doing so always results in an error because the combined assignment operator relies on the content of the variable as a starting point; therefore, the variable must contain something.

After the application creates the variable, it uses each of the common combined assignment operators to perform a task with the variable content. The application displays the result each time.

3. View each step of the code carefully and write down the results that you think the application will display.

For example, the first call to System.out.println()displays a value of 15 because MyInt is assigned a value of 15. This step asks you to determine what will happen after each of the remaining steps before you actually run the application.

4. Save the code to disk using the filename CombinedAssignment.java.

5. In your command prompt, type javac CombinedAssignment.java and press Enter.

The compiler compiles your application and creates a .class file from it.

6. Type java CombinedAssignment and press Enter.

You see the application outputs, as shown in Figure 5-2.

9781118098783-fg0502.tif

Figure 5-2:

7. Compare the results of your calculations against the actual application output.

8. If your results didn’t match the output, view each step of the code again to determine where you derived an incorrect output.

This sort of exercise helps you understand the combined operators better. In addition, this is the sort of analysis that professional programmers use to learn new programming skills.

practice_fmt.eps Change the numeric values used at each step of the applications, perform your analysis, and run the application again. Try various values to see how the application reacts. For example, try creating a value that will result in a negative output.

Performing Math Tasks with Arithmetic Operators

Most applications rely on math operations to perform part of their work, even when the user is unaware of such math. As this book progresses, you’ll use math to perform tasks such as keeping track of the application status. Just how this happens is unimportant for now, but it is important to know that you use math relatively often when working with applications. Here’s a rundown on the common math operators used in this book:

· *: Performs multiplication of the values within two variables.

· /: Divides the value within the variable on the right side of the operator by the value in the variable on the left side of the operator. The remainder is discarded when working with integer types.

· %: Divides the value within the variable on the right side of the operator by the value in the variable on the left side of the operator. However, in this case, the result is the remainder, rather than the quotient.

· +: Performs addition of the values within two variables.

· -: Subtracts the value of the variable on the right side of the operator from the value of the variable on the left side of the operator.

The following sections describe how to perform common math tasks by using the math operators. These sections are only an introduction to the topic. You’ll see math operators used in the majority of the examples in this book.

Performing simple math tasks

You’ll often need to perform simple multiplication, division, addition, or subtraction. The combined assignment operators described in the “Performing a combined assignment” section of the chapter provide the best way to perform single math tasks. In the following example, you see how Java performs math operations involving multiple operators or situations where the combined assignment operators don’t work.

Files needed: SimpleMath.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

public class SimpleMath
{
public static void main(String[] args)
{
// Create a series of variables to use.
int X = 5;
int Y = 10;
int Z = 15;

// Perform multiplication and display the

// result.
X = Y * Z;
System.out.printf("%d * %d = %d%n", Y, Z, X);

// Perform division and display the result.
X = Z / Y;
System.out.printf("%d / %d = %d%n", Z, Y, X);

// Perform division using the modulus operator
// and display the result.
X = Z % Y;
System.out.printf("%d %% %d = %d%n", Z, Y, X);

// Perform addition and display the result.
X = Y + Z;
System.out.printf("%d + %d = %d%n", Y, Z, X);

// Perform subtraction and display the result.
X = Y - Z;
System.out.printf("%d - %d = %d", Y, Z, X);
}
}

The example begins by creating three int values, X, Y, and Z. There are many situations where you don’t want to store the result of a calculation in the original variable so that you can reuse the original values in another calculation. In each case, the application performs a calculation and places the result in X. The code uses each of the values to display the calculation and its result.

This example is also the first one to use the printf() method. You use this method to create formatted output. Formatting works just as it does for the calendar example in the “Displaying Date and Time” section of Chapter 4. However, instead of using the date and time formatting strings described in Table 4-2 of Chapter 4, you use the formatting strings shown in Table 5-1 instead. Table 5-1 shows the most common formatting strings — Java does provide others that are used for special tasks.

Table 5-1 Common Java Formatting Strings

Code

Specific Use

Description

%b
%B

General

Displays the Boolean value of the variable. When working with a Boolean variable (either primitive type or object), the result is the actual value of the variable. Other variables display false when the variable is null (hasn’t been initialized) or true when the variable contains a value. The uppercase %B uses uppercase letters.

%s
%S

General

Displays the string value of a variable — whatever the toString() method would normally display. The uppercase %S uses uppercase letters.

%c
%C

Character

Displays the specified Unicode character using the rules of the Character data type. (See the “Character versus char” section of Chapter 3 for details.) The uppercase %C uses uppercase letters even if the character value would normally produce a lowercase output.

%d

Integral

Outputs an integer variable in decimal format.

%o

Integral

Outputs an integer variable in octal format.

%x
%X

Integral

Outputs an integer variable in hexadecimal format. The uppercase %X uses uppercase letters.

%e
%E

Floating point

Outputs a floating point variable using scientific notation. The uppercase %E uses uppercase letters.

%f

Floating point

Outputs a floating point variable using standard floating point (decimal) notation.

%g
%G

Floating point

Outputs a floating point variable using either decimal or scientific notation depending on the precision of the variable. (The application uses the format that will provide the best output.) The uppercase %G uses uppercase letters.

%%

Percent sign

Outputs a percent sign. You can’t use a single % sign because the % sign is used for other purposes when used alone.

%n

Newline character

Adds a newline character to the end of any output that you create. You can also use the \n escape character, but using %n is preferable in formatted output because it matches the remaining formatting strings.

3. View each step of the code carefully and write down the results that you think the application will display.

4. Save the code to disk using the filename SimpleMath.java.

5. Type javac SimpleMath.java and press Enter.

The compiler compiles your application and creates a .class file from it.

6. Type java SimpleMath and press Enter.

The application outputs the formatted strings containing the values used for each math operation, as shown in Figure 5-3. If you change the values of X, Y, or Z, those changes will automatically appear in the output.

9781118098783-fg0503.tif

Figure 5-3:

7. Compare the results of your calculations against the actual application output.

8. If your results didn’t match the output, view each step of the code again to determine where you derived an incorrect output.

practice_fmt.eps Try changing the values of X, Y, and Z in the example. Calculate the results of each of the changes before you run the application. Notice that the application automatically displays the appropriate values in the output for you.


LINGO

An operator is a symbol that defines a task to perform on an operand. An operand is either a variable or a constant. Binary operators, such as *, /, %, +, and -, require two operands — one on the left side of the operator and another on the right.


Executing complex math tasks

Straightforward binary math operations are common enough, but many math tasks are more complex than that. As the math task becomes more complex, the requirement to understand how mathematicians perform their work becomes more important.

The same rules you learned in school for performing math apply to computers as well, so there’s nothing new here. However, the computer doesn’t just understand what you meant to say or write — the computer holds you to a strict interpretation of precisely what you write. The order and precedence of the math operations are important on the computer (as they would be to any moderately complex human communication).

remember.eps The basic rule to remember is that operations proceed from left to right, just as they do in school. Also, multiplication and division take precedence over addition and subtraction. The “Understanding Operator Precedence” section of this chapter provides you with a precise list of how each of the operators interact with each other.

This book can’t describe everything there is to know about math — that’s a topic for another book. However, you can discover some basic principles and use them to build your own examples. In the following exercise, you work through some complex math tasks to see how computers interpret the inclusion of multiple operators.

Files needed: ComplexMath.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

public class ComplexMath
{
public static void main(String[] args)
{
// Create a series of variables to use.
int X = 5;
int Y = 10;
int Z = 15;
int Result;

// Addition and multiplication.
Result = X + Y * Z;
System.out.printf("%d + %d * %d = %d%n",
X, Y, Z, Result);

// Ordered addition and multiplication.
Result = (X + Y) * Z;
System.out.printf("(%d + %d) * %d = %d%n",
X, Y, Z, Result);

// Addition, subtraction, and multiplication.
Result = X + Y - Y * Z;
System.out.printf("%d + %d - %d * %d = %d%n",
X, Y, Y, Z, Result);

// Ordered addition, subtraction, and multiplication
// version one.
Result = X + (Y - Y) * Z;
System.out.printf("%d + (%d - %d) * %d = %d%n",
X, Y, Y, Z, Result);

// Ordered addition, subtraction, and multiplication
// version two.
Result = (X + (Y - Y)) * Z;
System.out.printf("(%d + (%d - %d)) * %d = %d%n",
X, Y, Y, Z, Result);
}
}

The example begins by creating three int values (X, Y, and Z) that act as inputs, as well as a single int (Result) that contains the result of any calculation. The example performs various math tasks with these inputs so that you can see how Java (and for that matter, most computer languages) will react. The screen output relies on the printf() method because it works so well for this type of display. To work through as many different results as needed, all you need to change are the three variable values at the beginning of the application.

In this case, the math operations are mixed — which means that they’re a combination of addition and multiplication. However, the rules stated earlier are all in play. Remember from your math classes that parenthesis act to group operations that you want performed first — they have the highest priority in this example. The code could actually come from a textbook in this case — it doesn’t truly feel as if you’re writing a Java application so much as you’re writing down an equation.

3. View each step of the code carefully and write down the results that you think the application will display.

4. Save the code to disk using the filename ComplexMath.java.

5. In your command prompt, type javac ComplexMath.java and press Enter.

The compiler compiles your application and creates a .class file from it.

6. Type java ComplexMath and press Enter.

The application outputs the formatted strings containing the values used for each math operation, as shown in Figure 5-4. If you change the values of X, Y, or Z, those changes will automatically appear in the output.

9781118098783-fg0504.tif

Figure 5-4:

7. Compare the results of your calculations against the actual application output.

8. If your results didn’t match the output, view each step of the code again to determine where you derived an incorrect output.

practice_fmt.eps Try creating other equations for the example. Remember to change both the equation in the code and your choice of string formatting you want used by the printf() method. (Refer to Table 5-1.)

Modifying Variable Content Using Unary Operators

Binary operators are those that require two operands (variables or constants) to work. A unary operator is one in which you need just the operator and its associated operand. The operators in the earlier “Performing Math Tasks with Arithmetic Operators” section are examples of binary operators. The following sections discuss unary operators, such as those used to increment or decrement the value in a variable.


LINGO

Unary operators perform an operation on a single operand, such as incrementing or decrementing the value within the operand. You must use a variable, and not a constant, when working with a unary operator in most cases.


Incrementing and decrementing numbers

The most common unary operations are incrementing and decrementing numbers. In most cases, an application uses these operations to keep count of something. However, you can use them anytime you need to increase or decrease the value of a variable by one. In this example, you see how the increment (++) and decrement (−−) operators work.

Files needed: IncrementDecrement.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

public class IncrementDecrement
{
public static void main(String[] args)
{
// Define a single variable.
int X = 0;

// Display the initial value.
System.out.println("X = " + X);

// Increment X and display the result.
X++;
System.out.println("X = " + X);

// Decrement X and display the result.
X--;
System.out.println("X = " + X);
}
}

The code in this example is straightforward. It begins by defining an int value, X. The code displays the initial value onscreen. It then increments X and displays the result. Notice that incrementing consists of adding ++ after the variable name. The same thing takes place when decrementing. You add a −− after the variable name.

3. Save the code to disk using the filename IncrementDecrement.java.

4. Type javac IncrementDecrement.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java IncrementDecrement and press Enter.

The output shown in Figure 5-5 demonstrates how incrementing and decrementing works. As previously mentioned, this action works great for keeping count of things.

9781118098783-fg0505.tif

Figure 5-5:

Understanding negation, bitwise Not, and Boolean Not

There are two types of unary operations that you should view together so that you don’t misunderstand them later on. Negation is the act of setting a value to its negative version — the value of 2 becomes –2. Some math-related tasks require that you negate a value in order to use it. In some cases, people confuse negation with subtraction, but subtraction is a binary operation and negation is a unary operation.


LINGO

Negation is the act of setting a value to its negative equivalent. A value of 2 becomes –2.



LINGO

The term bitwise means to perform a task a single bit at a time, rather than using the entire value. So, a bitwise Not operation looks at each bit individually — any 1 becomes a 0, and vice versa. Consequently, when you have a value of 5, which in binary is 00000101, it becomes a negative six, which in binary is 11111010. Notice how the bits are precisely reversed in value.


Contrast negation with the bitwise Not operation, which you implement by using the ~ operator. The Not operation reverses each of the bits in a value. All of the 0s become 1s and vice versa. The Not operation is often used in Boolean-related tasks. It helps an application consider the logic of a task.

To make things even more confusing, there’s a second Not operation called a Boolean Not operation that works on Boolean values. This operation relies on the ! operator. The bitwise operator (~) won’t work on Boolean values and the logical operator (!) won’t work on values other than Boolean.


LINGO

Boolean values are either true or false. When you Not a Boolean value, you turn it from true to false, or from false to true.


It’s time to compare and contrast how negation, bitwise Not, and Boolean Not work. In the following example, you see how an application can manipulate a number or Boolean value using each of these operators.

Files needed: NegationAndNot.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

public class NegationAndNot
{
public static void main(String[] args)
{
// Create the required variables.
int X = 85;
int Y = 0;
boolean Z = true;

// Display the current value.
System.out.println("X = " + X);

// Negate the value and display the result.
X = -X;
System.out.println("X = " + X);

// Negate the value a second time and
// display the result.
X = -X;
System.out.println("X = " + X);

// Show the result of adding a value to its
// Not value.
Y = X + -X;
System.out.printf(
"Adding %d to %d = %d%n", X, -X, Y);

// Set the value to its Not equivalent
// and display the result.
X = ~X;
System.out.println("X = " + X);

// Perform the Not operation again.
X = ~X;
System.out.println("X = " + X);

// Show the result of adding a value to its
// Not value.
Y = X + ~X;
System.out.printf(
"Adding %d to %d = %d%n", X, ~X, Y);

// Show the Boolean Not operation.
System.out.println("Original Z = " + Z);
Z = !Z;
System.out.println("Z = " + Z);
Z = !Z;
System.out.println("Z = " + Z);
}
}

This example begins by creating two variables. The first, an int named X, can use either negation or the bitwise Not operators. The second, a boolean named Y can use the Boolean Not operator. It’s important to consider these operations as a sort of on/off switch. So, the application starts by showing the original value of each variable, and then the values change twice (on and then off).

3. Save the code to disk using the filename NegationAndNot.java.

4. In your command prompt, type javac NegationAndNot.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java NegationAndNot and press Enter.

The code performs each of the tasks as described as shown in Figure 5-6. Notice that negation produces the precise negative of a number, while the bitwise Not produces the bitwise reversal of the variable’s value. Likewise, a Boolean Not produces the reversal of the Boolean value.

9781118098783-fg0506.tif

Figure 5-6:

Creating objects

Throughout this book, you create objects of various types. Java applications typically require one or more objects in order to work. In fact, the Java application itself is an object. Anytime you see the word class in a listing, you’re talking about objects. Every application in this book is aclass, which means that every application is an object.

It’s important to realize just how objects work. When you create a class, what you’re really creating is a blueprint. The blueprint describes how to create an object, but it isn’t the object. To create an instance of a class (the object), you use the new operator. The new operator tells Java to create an instance of the requested object using the class you specify as a blueprint. An application can create as many instances of a class as required, provided there are enough system resources (such as memory) to do so.

Casting one type to another

The act of casting transforms one type of variable into another type. It’s important to realize that casting isn’t some sort of magic. As far as the computer is concerned, all of your data is 1s and 0s. The translation takes place, in part, in how your application views the data. When making a cast between disparate types, such as casting an integer type to a floating point type, the actual form of the data changes as well, but not in a way you need to worry about. (It all happens beneath the surface automatically.)

Casting can produce data loss. For example, if you cast a floating point type to an integer type, you’ll lose the decimal portion of the floating point number. However, the integer portion will remain intact. When you cast a number held in a larger container, such as a long, to a smaller container, such as an int, you can lose the upper bits, and the actual value of the number can change.

In all cases, the cast occurs when you place the new type you want to use within parenthesis next to the original variable. For example, (float)MyInt would cast an int type to a float type. In the following example, you see how various kinds of casting work.

Files needed: TypeCasting.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

public class TypeCasting
{
public static void main(String[] args)
{
// Define variables to use for the example.
int MyInt = 65;
long MyLong;
float MyFloat;
double MyDbl = 12345678901.123456;
char MyChar = 'D';

// Try casting an int to a long and display
// the results.
MyLong = (long)MyInt;
System.out.printf("%d = %d%n", MyLong, MyInt);

// Try casting an int to a float and display
// the results.
MyFloat = (float)MyInt;
System.out.printf("%f = %d%n", MyFloat, MyInt);

// Try casting a double to a float and display
// the results.
MyFloat = (float)MyDbl;
System.out.printf("%f = %f%n", MyFloat, MyDbl);

// Try casting a double to a long and display
// the results.
MyLong = (long)MyDbl;
System.out.printf("%d = %f%n", MyLong, MyDbl);

// Try casting a char to a long and display
// the results.
MyLong = (long)MyChar;
System.out.printf("%d = %c%n", MyLong, MyChar);

// Try casting an int to a char and display
// the results.
MyChar = (char)MyInt;
System.out.printf("%c = %d%n", MyChar, MyInt);

// Try casting a double to an int and display
// the results.
MyInt = (int)MyDbl;
System.out.printf("%d = %f", MyInt, MyDbl);
}
}

The example begins by creating a number of variables of differing types. You’ve seen these types in action before and know from Chapter 2 that they have different presentations and different storage capacities. Simply casting one type to another may or may not work depending on the type and storage limitations.

3. Examine the code before you compile it and determine which of the casts you think will fail.

You can create a list of the failures before you run the application. It’s important to build knowledge of casts that will most definitely fail in real world applications.

4. Save the code to disk using the filename TypeCasting.java.

5. In your command prompt, type javac TypeCasting.java and press Enter.

The compiler compiles your application and creates a .class file from it.

6. Type java TypeCasting and press Enter.

You see the results of each of the casts, as shown in Figure 5-7. The left side always shows the cast value, and the right side always shows the original value. Notice in particular that the double type, MyDbl, is at the limit of the precision it can provide. The number displayed as output is a little less than expected in the last decimal position.

9781118098783-fg0507.tif

Figure 5-7:

Notice that casting the double to a float compounds the error in the double. The small inaccuracy in the double is probably acceptable for many calculations, but the inaccuracy in the float is unusable. Because the values are somewhat close, this could actually end up as a subtle error in your code — one that could take a long time to find.

On the other hand, casting from a double to a long is probably acceptable as long as you can do without the decimal portion of the number. The integer portion of the output matches precisely.

It’s interesting to note that casting between a char and a long and between an int and a char seems to work just fine. As previously noted, the computer sees a number, not a character.

A worst case cast occurs when the application tries to convert a double to an int. In this case, the output isn’t even close. The numbers don’t match at all. This is the sort of cast that can cause significant problems in an application.

warning.eps Java allows even unusable casts when you specifically include one in your code. (The assumption here is that you know what you’re doing.) Because the code doesn’t provide any sort of an exception or compilation warning, this sort of error is extremely hard to find.

7. Compare the results in your list to the actual results shown in Figure 5-7.

Creating a mental picture of how a cast can affect the output of your application is essential. Improper casts can cause all kinds of terrifying problems in applications. Many developers encounter this sort of error but don’t recognize it until someone else points it out. Casts in code are always suspected points of failure, so always verify that a cast will actually produce the desired results.

practice_fmt.eps Try changing the values of the variables in the example to see how a difference in value will affect the outcome of the casts. For example, it might be interesting to see what happens when you change the value of MyInt to 650.

Using Relational and Conditional Operators

Relational and conditional operators attempt to ascertain the truth value — whether something is true or not — of an expression. The operation results in a Boolean output that helps an application make a decision. The most common relations are comparisons between two operands using the following operators:

· <: Less than

· <=: Less than or equal to

· ==: Equal

· >=: Greater than or equal to

· >: Greater than

· !=: Not equal

You’ll use these operators quite a bit as the book progresses. However, you’ve probably already used them as part of a math class in determining the truth value of an expression, and you’ll find that computers use them in the same way.

Computers also require some special operators for working with data in ways that humans understand intuitively. For example, a computer needs to know whether two variables are of the same type. These concepts are a little advanced, and you don’t need to fully understand them now, but the following sections provide an overview of them as preparation for future chapters.

Finally, a special conditional operator set is available. Chapter 4 discusses conditional statements, but this is a conditional operator, so you see it demonstrated in this chapter. The conditional operator outputs one of two values depending on the truth value of the operand expression you provide. This is one of the few ternary operators that Java uses.


LINGO

Ternary operators require three operands to function properly. In the case of the conditional operator, it uses one operand to hold an expression that evaluates to true or false, a second operand that defines what to do when the expression is true, and a third operand that defines what to do when the expression is false.


Checking value equality

One of the more important truth tasks that applications perform is to check the equality of the values in two variables. This chapter presents some tricky situations in determining the truth behind equality in later chapters, but for now, it’s important to concentrate on the operators themselves. The following exercise helps you understand how equality checks work.

Files needed: DetermineEquality.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.util.Scanner;

public class DetermineEquality
{
public static void main(String[] args)
{
// Create the scanner.
Scanner GetInt = new Scanner(System.in);

// Obtain the comparison values.
System.out.print("Type the first number: ");
int First = GetInt.nextInt();

System.out.print("Type the second number: ");
int Second = GetInt.nextInt();

// Determine the equality of the two values.
System.out.printf("It's %B that %d < %d%n",
(First < Second), First, Second);
System.out.printf("It's %B that %d <= %d%n",
(First <= Second), First, Second);
System.out.printf("It's %B that %d == %d%n",
(First == Second), First, Second);
System.out.printf("It's %B that %d >= %d%n",
(First >= Second), First, Second);
System.out.printf("It's %B that %d > %d%n",
(First > Second), First, Second);
System.out.printf("It's %B that %d != %d%n",
(First != Second), First, Second);
}
}

An important concept to grasp is that at least one of the checks performed by this example will be true. In fact, it’s more likely that two or more checks will be true.

To make this example a little easier to use, it relies on a scanner that allows you to input two integer values. Any two integer values will do.

After the application reads the two values from the keyboard into First and Second, it performs a comparison of the two values. Notice how the code uses parentheses to change the order of precedence for the check so that the result is Boolean. Otherwise, these checks wouldn’t work.

3. Save the code to disk using the filename DetermineEquality.java.

4. In your command prompt, type javac DetermineEquality.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java DetermineEquality and press Enter.

The application asks you to input the first number.

6. Type 1 and press Enter.

The application asks you to input the second number.

7. Type 2 and press Enter.

The application outputs the results of the checks, as shown in Figure 5-8. Notice that multiple checks are true. For example, 1 is indeed less than 2 — 1 is also less than or equal to 2. These two values are also not equal to each other. The test you use depends on what sort of information you’re trying to obtain.

9781118098783-fg0508.tif

Figure 5-8:

8. Perform Steps 5 through 7 using values of 2 and 2.

Notice how the output changes to reflect the different values.

practice_fmt.eps Try a range of values with the application to see how it reacts to different inputs. This application demonstrates how truth values work within the computer and will help you create better applications later in the book.

Performing a type comparison

The earlier “Casting one type to another” section of this chapter demonstrated how you can turn one type into another type. It also demonstrated that performing a cast can be a dangerous task at times because the cast may not produce the desired result. The following exercise demonstrates a technique you can use to determine the type of a variable. You can use this information to determine whether it’s safe to perform a cast, among other tasks that you’ll discover as the book progresses.

Files needed: CompareType.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

public class CompareType
{
public static void main(String[] args)
{
// Define a variable that's an object.
Integer MyInt = 22;

// Display the type of MyInt.
System.out.println(
"MyInt is of type " + MyInt.getClass());

// Check for the type of MyInt.
System.out.printf(
"It's %B that MyInt is of type Integer.%n",
(MyInt instanceof Integer));
}
}

Type is always associated with an object, so the example begins by creating a variable of type Integer named MyInt. The getClass() method always returns the class used to create the object. However, the easiest way to determine whether a variable is of a specific type is to use theinstanceof operator. In this case, the application determines whether MyInt is of type Integer.

3. Save the code to disk using the filename CompareType.java.

4. In your command prompt, type javac CompareType.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java CompareType and press Enter.

The example outputs the full name of the class used to create MyInt. It then shows the truth value of whether MyInt is an instance of type Integer, as shown in Figure 5-9.

9781118098783-fg0509.tif

Figure 5-9:

Performing a conditional evaluation

Java provides a special conditional evaluation operator that provides shorthand for the conditional statements that you’ll discover in Chapter 6. The conditional evaluation operator (?:) requires three operands. The first is an expression that outputs a Boolean value. The second is an output that’s invoked when the condition is true. The third is an output that’s invoked when the condition is false. The following exercise demonstrates how this works.

Files needed: ConditionalExpression.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.util.Scanner;

public class ConditionalExpression
{
public static void main(String[] args)
{
// Create the scanner.
Scanner GetAnswer = new Scanner(System.in);

// Ask the user a question.
System.out.print("Do you love the color blue? ");
boolean Answer = GetAnswer.nextBoolean();

// Determine which output to provide.
String Result =
Answer ? "You love blue!" : "You like orange.";

// Display the result.
System.out.println(Result);
}
}

The example begins by asking the user a simple question, “Do you love the color blue?” The user needs to type true or false, depending on personal taste. The application assigns this answer to Answer. It then uses Answer as the first operand to the conditional evaluation operator. The second and third operands are strings in this case. Depending on the user’s answer, the String variable, Result, can contain one of two values. The application ends by displaying Result onscreen.

3. Save the code to disk using the filename ConditionalExpression.java.

4. In your command prompt, type javac ConditionalExpression.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java ConditionalExpression and press Enter.

The application asks the question.

6. Type true and press Enter.

The application tells you that you love the color blue.

7. Type java ConditionalExpression and press Enter.

The application asks the question.

8. Type false and press Enter.

The application tells you that you like orange instead. Figure 5-10 shows how the conditional operator performs its work.

9781118098783-fg0510.tif

Figure 5-10:

Understanding Operator Precedence

This chapter has discussed operator precedence quite a bit. It’s essential to know how Java interprets the symbols you use to perform specific operations and in what order it interprets them. Otherwise, you could write an application with one result in mind and receive an entirely different result (as demonstrated by several of the examples in this chapter). Whenever you have a doubt as to how Java will interpret a symbol you use, you can rely on the information in Table 5-2 to help you.

0502
0502a
0502b

The Priority column of Table 5-2 is probably the most important because it defines the strict order in which Java interprets the symbols displayed in the Operators column. An operator higher in the table always takes precedence over an operator that’s lower in the table.

The Associativity column is also important. In most cases, Java interprets symbols from left to right, which means that the symbols have a left associativity. However, in a few cases, the operator works from right to left. For example, when using the = operator, Java interprets the information to the right of the operator first, and it then assigns the result to the operand on the left of the operator. So the flow is from right to left, which makes the = operator right associative.


LINGO

Associativity is a math term that defines how elements in a binary operation interact. In most cases, Java uses left associativity. It begins from the left side of a group of operators and works toward the right side. For example, if you have 1 + 2 + 3 as an equation, Java adds 1 and 2 first, then adds 3 to the result of the first operation. You can control associativity by using parenthesis. The article at http://math.about.com/od/prealgebra/a/associative.htm provides more information on this topic.


summingup_fmt.eps Summing Up

Here are the key points you learned about in this chapter:

· Most applications use simple assignments to initialize variables.

· You must initialize a variable before you can modify it using a combined assignment operator.

· Combined assignment operators perform an operation on the variable by using a value to the right of the operator as input, and they then store the result in the variable.

· When performing math-related tasks, you must consider the order in which the values appear and the operations performed on them.

· Incrementing and decrementing are often used to keep track of the count of something.

· Negation produces the negative value of a number, while a bitwise Not produces the reversal of the bits within the number.

· A Boolean Not turns a true value into a false value, and vice versa.

· Use the new operator to create as many instances of an object as required by an application.

· Casting makes it possible to turn one variable type into another.

· Casting incorrectly can have serious side effects that could make the output of your application unusable.

· Relational and conditional evaluation operators make it possible to determine the truth value of an expression.

· It’s possible that more than one relational operator will be true for a given expression.

· At least one relational operator will provide an output of true for a given expression.

· Determining the type of a variable can help you overcome issues with improper casting.

· The conditional evaluation operator is one of the few ternary operators provided by Java.

· Java always executes operations defined by operators with a higher precedence first.

· The associativity of an operator determines whether Java works with the right side or the left side first.

Try-it-yourself lab

For more practice with the features covered in this chapter, try the following exercise on your own:

1. Open the ComplexMath application.

2. Change the application code to work with double values.

Use floating point values such as 2.3 or 3.5 to test the results.

3. Go through the code you create to determine the expected output.

Track each line and provide a line-by-line summary of the results you expect to see.

4. Compile the application.

5. Run the application.

6. View the results and match them to your expected results.

7. Perform Steps 2 through 7 for BigDecimal variables.

Each of the primitive or object types should react as expected to the math operations you create. Math is math. The kind of variable you use simply defines the storage container, not how the math will work.

Know this tech talk

· associativity: The order in which Java performs binary operations.

· binary operator: An operator that requires two operands to function. The addition operation, as specified by the + operator, is an example of a binary operator.

· bitwise: The act of modifying a value one bit at a time, rather than acting on the value as a whole.

· class: A blueprint written in code for creating objects. A class can include methods, properties, and events. The class defines specific ways to manipulate data in a safe manner.

· grouping: The act of using parentheses to show the preferred order of completing math tasks, rather than relying on the default order.

· negation: The act of setting a value to its negative equivalent. This means that a positive value becomes a negative value, and a negative value becomes positive. A value of 2 becomes –2, and a value of –2 becomes 2.

· object: An instance of a class created using the new operator.

· operand: The variable or constant used with an operator to produce a result from an operation. For example, when looking at A + B, A and B are both operands, + is the operator, and addition is the operation.

· operator: A special symbol or symbol set that performs a predefined task with a value within a variable — either a primitive type or an object. In some cases, operators change the value, but in others they simply perform a comparison and provide the result as output.

· precedence: The order in which Java interacts with operators when an equation or expression contains more than one operator. For example, Java always performs multiplication before it performs addition. Most of the rules of precedence are the same as those used by mathematicians.

· ternary operator: An operator that requires three operands to function. For example, the conditional operator requires three operands: the conditional expression, a true output, and a false output.

· unary operator: An operator that performs an operation on a single operand. For example, B++ is an example of a unary operator where B is the operand and ++ is the operator for an increment operation.