• No results found

Operators, Conditionals, and Loops

In document Java 8 Programming Black Book (Page 113-119)

If you need an immediate solution to: See page:

Operator Precedence 81

Incrementing and Decrementing (++ and --) 82

Unary NOT (~ And !) 83

Multiplication and Division (* and /) 83

Modulus (%) 83

Addition and Subtraction (+ and -) 84

Shift Operators (>>, >>>, and <<) 84

Relational Operators (>, >=, <, <=, ==, and !=) 85

Bitwise and Bitwise Logical AND, XOR, and OR (&, ^, and /) 85

Logical (&& and ||) 87

The if-then-else Operator (?:) 87

Assignment Operators (= and [operator]=) 88

Using the Math Class 89

Changes in the Math Class 90

Class StrictMath 90

Comparing Strings 91

The if Statement 92

The else Statement 92

Nested if Statement 93

The if-else Ladders 93

The switch Statement 93

Using Strings in switch Statement 95

The while Loop 95

The do-while Loop 96

If you need an immediate solution to: See page:

The for Loop 97

The for-each Loop 99

Supporting for-each in Your Own Class 101

Nested Loops 102

Using the break Statement 103

Using the continue Statement 103

In Depth

In Depth

In the previous chapter, we took a look at how Java handles data in basic ways. In this chapter, we’ll start doing something with that data as we examine the Java operators, conditionals, and loops.

Storing a lot of data in your program is fine; but unless you do something with it, it’s not of much use. Using operators, you can manipulate your data—add, subtract, divide, multiply, and more. With conditionals, you can alter a program’s flow by testing the values of your data items. Using loops, you can iterate over all data items in a set, such as an array, working with each data item in succession in an easy way. These represent the next step up in programming power from the previous chapter, and we’ll discuss all three of these programming topics here.

Operators

Java provides a very easy way to work with data in a program. Like most languages, it provides a number of built-in operators. For example, if one variable contains value 10 and another variable contains 20, the variables can be added using the + operator, as shown in this code:

public class App {

public static void main(String[] args) { int operand1 = 20, operand2 = 10, sum;

sum=operand1+operand2;

System.out.println(operand1 + " + " +operand2 + " = " + sum); } }

Here’s the result of this code:

C:\>java App 20 + 10 = 30

So, what operators does Java offer? Here’s a list of all of them:

--(decrement)

- (subtraction)

! (logical unary NOT)

!= (not equal to)

% (modulus)

%= (modulus assignment)

& (logical AND)

&& (short-circuit AND)

&= (bitwise AND assignment)

* (multiplication)

*= (multiplication assignment)

/ (division)

/= (division assignment)

?: (ternary if-then-else)

^ (logical XOR)

^= (bitwise XOR assignment)

| (logical OR)

|| (short-circuit OR)

|= (bitwise OR assignment)

~ (bitwise unary NOT)

+ (addition)

++ (increment)

+= (addition assignment)

< (less than)

<< (shift left)

<<= (shift left assignment)

<= (less than or equal to)

= (assignment)

-= (subtraction assignment)

== (equal to)

> (greater than)

>= (greater than or equal to)

>> (shift right)

>>= (shift right assignment)

>>> (shift right with zero fill)

>>>= (shift right zero fill assignment)

You’ll see these operators at work in this chapter. Operators that take one operand are called unary operators.

Those that take two operands—for example, addition (a + b)—are called binary operators. There’s even an operator,?:, that takes three operands—the ternary operator.

Besides the built-in operators, we’ll also cover the Java Math class in this chapter, which allows you to add a lot more math power to your programs, including exponentiation (unlike other languages, Java has no built-in exponentiation operator), logarithms, trigonometric functions, and more. StrictMath classes (you can find more about these classes at http://java.sun.com/javase/8/docs/api/) ensure that the same mathematical precision is used no matter what machine your program is running on.

Conditionals

The next step up from using simple operators is to use conditional statements, also called branching statements, in your code. You use conditional statements to make decisions based on the value of your data and make the flow of the program go in different directions accordingly.

Say you wanted to report on the weather; and if it’s less than 80 degrees Fahrenheit, you want to print out a message that reads “It’s not too hot”. You can do this by checking the current temperature with a Java if statement that compares the value in the variable temperature to 80; and if that value is under 80, it prints out your message:

public class App {

public static void main(String[] args) { int temperature = 73;

if (temperature < 80) { System.out.println("It's not too hot."); } }

}

The if statement tests whether its condition (the part that appears in the parentheses) is true, which in this case is temperature < 80. The Java < (less than) relational operator is used to test whether the value in temperature is less than 80. Because we have set that value to 73, the if statement’s condition is true, which means the code in the body of the if statement will be executed. Here’s the result of this code:

C:\>java App It's not too hot.

You can make if statements more complex by adding else clauses. These clauses must follow the if statement and are executed when the if statement condition turns out to be false. Here’s an example:

public class App {

public static void main(String[] args) {

In Depth int temperature = 73;

if (temperature < 80) { System.out.println("It's not too hot!"); } else { System.out.println("It's too hot!"); }

} }

As you’ll see, there are other conditional statements as well, and we’ll put them to work in this chapter, giving the Java syntax a thorough workout.

Loops

Loops enable you to execute a set of statements for a number of times. For example, you may want to print your name five times on the console or calculate the sum of the first hundred natural numbers; in such cases, loops are used. The loop execution depends upon a loop condition. The statements inside a loop are executed as long as the loop condition remains true. Generally, the condition involves a loop index that gets incremented or decremented every time the loop executes.

The general syntax of a for loop is as follows:

for (initialization_expression; test_conditon; iteration_expression) { statement;

}

Note that the statement that makes up the body of the for loop can be a compound statement, which means it can be made up of several single statements enclosed within curly braces.

You can initialize the loop index with initialization expression, provide a test condition for loop termination, and modify loop index value in iteration expression. Note that we are declaring and initializing the loop index at the same time. Isn’t it similar to C++? Yes, C++ also allows you to simultaneously declare and initialize the loop index. A simple example of a for loop which prints Kogent five times is as follows:

public class App {

public static void main(String[] args) {

for (int loop_index = 1; loop_index < 6; loop_index++){

System.out.println("Kogent"); } } }

This code prints Kogent, using loop_index, which starts at 1 and is steadily incremented each time through the loop by 1 till the loop test condition evaluates true. The result of this code is:

C:\>java App Kogent Kogent Kogent Kogent Kogent

There are statements that cause an unconditional jump to other statement in the code. Such statements are called jump statements. These are mainly used to interrupt the control flow within the switch statements and loops.

There are three jump statements supported by Java: break, continue, and return. Generally, the break statement allows exit from a loop or switch before the execution completes, and the continue statement takes control to the beginning of a loop or switch. For the return statement, please see the topic “Returning Values from Methods” in Chapter 4.

Here’s a simple example of the break statement to make things clearer. In this case, the loop index is initialized with value 1 and is incremented by 1 for every execution of the loop. In the code, the test condition states that the loop should execute till the loop index is less than 7:

public class App {

public static void main(String[] args) {

for (int loop_index = 1; loop_index < 7; loop_index++){

if(loop_index==5) break;

System.out.println(loop_index); }

System.out.println("Kogent"); }

}

This code prints the value of loop index until it becomes 5. Then the break statement takes control out of the loop and Kogent gets printed. The result of this code is:

C:\>java App 1

2 3 4 Kogent

As you can see, for loop is a powerful one; in fact, it’s just one of the many topics coming up in the “Immediate Solutions” section. It’s now time to start by using operators, conditional statements, and loops.

Immediate Solutions

Immediate Solutions

In document Java 8 Programming Black Book (Page 113-119)

Related documents