JAVA PROGRAMMING

OPERATORS AND CONTROL STATEMENTS

Operators:

Java provides a rich operator environment. Most of its operators can be divided into the following four groups: arithmetic, bitwise, relational and logical. Java also defines some additional operators that handle special situations.

Arithmetic Operators:

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators

Operator

Result

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Modulus

++

Increment

+=

Addition assignment

-=

Subtraction assignment

*=

Multiplication assignment

/=

Division assignment

%=

Modulus assignment

--

Decrement</TD< tr>

The operands of the arithmetic operators must be of a numeric type. You cannot use them on Boolean types, but you can use them on char types, since the char type in Java is essentially, a subset of int.

//Demonstrate the basic arithmetic operators.
class BasicMath {
public static void main(String args[]) {
System.out.println("Integer Arithmetic");
int a = 1+1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a +"\n b = " + b+"\n c = " + c);
System.out.println(" d = " + d +"\n e =" + e);// '\n' escape sequence for
//newline
// arithmetic using doubles
System.out.println("\n Floating Point Arithmetic");
double da = 1+1;
double dd = da * 3;
double dc =db / 4;
double dd = dc - da;
double de = -dd;
System.out.println("da = " + da+"\n db = " + db+"\n dc = " + dc);
System.out.println(" dd = " + dd+" de =" + de);
}
}

The Modulus Operator:

The modulus operator, % returns the remainder of a division operation. It can be applied to floating point types as well as integer types. The following example program demonstrates the %:

// Demonstrate the % operator.
class Modulus {
public static void main(String args[] ){
int x = 42;
double y = 42.3;
System.out.println("x mod 10 = " + x % 10) ;
System.out.println("y mod 10 = " + y % 10) ;
}
}


When you execute this program you will get the following output:
x mod 10 = 2
y mod 10 = 2.299999999999997

Arithmetic Assignment Operators:

Java provides special operators that can be used to combine an arithmetic operation with an assignment. As you probably know, statements like the following are quite common in programming:

a = a + 4 ; can be rewritten as a + =4;

This version uses the += assignment operator. Both statements perform the same action: they increase the value of a by 4.

There are assignment operators for all of the arithmetic, binary operators.

Increment and Decrement:

The + + and - - are Java's increment and decrement operators. As you will see, they have some special properties that make them quite interesting. The increment operator increases its operand by one. For example, this statement:

x = x + 1; can be written as x ++;
Similarly, this statement:
x = x -1; is equivalent to x --;

The Bitwise Operators:

Java defines several bit wise operators that can be applied to the integer types, long, int, short, char, and byte. These operators act upon the individual bits of their operands. They are summarized in the following table.

          Operator                                                     Result
               ~                                            Bitwise unary NOT
               &                                           Bitwise AND
                |                                             Bitwise OR
               ^                                            Bitwise exclusive OR
              >>                                         Shift right
             <<                                         Shift left
              &=                                         Bitwise AND assignment
              |=                                           Bitwise OR assignment
              ^=                                         Bitwise exclusive OR assignment
                                                                         Bitwise exclusive OR assignment
              "=                                          Shift right assignment
              =                                         Shift right zero fill assignment
                   "=                                         Shift left assignment
 

It is useful to know how Java stores integer values and how it represents negative numbers. Binary numbers of varying bit widths represents all of the integer types. For example, the byte value for 42 in binary is 00101010, where each position represents a power of two, starting with 2 0 at the rightmost bit. The next position to the left would be2 1, 2, continuing towards the left with 2 2,or 4, then 8, 16, 32, and so on. So 42 has 1 bit set at positions 1,3, and 5 (counting from 0 at the right); thus 42 is the sum of 2 1 + 2 3 + 2 5, which is 2+ 8 + 32.

Relational Operators:

 
               Operator                               Result
               = =                         Equal to
               !=                           Not equal to
               >, > =                     Greater than, Greater than or equal to
               <, < =                     Less than, Less than or equal to
 

The outcome of these operations is a boolean value. The relational operators are most frequently used in the expressions that control the 'if' statement and the various loop statements. As stated, the result produced by a relational operator is a boolean value. For example, the following code fragment is perfectly valid:

 
               int a = 4;
               int b= 1;
               boolean c = a < b;

In this case, the result of a < b (which is false) is stored in c.

 

Boolean Logical Operators:

The boolean logical operators shown here operate only on Boolean operands. All of the binary logical operators combine two boolean values to form a resultant boolean value.

Operator

 Result

 &

 |

^

||

&&

!

 & =

 | =

 ^ =

= =

 ! =

 ?:

 Logical AND

Logical OR

Logical XOR

Short-circuit OR

Short-circuit AND

Logical unary NOT

AND assignment

OR assignment

XOR assignment

Equal to

Not equal to

 Ternary if-then-else

The logical Boolean operators, &, |, and ^, operate on Boolean values in the same way that they operate on the bits of an integer. The logical! Operator inverts the Boolean state:! true = = false and !false = = true.

// Demonstrate the boolean logical operators.
class BoolLogic {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a^ b;
boolean f = (!a & b) | (a & !b) ;
boolean g =!a;
System.out.println(" a = " + a +" \n b = " + b) ;
System.out.println(" a | b = " + c +"\n a & b = " + d) ;
System.out.println(" a^b = " + e +"\n !a & b | a & !b = " + f) ;
System.out.println(" !a = " + g) ;
}
}

After running this program, you will see that the same logical rules apply to boolean values as they did to bits. As you can see from the following output, the string representation of a Java boolean value is one of the literal values true or false:

a = true
b = false
a | b = true
a & b = false
a ^ b = true
a & b | a & !b = true
!a = false

The Assignment Operator:

The assignment operator is the single equal sign, =. The assignment operator works in Java much as it does in any other computer language. It has this general form:

var = expression;

Here, the type of var must be compatible with the type of expression.

int x,y,z;
x =y =z = 100; // set x, y, and z to 100

This fragment sets the variables x, y, and z to 100 using a single statement. This works because the = is an operator that yields the value of the right-hand expression. Thus, the value of z = 100 is 100, which is then assigned to y, which in turn is assigned to x. Using a "chain of assignment" is an easy way to set a group of variables to a common value.

The '?'Operator:

Java includes a special ternary (three - way) operator that can replace certain types of if-then-else statements. The ? has this general form:

Expression1 ? expression2:expression3

Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ? operation is that of the expression evaluated. Both expression2 and expression3 are required to return the same type, which can't be void.


Here is an example of the way in which '?' is employed,

Consider A=10, B=20;
Now consider the expression A < B ? A : B;
The resulting outcome will be the value of A (that is, 10)

Operator Precedence:

Table below shows the order of precedence for Java operators, from highest to lowest. Notice that the first row shows items that you may not normally think of as operators: parentheses, square brackets, and the dot operator. Parentheses are used to alter the precedence of an operation. As you know from the previous chapter, the square brackets provide array indexing. The dot operator is used to deference objects. Parentheses raise the precedence of the operations that are inside them. This is often necessary to obtain the result you desire.

Table: The Precedence of the Java Operators

Highest

( )

[ ]

 

 

++

--

~

!

*

/

%

 

+

-

 

 

"

>>>

"

 

>

>=

<

<=

==

!=

 

 

&

 

 

 

^

 

 

 

|

 

 

 

&&

 

 

 

||

 

 

 

?:

 

 

 

=

op=

 

 

Lowest

Java's Selection Statements:

A programming language uses control statement to cause the flow of execution to advance and branch based on changes to the state of a program. Java's program control statements can be put into the following categories: selection, iteration, and jump. Selection statements allow your program to choose different paths of execution based upon the outcome of an expression or the state of a variable. Iteration statements enable program execution to repeat one or more statements (that is, iteration statements form loops). Jump statements allow your program to execute in a non-linear fashion.

Java supports two selection statements: if and switch. These statements allow you to control the flow of your program's execution based upon conditions known only during run time. If your background in programming does not include C/C++, you will be pleasantly surprised by the power and flexibility contained in these two statements.

if: The if statement is Java's conditional branch statement. It can be used to route program execution through two different paths. Here is the general form of the if statement

if (condition) statement1;
        else statement2;

Here, each statement may be a single statement or a compound statement enclosed in curly braces (that is, a block). The condition is any expression that returns a boolean value. The else clause is optional.

The if works like this: If the condition is true, then statement is executed. Otherwise, statement2 (if it exists) is executed. In no case will both statements be executed. For example, consider the following:

int a, b;
if(a < b) a = 0
else b = 0;

if, else Statements: The basic syntax for if, else statements is:

if (boolean expression) {
Statement or block;
} else {
Statement or block;
}

Nested ifs: A nested if is an 'if' statement that is the target of another if or else.

if(i == 10) {
if (j < 20) a", b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
} else a = d; // this else refers to if (i = =10)

As the comments indicate, the final else is not associated with if(j<20), because it is not in the same block (even though it is the nearest if without an else). Rather, the final else is associated with if(i==10). The inner else refers to if(k>100), because it is the closest if within the same block.

The if-else-if Ladder:

A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder. It looks like this:

 
                           if(condition) statement;
                                           else if (condition )
                                                        statement;
                                            else if(condition)
                                                             statement;
                                                                            .
                                                                            .
                                                                            .
                                                             else
                                                                            statement;

The 'if' statements are executed from the top down. As soon as one of the conditions controlling the 'if' is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. The final else acts as a default condition; that is, if all other conditional tests fail, then the last else statement is performed. If there is no final else and all other conditions are false, then no action will take place.

'switch' statement: The switch statement syntax is

switch (expr1) {
case constant2:
statements;
break;
case constant3:
statements;
break;
default:
statements;
break;
}

The optional default label is used to specify the code segment to be executed when the value of the variable or expression cannot match any of the case values. If there is no break statement as the last statement in the code segment for a certain case, the execution continues into the code segment for the next case without checking the case expression's value.

Nested switch Statements:

You can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines its own block, no conflicts arise between the case constants in the inner switch and those in the outer switch. For example, the following fragment is perfectly valid:

switch(count) {
case 1:
switch,(target) {         // nested switch
case 0:
System.out.println("target is zero");
break;
case 1:                      // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2:          // .....

Here, the case 1: statement in the inner switch does not conflict with the case 1: statement in the outer switch. The count variable is only compared with the list of cases at the outer level. If count is I, then target is compared with the inner list cases. In summary, there are three important features of the switch statement to note:

  • The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of Boolean expression. That is, the switch looks only for a match between the value of the expression and one of its case constants.
  • No two case constants in the same switch can have identical values. Of course, a switch statement enclosed by an outer switch can have case constants in common.
  • switch statement is usually more efficient than a set of nested ifs.

The last point is particularly interesting because it gives insight into how the Java compiler works. When it compiles a switch statement, the Java compiler will inspect each of the case constants and create a "jump table" that it will use for selecting the path of execution depending on the value of the expression. Therefore, if you need to select among a large group of values, a switch statement will run much faster than the equivalent logic coded using a sequence of if-else's. The compiler can do this because it knows that the case constants are all the same type and simply must be compared for equality with the switch expression. The compiler has no such knowledge of a long list of if expressions.

Iteration Statements:

Java's iteration statements are for, while, and do-while. These statements create what we commonly call loops. As you probably know, a loop repeatedly executes the same set of instructions until a termination condition is met. As you will see, Java has a loop to fit any programming need.

While: The while loop is Java's most fundamental looping statement. It repeats a statement or block while its controlling expression is true. Here is its general form:

while(condition) {
/ / body of loop
}

The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control passes to the next line of code immediately following the loop. The curly braces are unnecessary if only a single statement is being repeated.

Here is a while loop that counts down from 10, printing exactly ten lines of "tick":

// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick" + n);
n--; }
}
}

do-while: As you just saw, if the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a while loop at least once, even if the conditional expression is false to begin with. Java supplies a loop that does just that: the do-while. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is

do {
// body of loop
} while (condition);

Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java's loops, condition must be a Boolean expression.

// Demonstrate the do-while loop.
class DoWhile {
public static void main{String args[] ) {
int n = 10;
do {
System.out.println("tick" + n);
n--;
} while(n > 0);
}
}


for: It is a powerful and versatile construct. Here is the general form of the 'for' statement.

for (initialization; condition; iteration) {
//body
}

 If only one statement is being repeated, there is no need for the curly braces. The 'for' loop operates, as follows. When the loop first starts, the initialization portion of the loop is executed. Generally, this is an expression that sets the value of the loop control variable.

It is important to understand that the initialization expression is only executed once. Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop control against a target value. Next, the iteration portion of the loop is executed. This is usually an expression that increments or decrements the loop control variable.

Here is a version of the "tick" program that uses a for loop:

// Demonstrate the for loop
class ForTick {
public static void main(String agrs[]) {
int n;
for(n =10; n>0; n --)
System.out.println("tick " + n);
}
}

 

Using the Comma: There will be times when you will want to include more than one statement in the initialization and iteration portions of the for loop. For example, consider the loop in the following program:

//Using the comma
class Comma {
public static void main(String args [ ] ) {
int a, b;
for(a=l, b=4; a
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}

 

Nested loops: Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside another. For example, here is a program that nests for loops:

//Loops may be nested.
class nested {
public static void main(String args [ ] ) {
int a, b;
for(a=0; a<10; a++) {
for(b=a; b<10; b++)
System.out.println(" . ");
System.out.println( );
}
}
}


You can use the following statements to further control loop statements:

  • break [label];
  • continue [label];
  • label : statement; // where statement should be no long.

The break statement is used to exit from switch statements, and labelled blocks prematurely.

The continue statement is used to skip over and jump to the loop body. The label statement identifies any valid statement to which a control needs to be transferred. It is used to identify a compound state that has a loop construct.

Special Loop Flow Control: The break, continue and label statements can be used follows:

  • the break statement
    do {
          statement or block;
          if (condition is true)
              break;
        } while (boolean expression);
  • The continue statement
    do {
           statement or block;
           if (boolean expression)
            continue;
      } while (boolean expression);
  • The break statement with a label named loop
    do{
               statement;
              do {
                   statement ;
                   statement ;
                    if (boolean expression)
                            break;
                  } while (boolean expression);
                 statement ;
    } while (boolean expression);

return : The last control statement is return. The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method. As such, it is categorized as a jump statement. At any time in a method the return statement can be used to cause execution to branch back to the caller of the method. Thus, the return statement immediately terminates the method in which it is executed. Here, return causes execution to return to the Java run-time system, since it is the run-time system that calls main( ).

// Demonstrate return.
class Return {
public static void main(String args[ ]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return;
System.out.println("This won't execute.");
}
}

 

 

 

  HOME

<<PREVIOUS             NEXT>>

Want Easy lessons and exercises!! Then search here:

Google
Web www.poombatta.com



© poombatta.com