Java Operators and Control Statements
Java Operators and Control Statements
Control Statements: Java’s Selection Statements (if, The Traditional switch), Iteration
Statements (while, do-while, for, The For-Each Version of the for Loop, Local Variable Type
Inference in a for Loop, Nested Loops), Jump Statements (Using break, Using continue, return).
Textbook 1: Ch 4, Ch 5
TOPIC: OPERATORS
Operators are symbols that perform special operations on one, two, or three operands and return
a result.
1. Arithmetic Operators:
● Arithmetic operators are used in mathematical expressions.
● The operands of the arithmetic operators must be of numeric type.
● It can’t be used on boolean type.
● It can be used on char type as char type in Java is a subset of int.
● The various arithmetic operators are shown in the table below
[Link](“da = “ + da);
[Link](“db = “ + db);
[Link](“dc = “ + dc);
[Link](“dd = “ + dd);
[Link](“de = “ + de);
}
}
Output:
Integer Arithmetic
a=2
b=6
c=1
d = -1
e=1
Floating point arithmetic
da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5
// Demo of % operator
class Modulus {
public static void main(String args[ ]) {
int x = 42;
double y = 42.25;
Output:
x mod 10 = 2
y mod 10 = 2.25
forms.
○ 2. They are implemented more efficiently by the Java run-time system than their
equivalent long forms.
● Hence professionally written Java programs use compound assignment operators.
● The following program illustrates several op= assignments in action
a += 5;
b *= 4;
c += a * b;
c %= 6;
[Link](“a = “ + a);
[Link](“b = “ + b);
[Link](“c = “ + c);
}
}
Output:
a=6
b=8
c=3
● In the postfix form, the previous value is obtained for use in the expression and then the
operand is modified.
● Prefix example, Consider the statements -
◦ x = 42;
◦ y = ++x;
◦ Here, the increment occurs before x is assigned to y. So y = 43 and x = 43. Thus, the
above line is equivalent to following two statements
◦ x = x + 1;
◦ y = x;
● Postfix example: Consider the statements -
◦ x = 42;
◦ y = x++;
◦ Here, the value of x is obtained before the increment operator is executed. So y = 42
and x = 43. Thus, the above line is equivalent to following two statement -
◦ y = x;
◦ x = x + 1;
● The following program demonstrates the increment operator
// class IncDec {
public static void main (String args [ ]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d= a++;
c++;
[Link](“a = “ + a);
[Link](“b = “ + b);
[Link](“c = “ + c);
[Link](“d = “ + d);
}
}
Output:
a=2
b=3
c=4
d=1
int i = 11;
i = i++ + ++i;
[Link](i);
}
}
Answer: 24
2. Program 2
Answer :
a=13
b=24
c=103
3. Program 3
Answer : 0
4. Program 4
[Link]("i="+i);
[Link]("j="+j);
[Link]("k="+k);
[Link]("m="+m);
}
}
Answer :
i=0
j=1
k=2
m=-4
5. Program 5
Answer : 0
6. Program 6
[Link]("i="+i);
[Link]("j="+j);
[Link]("k="+k);
}
}
Answer :
i=19
j=29
k=-20
● Bitwise operators manipulate the bits within an integer. So we need to know how Java
stores integer values and how it represents negative numbers.
● Binary numbers of varying bit widths represent all the integer types.
● For example, the byte value of 42 in binary is 00101010– byte size is 8 bits,
MSB LSB
0 0 1 0 1 0 1 0
27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1
32 + 8 + 2 = 42
+42
0 0 1 0 1 0 1 0
Invert (change 1’s to 0’s and vice versa)
1 1 0 1 0 1 0 1
Add 1 +1
we get -42
1 1 0 1 0 1 1 0
● When we consider the zero crossing, byte value, zero is represented by 0000 0000.
● 1’s complement (inverting all the bits) creates 1111 1111, which creates negative zero.
● As negative zero is invalid in math. The problem is solved by using two’s complement to
represent negative numbers. By adding 1 to 1’s complement of zero, we get 1 0000 0000.
● The 1 bit is produced too far to the left, resulting in the desired behavior, where -0 is same
as 0. The same principle applies for all Java’s integer types.
0
0 0 0 0 0 0 0 0
Invert (change 1’s t 0’s and vice versa), we get, -0
1 1 1 1 1 1 1 1
Which is not same as zero. Therefore, Add 1 and we get
MSB LSB
1 0 0 0 0 0 0 0 0
-0 bit pattern is same as zero.
1 0 1 0 1 0
1 1 1 1 0 0
x = 42 0 0 1 0 1 0 1 0 1 0
~x 1 1 0 1 0 1 0 1 0 1 = -43
so, y = -43
int z = x & y;
00101010 42
&00001111 15
00001010 10
so z = 10
● Each left shift doubles the original value. But if we shift a 1 into the high-order position (
bit 31 or 63) the value will become negative.
● An example program to show the left shift multiplies the value by 2
// class MultByTwo {
public static void main(String args[ ] ) {
int i;
int num = 0xFFFF FFE;
for (i = 0; i < 4 ; i++) {
num = num << 1;
[Link](num);
}
}
}
Output:
536870908
1073741816
2147483632
-32
num=0xFFFF FFE => 0000 1111 1111 1111 1111 1111 1111 1110
i=0; num = num << 1 = 536870908 => 0001 1111 1111 1111 1111 1111 1111 1100
i=1; num = num << 1 = 1073741816 => 0011 1111 1111 1111 1111 1111 1111 1000
i=2; num = num << 1 = 2147483632 => 0111 1111 1111 1111 1111 1111 1111 0000
i=3; num = num << 1 = -32 => 1111 1111 1111 1111 1111 1111 1110 0000
● When the bits are shifted off (low order bits) those bits are lost.
● Example:
◦ int a = 35;
◦ a = a >> 2; // a still contains 8
● Each time we shift a value to the right, it divides that value by 2 and discards any
remainder.
1111 1111 1111 1111 1111 1111 1111 1111 -1 in binary as an int
>>> 24
0000 0000 0000 0000 0000 0000 1111 1111 255 in binary as an int
● The >>> operator is meaningful for 32-bit and 64-bit values. As smaller values are
automatically promoted to int in expressions.
● For unsigned right shift on a byte value zero filling must begin at bit 7. But this is not the
case, since it is a 32-bit value that is actually being shifted.
class OpBitEquals {
public static void main(String args [ ]) {
int a =1;
int b = 2;
int c = 3;
a |= 4;
b >>= 1;
c <<= 1;
a ^= c;
[Link](“a = “ a);
[Link](“b = “ b);
[Link](“c = “ c);
}
}
Output:
a=3
b=1
c=6
Relational Operators:
● The relational operators determine the relationship between the two operands.
● They determine equality and order.
● The relational operators are
● Java does not define true and false in the same way as C/C++. In C/C++,
true is any nonzero value and false is zero.
● In Java, true and false are non numeric values that do not relate to zero or
nonzero. Therefore to test for zero and non-zero, we must explicitly employ
one or more of the relational operators.
[Link](“ a = “ + a);
[Link](“ b = “ + b);
[Link](“ a | b = “ + c);
[Link](“ a & b = “ + d);
[Link](“ a ^ b = “ + e);
[Link](“!a&b | a& !b= “ + f);
}
}
Output:
a = true
b = false
a | b = true
a & b = false
a^b = true
a&b | a&!b = true
Programming in Java Page 16
Programming in Java Module 2: Operators and control statements
!a = false
The ?: Operator:
● Java includes a ternary (three-way) operator that can replace certain types of
if-then-else-statements.
● The operator is ?:
● General form:
expression1 ? Expression2 : expression3
● expression1 can be any expression that evaluates to a boolean value.
● If expression1 is true then expression2 is evaluated, else, expression3 is
evaluated.
● Example:
ratio = denom == 0 ? 0 : num /denom;
● if denom equals zero, then the expression between the question mark and the
colon is evaluated and used as the value of the entire ? Expression.
● If denom is not equal to zero, then the expression after the colon is evaluated
and used for the value of the entire ? Expression.
● The result is then assigned to ratio.
● Example program
class Ternary {
public static void main(String args[ ]) {
int i, k;
i = 10;
k = i < 0 ? -i : i;
[Link](“Absolute value of “ + i + “ is “ + k);
i = -10;
k = i < 0 ? -i : i;
[Link](“Absolute value of “ + i + “ is “ + k);
}
}
Output:
Absolute value of 10 is 10
Absolute value of -10 is 10
Output:
Enter all three numbers:
30
0
-3
Largest Number:30
Operator Precedence:
● The following table shows the order of precedence for Java operators from
highest to lowest.
Highest
() [] .
++ -- ~ !
* / %
+ -
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
= op=
Lowest
Java’s program control statements can be put into the following categories:
1. Selection
2, Iteration
3. Jump
1. Selection – selection statements allow program to choose different paths of execution based on
the outcome of an expression or the state of a variable.
2. Iteration – Iteration statements enable program execution to repeat one or more statements.
The if Statement:
● The if statement is Java’s conditional branch statement. It can be used to
route program execution through two different paths.
● General form
if (condition) statement1;
else statement2;
● Each statement may be a single statement or a compound statement enclosed
in curly braces. 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 statement1 is executed
otherwise statement2 (if it exists) is executed. In no case will both
statements be executed.
● Example:
int a, b;
if (a<b)
a=0;
else
b=0;
● If a is less than b, then a is set to zero. Otherwise, b is set to zero. In
no case are they both set to zero.
● Most often, the expression used to control the if will involves relational
operators. It is possible to control the if using a single boolean variable,
as shown in this code fragment:
boolean dataAvailable;
//...
if (dataAvailable)
ProcessData();
else
waitForMoreData();
● Remember, only one statement can appear directly after the if or the
else. If you want to include more statements, you’ll need to create a
block, as in this fragment:
int bytesAvailable;
// ...
if (bytesAvailable > 0) {
ProcessData();
bytesAvailable -= n;
} else
waitForMoreData();
General form:
if (condition)
statement;
else if (condition)
statement;
else if (condition)
statement;
.
.
.
else
statement;
Here is a program that uses an if-else-if ladder to determine which season a particular
month is in.
// Demonstrate if-else-if statements.
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
[Link]("April is in the " + season + ".");
}
}
Here is the output produced by the program:
April is in the Spring.
Note: No matter what value you give month, one and only one assignment statement within the
ladder will be executed.
SWITCH:
● The switch statement is Java’s multiway branch statement.
case 3:
[Link]("i is three.");
break;
default:
[Link]("i is greater than 3.");
}
}
}
The output produced by this program is shown here:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
The break statement is optional. If you omit the break, execution will continue into the
next case.
It is sometimes desirable to have multiple cases without break statements between
them.
For example, consider the following program:
// In a switch, break statements are optional.
class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++)
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
[Link]("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
[Link]("i is less than 10");
break;
default:
[Link]("i is 10 or more");
}
}
}
This program generates the following output:
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is 10 or more
i is 10 or more
Execution falls through each case until a break statement (or the end of the switch) is
reached.
Beginning with JDK 7, you can use a string to control a switch statement. For example,
// Use a string to control a switch statement.
class StringSwitch {
public static void main(String args[]) {
String str = "two";
switch(str) {
case "one":
[Link]("one");
break;
case "two":
[Link]("two");
break;
case "three":
[Link]("three");
break;
default:
[Link]("no match");
break;
}
}
}
The output from the program is
two
case 2: // ...
The case 1: statement in the inner switch does not conflict with the case 1: statement
in the outer switch. The count variable is compared only with the list of cases at the
outer level. If count is 1, then target is compared with the inner list cases.
● 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. A
switch statement and an enclosing outer switch can have case constants in
common.
● A switch statement is usually more efficient than a set of nested ifs.
● When a switch statement is compiled, 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 expression. Therefore, If we want 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-elses.
2. Iteration Statements:
● Java’s iteration statements are for, while and do-while.
● These statements create loops. A loop repeatedly executes the same set of
instructions until a termination condition is met.
while:
● The while loop repeats a statement or block while its controlling expression
is true.
● 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 not needed if only a single statement is being repeated.
● As the while loop evaluates its conditional expression at the top of the
loop, the body will not execute even once if the condition is false to begin
with.
● The body of the while can be empty. As a null statement is syntactically
valid in Java.
The do-while:
● The do-while loop always executes its body at least once, because its
condition expression is at the bottom of the loop.
● General form
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. The condition must be a
Boolean expression.
● The do-while loop is useful when you process a menu selection, because
you will usually want the body of the menu loop to execute at least once.
[Link](b + “ “);
}
● for loop variations:
➢ First for loop variation: The condition expression of the for loop does
not need to test the loop control variable against some target value.
Example:
boolean done = false;
for(int i=1;!done;i++) {
...
if (interrupted()) done = true;
}
In the example above, the for loop continues to run until the boolean
variable done is set to true. It does not test the value of i.
➢ Second for loop variation: Either the initialization or the iteration
expression or both may be absent
Example:
boolean done = false;
int i = 0;
for (; !done; ) {
if ( i== 10) done = true;
i++;
}
➢ Third for loop variation: Infinite loop – a loop that never terminates
for ( ; ; ) {
// ...
}
Nested Loops:
● Java allows loops to be nested. That is, one loop may be inside another.
● Example
class Nested {
public static void main(String args[ ] ) {
int i, j;
for (i = 0; i <10; i ++) {
for (j=i;j<10;j++)
[Link](“.”);
[Link]();
}
}
}
Output:
..........
.........
........
.......
......
.....
....
Programming in Java Page 30
Programming in Java Module 2: Operators and control statements
...
..
.
The following table gives the difference of for and foreach loop:
JUMP STATEMENTS:
● Java supports three jump statements: break, continue and return.
● These statements transfer control to another part of your program.
1. break:
● break statements has three uses.
○ First it terminates a statement sequence in a switch statement.
○ Second it can be used to exit a loop.
○ Third, it can be used as goto.
Using a break to exit a loop:
● When a break statement is encountered inside a loop, the loop is terminated and program
control resumes at the next statement following the loop.
Programming in Java Page 31
Programming in Java Module 2: Operators and control statements
● The break statement can be used with any of Java’s loops, including intentionally infinite
loops.
● When used inside aerp set of nested loops, the break statement will only break out of the
innermost loop.
Using break as a form of goto:
● goto is useful when you are exiting from a deeply nested set of loops.
● Goto is not preferred as a goto-ridden code is hard to understand and hard to maintain. But
they can be useful when you are exiting from a deeply nested set of loops.
● Break gives the benefits of a goto statement without its problems
● The general form
break label;
● label is the name of a label that identifies a block of code.
● A label is any valid Java identifier followed by a colon.
● Example:
class Break
{
public static void main(String args[ ])
{
boolean t = true;
first:
{
second :
{
third:
{
[Link]("Before the break");
if (t) break second; // break out of second block
[Link]("This won’t execute");
} // End of third block
[Link]("This won't execute");
}
[Link]("This is after second block .");
} // End of first block
} // End of main
}
Output:
Before the break
This is after second block
USING CONTINUE:
● useful to force an early iteration of a loop.
● In while and do-while loops a continue statement causes control to be
transferred directly to the conditional expression that controls the loop.
● In a for loop, control goes first to the iteration portion of the for statement and
then to the conditional expression.
● As with the break statement, continue may specify a label to describe which
enclosing loop to continue.
Programming in Java Page 32
Programming in Java Module 2: Operators and control statements
Here is an example program that uses continue to cause two numbers to be printed
on each line:
// Demonstrate continue.
class Continue {
public static void main(String args[]) {
}
The continue statement in this example terminates the loop counting j and continues
with the next iteration of the loop counting i. Here is the output of this program:
0
01
024
0369
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81
Return:
● The return statement is used to explicitly return from a method.
● It causes program control to transfer back to the caller of the method.
● The return statement immediately terminates the method in which it is
executed.