0% found this document useful (0 votes)
9 views34 pages

Java Operators and Control Statements

Module 2 of the Java programming course covers operators and control statements, detailing arithmetic, bitwise, relational, and logical operators. It explains the use of various control statements like selection and iteration, along with examples of arithmetic operations and compound assignment operators. Additionally, it discusses increment and decrement operators, providing sample programs to illustrate their functionality and outputs.

Uploaded by

dscm200515
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views34 pages

Java Operators and Control Statements

Module 2 of the Java programming course covers operators and control statements, detailing arithmetic, bitwise, relational, and logical operators. It explains the use of various control statements like selection and iteration, along with examples of arithmetic operations and compound assignment operators. Additionally, it discusses increment and decrement operators, providing sample programs to illustrate their functionality and outputs.

Uploaded by

dscm200515
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Programming in Java Module 2: Operators and control statements

Module 1 Syllabus Continuation:


Operators: Arithmetic Operators, Relational Operators, Boolean Logical Operators, The
Assignment Operator, The ? Operator, Operator Precedence, Using Parentheses.

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.

In Java, operators are divided into four groups


1. Arithmetic
2. Bitwise
3. Relational
4. Logical

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

Sl. No. Operator Result


1 + Addition
2 - Subtraction (Also unary minus)
3 * Multiplication
4 / Division
5 % Modulus
6 ++ Increment
7 += Addition Assignment
8 -= Subtraction Assignment
9 *= Multiplication Assignment
10 /= Division Assignment
11 %= Modulus Assignment
12 -- Decrement

Programming in Java Page 1


Programming in Java Module 2: Operators and control statements

The Basic Arithmetic Operators:

●​ The basic arithmetic operations are -


1. addition
2. subtraction
3. multiplication
4. division
●​ The minus operator also has a unary form that negates its single operand.
●​ When the division operator is applied to an integer type, there will be no fractional
component attached to the result.
●​ The following program demonstrates the arithmetic operations -

// Program to demonstrate the basic arithmetic operators


class BasicMath {
​ public static void main( String args[ ]) {
​ ​ [Link](“Integer Arithmetic”);
​ ​ int a = 1 + 1;
​ ​ int b = a * 3;
​ ​ int c = b / 4;
​ ​ int d = c – a;
​ ​ int e = -d;
​ ​
​ ​ [Link](“a = “ + a);
​ ​ [Link](“b = “ + b);
​ ​ [Link](“c = “ + c);
​ ​ [Link](“d = “ + d);
​ ​ [Link](“e = “ + e);

​ ​ [Link](“Floating Point Arithmetic”);


​ ​ double da = 1 + 1;
​ ​ double db= da * 3;
​ ​ double dc = db / 4;
​ ​ double dd = dc - da;
​ ​ double de = -dd;

​ ​ [Link](“da = “ + da);
​ ​ [Link](“db = “ + db);
​ ​ [Link](“dc = “ + dc);
​ ​ [Link](“dd = “ + dd);
​ ​ [Link](“de = “ + de);
​ }
}


Output:
Integer Arithmetic

Programming in Java Page 2


Programming in Java Module 2: Operators and control statements

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

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 program demonstrates the % operator

// Demo of % operator
class Modulus {
​ public static void main(String args[ ]) {
​ ​ int x = 42;
​ ​ double y = 42.25;

​ ​ [Link](“x mod 10 = “ + x % 10);


​ ​ [Link](“y mod 10 = “ + y % 10);
​ }
}

Output:
x mod 10 = 2
y mod 10 = 2.25

Arithmetic Compound Assignment Operators:


●​ Compound assignment operators are special operators that are used to combine an
arithmetic operation with an assignment operation.
●​ A statement like the following
○​ a = a + 4;
○​ can be rewritten as
○​ a += 4;
●​ The above statement uses the += compound assignment operator. Both statements perform
the same action. They increase the value of a by 4.
●​ There are compound assignment operators for all arithmetic, binary operators.
●​ Any statement of the form
○​ var = var op expression;
○​ can be rewritten as
○​ var op= expression;
●​ Advantages:
○​ 1. They save a bit of typing because they are “shorthand” for their equivalent long

Programming in Java Page 3


Programming in Java Module 2: Operators and control statements

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

// Demo program to illustrate compound assignment operators


class OpEquals {
​ public static void main(String args [ ]) {
​ ​ int a = 1;
​ ​ int b = 2;
​ ​ int c = 3;

​ ​ 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

Increment and Decrement operator:


●​ The ++ and – are Java’s increment and decrement operators respectively.
●​ The increment operator increases its operand by one.
●​ The decrement operator decreases its operand by one.
●​ The statement
◦​ x = x + 1; can be rewritten in Java using increment operator as
◦​ x++;
●​ Similarly, the statement
◦​ x = x – 1; is same as
◦​ x--;
●​ Increment and decrement operators appear both in postfix form and prefix form.
●​ In postfix form, the operator follows the operand
●​ In prefix form the operator precede the operand.
●​ For statements like
◦​ x++;
◦​ --y;
◦​ there is no difference between prefix and postfix forms.
●​ The prefix and postfix forms matter a lot when the increment and/or decrement
operators are part of a larger expression.
●​ In the prefix form, the operand is incremented or decremented before the value is obtained
for use in the expression.
Programming in Java Page 4
Programming in Java Module 2: Operators and control statements

●​ 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

Write the output of the following:


1.​ Program 1

public class IncrementDecrementQuiz


{
public static void main(String[] args)
{

Programming in Java Page 5


Programming in Java Module 2: Operators and control statements

int i = 11;
i = i++ + ++i;
[Link](i);
}
}

Answer: 24

2. Program 2

public class IncrementDecrementQuiz


{
public static void main(String[] args)
{
int a=11, b=22, c;
c = a + b + a++ + b++ + ++a + ++b;
[Link]("a="+a);
[Link]("b="+b);
[Link]("c="+c);
}
}

Answer :
a=13
b=24
c=103

3. Program 3

public class IncrementDecrementQuiz


{
public static void main(String[] args)
{
int i=0;
i = i++ - --i + ++i - i--;
[Link](i);
}
}

Answer : 0

4. Program 4

Programming in Java Page 6


Programming in Java Module 2: Operators and control statements

public class IncrementDecrementQuiz


{
public static void main(String[] args)
{
int i=1, j=2, k=3;
int m = i-- - j-- - k--;

[Link]("i="+i);
[Link]("j="+j);
[Link]("k="+k);
[Link]("m="+m);
}
}

Answer :
i=0
j=1
k=2
m=-4

5. Program 5

public class IncrementDecrementQuiz


{
public static void main(String[] args)
{
int a=1, b=2;

[Link](--b - ++a + ++b - --a);


}
}

Answer : 0

6. Program 6

public class IncrementDecrementQuiz


{
public static void main(String[] args)
{
int i=19, j=29, k;

Programming in Java Page 7


Programming in Java Module 2: Operators and control statements

k = i-- - i++ + --j - ++j + --i - j-- + ++i - j++;

[Link]("i="+i);
[Link]("j="+j);
[Link]("k="+k);
}
}

Answer :
i=19
j=29
k=-20

THE BITWISE OPERATORS:


●​ Bitwise operators act upon the individual bits of their operands.
●​ Java defines several bitwise operators that can be applied to integer types – long, int, short,
char, byte.
●​ The following table shows the list of bitwise operators -

Sl. No. Operator Result


1 ~ Bitwise unary NOT
2 & Bitwise AND
3 | Bitwise OR
4 ^ Bitwise exclusive OR
5 >> Shift Right
6 >>> Shift Right Zero Fill
7 << Shift Left
8 &= Bitwise AND Assignment
9 |= Bitwise OR Assignment
10 ^= Bitwise exclusive OR Assignment
11 >>= Shift Right Assignment
12 >>>= Shift Right Zero Fill Assignment
13 <<= Shift Left Assignment

●​ Bitwise operators manipulate the bits within an integer. So we need to know how Java
stores integer values and how it represents negative numbers.

Programming in Java Page 8


Programming in Java Module 2: Operators and control statements

How positive integer values are stored:

●​ 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

HOW NEGATIVE INTEGER VALUES ARE STORED:

●​ Java uses an encoding known as two’s complement to represent negative numbers in


binary format.
●​ To find the binary equivalent of -42, invert (change 1’s to 0’s and vice versa) all the bits of
+42.
●​ Then add 1 to the result. We get the binary equivalent of -42. The conversion is illustrated
below. The binary equivalent of -42 is 11010110.
●​ The high-order bit determines the sign of an integer. Positive numbers have high order bit
0 and negative numbers have high order bit 1.

​ ​ ​ +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

Why Java uses 2’s complement to represent negative integer values?

●​ 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.

Programming in Java Page 9


Programming in Java Module 2: Operators and control statements

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.

The Bitwise Logical Operators:


●​ The bitwise logical operators are &, |, ^ and ~.
●​ The following table shows the outcome of each operation:

A B A|B A&B A^B ~A


0 0 0 0 0 1
0 1 1 0 1 1

1 0 1 0 1 0
1 1 1 1 0 0

The Bitwise NOT:


●​ The bitwise NOT operator, ~, inverts all of the bits of its operand.
●​ It is also called bitwise complement or unary NOT operator.
●​ Its an unary operator.
●​ For example,
int x = 42;
int y;
y = ~x;

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

The Bitwise AND:


●​ The AND operator, &, produces a 1 bit if both operands are 1.
●​ A zero is produced in other cases.
●​ Example
int x = 42;
int y = 15;
Programming in Java Page 10
Programming in Java Module 2: Operators and control statements

int z = x & y;

00101010 42
&00001111 15
00001010 10
so z = 10

The Bitwise OR:


●​ The bitwise OR operator, |, produces 1 if either of the bits in the operands is a 1.
●​ Example:
int x = 42;
int y = 15;
int z = x | y;
00101010 42
| 00001111 15
00101111 47
so z = 47

The Bitwise XOR:


●​ The bitwise XOR operator, ^, produces 1 if exactly one operand is 1 otherwise the result is
zero.
●​ Example:
int x = 42;
int y = 15;
int z = x ^ y;
00101010 42
^ 00001111 15
00100101 37
so z = 37

THE LEFT SHIFT:


●​ The left shift operator, <<, shifts all of the bits in a value to the left a specified
number of times.
●​ The general form is
◦​ value << num
◦​ num specifies the number of positions to left-shift the value in value.
●​ The high-order bit is shifted out (and lost) for each shift left, and a zero is brought in on
the right.
●​ When a left shift is applied to an int operand, bits are lost once they are shifted past bit
position 31.
●​ When a left shift is applied to a long operand, bits are lost once they are shifted past bit
position 63.
●​ Java’s automatic type promotions produce unexpected results when we are shifting
byte and short values.
●​ For example, if we left shift a byte value, that value will first be promoted to int and then
shifted. Therefore, we must discard the top three bytes of the result if we need the shifted
byte value. For this, we need to cast the result back to byte.
●​ The following program demonstrates this concept

Programming in Java Page 11


Programming in Java Module 2: Operators and control statements

// Left shifting a byte value


class ByteShift {
​ public static void main (String args[ ] ) {
​ byte a = 64, b;
​ int i;
​ i = a << 2;
​ b = (byte) (a << 2);
​ [Link](“Original value of a :” + a);
​ [Link](“i and b:” + i + “ “ + b);
}
}
Output:
Original value of a: 64
i and b: 256 0

a = 64 => 0000 0000 0000 0000 0000 0000 0100 0000


i = a << 2 = 256 => 0000 0000 0000 0000 0000 0001 0000 0000
b = (byte) (a << 2) = 0 => 0000 0000

●​ 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

Programming in Java Page 12


Programming in Java Module 2: Operators and control statements

The Right Shift:


●​ The right shift operator, >>, shifts all the bits in a value to the right a specified number of
times.
●​ General form:
◦​ value >> num;
◦​ where num specifies the number of positions to right shift the value in value.
●​ Example:
◦​ int a = 32;
◦​ a = a >> 2; // a now contains 8

a = 32 => 0000 0000 0000 0000 0000 0000 0010 0000


a = a >> 2 = 8 => 0000 0000 0000 0000 0000 0000 0000 1000

●​ When the bits are shifted off (low order bits) those bits are lost.
●​ Example:
◦​ int a = 35;
◦​ a = a >> 2; // a still contains 8

a = 35 => 0000 0000 0000 0000 0000 0000 0010 0011


a = a >> 2 = 8 => 0000 0000 0000 0000 0000 0000 0000 1000

●​ Each time we shift a value to the right, it divides that value by 2 and discards any
remainder.

●​ For example -8 >> 1 is -4


1111 1000 -8
>> 1
1111 1100 -4
●​ If we shift -1 right, the result always remains -1, as sign extension keeps bringing in
more ones in the high order bits.

The Unsigned Right Shift:


●​ To preserve the sign of the value, the >> operator fills the high order bit with its previous
contents each time a shift occurs. This is undesirable, if we are shifting a non-numeric
value (something that does not represent a numeric value). This situation arises when
working with graphics.
●​ We want to shift a zero into the high order bit irrespective of its initial value. This is
known as unsigned shift. For this, we use Java’s unsigned shift – right operator, >>>,
which always shifts zero into the high order bit.
●​ The following code demonstrates >>>
int a = -1;
a = a >>> 24

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.

Programming in Java Page 13


Programming in Java Module 2: Operators and control statements

●​ 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.

Bitwise Operator Compound Assignments:


●​ All of the binary bitwise operators have a compound form similar to that of the algebraic
operators, which combines the assignment with the bitwise operation.
●​ For example, the following two statements which shift the value in a right by four bits, are
equivalent
a = a >> 4;
a >>= 4;
●​ Similarly,
a = a | b;
a |= b;
are the same.
●​ The following program demonstrates bitwise operator assignments

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

Sl. No. Operator Result


1 == Equal to
2 != Not Equal to
3 > Greater than

Programming in Java Page 14


Programming in Java Module 2: Operators and control statements

4 < Less than


5 >= Greater than or equal to
6 <= Less than or equal to

●​ The outcome of these operations is a boolean value.


●​ The relational operators are used in the expressions that control the if
statement and various loop statements.
●​ Any type in Java, including integers, floating-point numbers, characters and
Booleans can be compared using the equality test, ==, and the inequality test,
!=.
●​ Only numeric types can be compared using the ordering operators. That is,
only integer, floating-point, and character operands may be compared to see
which is greater or less than the other.
●​ Example:
int a = 4;
int b = 1;
boolean c = a < b;
●​ The result of a < b (which is false) is store in c.
●​ The C/C++ statements
int done;
​​ ​ if (!done) ...
​​ ​ if (done) ...
​​ ​ must be written like this
​​ ​ if ( done == 0) ...
​​ ​ if ( done != 0) ...

●​ 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.

Boolean Logical Operators:


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

Sl. No. Operator Result


1 & Logical AND
2 | Logical OR
3 ^ Logical XOR (Exclusive OR)
4 || Short-circuit OR
5 && Short-circuit AND
6 ! Logical unary NOT

Programming in Java Page 15


Programming in Java Module 2: Operators and control statements

7 &= AND assignment


8 |= OR assignment
9 ^= XOR assignment
10 == Equal to
11 != Not equal to
12 ?: Ternary if-then-else

The following table shows the effect of each logical operation:

A B A|B A&B A^B !A


False False False False False True
True False True False True False
False True True False True True
True True True True False False

// Program to 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;

​ ​ [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

Short-Circuit Logical Operators:


●​ Java provides two Boolean operators not found in many other computer
languages. These are secondary versions of the Boolean AND and OR
operators and are known as short-circuit operators.
●​ The OR operator results in true when A is true, no matter what B is. Similarly,
the AND operator results in false when A is false, no matter what B is.
●​ When we use || and && forms, rather than | and & forms of these
operators, Java will not bother to evaluate the right-hand operand when
the outcome of the expression can be determined by the left operand
alone.
●​ Example
if (denom !=0 && num /denom > 10)
As the short circuit form of && is used, there is no risk of causing a
run-time exception when denom is zero.
●​ If this line of code were written using the single & version of AND, both sides
would be evaluated, causing a run-time exception when denom is zero.
●​ Its a standard practice to use the short-circuit forms of AND and OR in cases
involving Boolean logic, leaving the single character versions exclusively for
bitwise operations.

The Assignment operator:


●​ The assignment operator is the single equal sign, =.
●​ The general form is
​​ var = expressions;
​​ The type of var must be compatible with the type of expression.
●​ The assignment operator allows to create a chain of assignments.
​​ For example:
​​ int x, y, z;
​​ x = y = z = 100;

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

Programming in Java Page 17


Programming in Java Module 2: Operators and control statements

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

Program to find the largest of three numbers using ternary operator


import [Link];
public class Largest_Ternary
{
public static void main(String[] args)
{
int a, b, c, d;
Scanner s = new Scanner([Link]);
[Link]("Enter all three numbers:");
a = [Link]();
b = [Link]();
c = [Link]();
d= (a>b) ? ((a>c)? a:c): ((b>c)? b:c);
[Link]("Largest Number:"+d);
}
}

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.

Programming in Java Page 18


Programming in Java Module 2: Operators and control statements

Highest
() [] .
++ -- ~ !
* / %
+ -
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
= op=
Lowest

●​ Parentheses raise precedence of the operators that are inside them.


●​ Example:
​a >> b + 3; or a >> (b + 3);
The above expressions first adds 3 to b and then shifts a right by that result.
●​ If we want to first shift a right by b positions and then add 3 to that result, we need to
parenthesize the expression like this
(a >> b) + 3;
●​ Parentheses can sometimes be used to help clarify the meaning of an expression. Adding
redundancy by clarifying parentheses to complex expressions can help prevent confusion later.

TOPIC: CONTROL STATEMENTS

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.

Programming in Java Page 19


Programming in Java Module 2: Operators and control statements

2. Iteration – Iteration statements enable program execution to repeat one or more statements.

3. jump – jump statements allow your program to execute in a nonlinear fashion.

JAVA’S SELECTION STATEMENTS:


●​ Java supports two selection statements: if and switch
●​ Selection statements allow you to control the flow of your program’s
execution based upon conditions known only during run time.

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();

Programming in Java Page 20


Programming in Java Module 2: Operators and control statements

●​ Here, both statements within the if block will execute if bytesAvailable


is greater than zero.
●​ Some programmers find it convenient to include the curly braces when
using the if, even when there is only one statement in each clause. This
makes it easy to add another statement at a later date, and you don’t
have to worry about forgetting the braces. In fact, forgetting to define a
block when one is needed is a common cause of errors. For example,
consider the
following code fragment:
int bytesAvailable;
// ...
if (bytesAvailable > 0) {
ProcessData();
bytesAvailable -= n;
} else
​ waitForMoreData();
bytesAvailable = n;
●​ It seems clear that the statement bytesAvailable = n; was intended to
be executed inside the else clause, because of the indentation level.
However, there is no way for the compiler to know what was intended.
This code will compile without complaint, but it will behave incorrectly
when run. The preceding example is fixed in the code that follows:
int bytesAvailable;
// ...
if (bytesAvailable > 0)
{
ProcessData();
bytesAvailable -= n;
}
else
{
waitForMoreData();
bytesAvailable = n;
}
Nested ifs:
●​ A nested if is an if statement that is the target of another if or else.
●​ When we nest ifs, remember that an else statement always refers to the
nearest if statement that is within the same block as the else and that is not
already associated with an else.
●​ Example:
​​ 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)

Programming in Java Page 21


Programming in Java Module 2: Operators and control statements

The if-else-if ladder:

General form:
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 are true, then the final else statement will be executed.
●​ The final else acts as the default condition.
●​ If there is no final else and all other conditions are false, then no action will take place.

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.

Programming in Java Page 22


Programming in Java Module 2: Operators and control statements

●​ The general form


switch (expression) {
case value1:
​ // Statement sequence
​ break;
case value2:
​ // Statement sequence
​ break;
.
.
.
case valueN:
​ // Statement sequence
​ break;
default:
​ // default statement sequence
}
●​ For versions of Java before JDK 7, an expression must be of type byte, short, int,
char, or an enumeration. Beginning with JDK 7, the expression can also be of type
String.
●​ Each of the values specified in the case statements must be of a type compatible with the
expression.
●​ An enumeration value can also be used to control a switch statement.
●​ Each case value must be unique literal. Duplicate case values are not allowed.
●​ Working: The value of the expression is compared with each of the literal values in the
case statements. If a match is found, the code sequence following that case statement is
executed. If none of the constants match the value of the expression, then the default
statement is executed. The default statement is optional. If no case matches and no default
is present, then no further action is taken.
●​ The break statement is used inside the switch to terminate a statement sequence. When a
break statement is encountered, execution branches to the first line of code that follows the
entire switch statement. This has the effect of “jumping out” of the switch.

Here is a simple example that uses a switch statement:


// A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
[Link]("i is zero.");
break;
case 1:
[Link]("i is one.");
break;
case 2:
[Link]("i is two.");
break;
Programming in Java Page 23
Programming in Java Module 2: Operators and control statements

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

Programming in Java Page 24


Programming in Java Module 2: Operators and control statements

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.

// An improved version of the season program.


class Switch {
public static void main(String args[]) {
int month = 4;
String season;
switch (month) {
case 12:
case 1:
case 2:
​ season = "Winter";
​ break;
case 3:
case 4:
case 5:
​ season = "Spring";
​ break;
case 6:
case 7:
case 8:
​ season = "Summer";
​ break;
case 9:
case 10:
case 11:
​ season = "Autumn";
​ break;
default:
​ season = "Bogus Month";
}
[Link]("April is in the " + season + ".");
}
}
Programming in Java Page 25
Programming in Java Module 2: Operators and control statements

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

Note: Switching on strings can be more expensive than switching on [Link],


it is best to switch on strings only in cases in which the controlling data is already in
string form. In other words, don’t use strings in a switch unnecessarily.

Nested switch statements:


●​ we can use switch as part of the statement sequence of an outer switch. This is
called 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:
​ [Link]("target is zero");
​ break;
case 1: // no conflicts with outer switch
​ [Link]("target is one");
​ break;
}
break;

Programming in Java Page 26


Programming in Java Module 2: Operators and control statements

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.

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. 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

Programming in Java Page 27


Programming in Java Module 2: Operators and control statements

​​ 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.

The for loop:


●​ Beginning with JDK 5, there are two forms of the for loop.
●​ The first is the traditional form that has been in use since the original
version of Java.
●​ The second is the new “for-each” form.
●​ General form of traditional 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. This sets the value of the loop control
variable, which acts as a counter that controls the loop. Next, condition is
evaluated. This must be a Boolean expression. If this expression is true, then
the body of the loop is executed. Next, the iteration portion of the loop is
executed. This is usually an expression that increments or decrements the
loop control variable. The loop then iterates, first evaluating the condition
expression, then executing the body of the loop, and then executing the
iteration expression with each pass. This process repeats until the condition
returns false.
●​ Declaring loop control variables inside the for loop:
➢​ If the variable that controls a for loop is only needed for the purpose of
the loop and is not used elsewhere, it is possible to declare the variable
inside the initialization portion of the for.
➢​ When we declare a variable inside a for loop, the scope of that variable
is limited to the for loop. Outside the for loop, the variable will cease to
exist.
●​ Using the Comma:
➢​ Java permits the user to include multiple variables in both the
initialization and iteration portions of the for loop. Each variable is
separated from the next by a comma.
➢​ Example:
int a, b;
for (a=1, b=4; a < b; a++, b--) {
​​ ​ ​ ​ [Link](a + “ “);

Programming in Java Page 28


Programming in Java Module 2: Operators and control statements

​​ ​ ​ ​ [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 ( ; ; ) {
// ...
}

The for-each version of the for loop:


●​ Beginning with JDK 5, a second form of for – for-each loop got introduced.
●​ A for-each style loop is designed to cycle through a collection of objects,
such as an array, from start to finish.
●​ Java adds the for-each capability by enhancing the for statement. The
advantage of this approach is that no new keyword is required and no
preexisting code is broken.
●​ It is also known as enhanced for loop.
●​
●​ General form
​​ ​ for (type itr-var : collection) statement-block
●​ Here, type specifies the type and itr-var specifies the name of an iteration
variable that will receive the elements from a collection, one at a time, from
beginning to end. The collection being cycled through is specified by
collection. With each iteration of the loop, the next element in the collection
is retrieved and stored in itr-var. The loop repeats until all elements in the
collection have been obtained.
●​ Example:
​​ ​ int nums[ ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
​​ ​ int sum = 0;
Programming in Java Page 29
Programming in Java Module 2: Operators and control statements

​​ ​ for (int x: nums) sum += x;


●​ Although, the for-each for loop iterates until all elements in an array have
been examined, it is possible to terminate the loop early by using a break
statement.
●​ The iteration variable is “read-only” as it relates to the underlying array. An
assignment to the iteration variable has no effect on the underlying array.
That is, we can’t change the contents of the array by assigning the iteration
variable a new value.
●​ Example program
​​ ​ // The for-each loop is read-only
​​ ​ class NoChange {
​​ ​ ​ public static void main (String args[ ] ) {
​​ ​ ​ ​ int nums [ ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
​​ ​ ​ ​ for (int x : nums) {
​​ ​ ​ ​ ​ [Link] (x + “ “);
​​ ​ ​ ​ ​ x = x * 10;
​​ ​ ​ ​ }
​​ ​ ​ [Link]();
​​ ​ ​ for (int x: nums)
​​ ​ ​ ​ [Link](x + “ “);
​​ ​ ​ [Link]();
​​ ​ }
}
Output:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

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[]) {

for(int i=0; i<10; i++) {


if (i%2 == 0)
{
​ [Link](i + " ");
​ continue;
}
}
}
}
This code uses the % operator to check if i is even. If it is, the loop continues
without
printing a newline. Here is the output from this program:
01
23
45
67
89
As with the break statement, continue may specify a label to describe which
enclosing loop to continue.

Here is an example program that uses continue to print a triangular multiplication


table for 0 through 9:
// Using continue with a label.
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i)
{
[Link]();
continue outer;
}
[Link](" " + (i * j));
​ ​ ​ ​ ​ }
​ ​ ​ ​ }
​ ​ ​ ​ [Link]();
}

Programming in Java Page 33


Programming in Java Module 2: Operators and control statements

}
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.

Programming in Java Page 34

You might also like