0% found this document useful (0 votes)
28 views

Lecture 04 - Operators and Control Statements

This document discusses operators and control statements in Java. It outlines different types of operators including arithmetic, bitwise, relational, and logical operators. It provides examples of using various operators like shift, logical, and relational operators on integer and boolean values. The document also briefly introduces control statements like for-each loop, break, continue statements.

Uploaded by

Muhammad Tayyab
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Lecture 04 - Operators and Control Statements

This document discusses operators and control statements in Java. It outlines different types of operators including arithmetic, bitwise, relational, and logical operators. It provides examples of using various operators like shift, logical, and relational operators on integer and boolean values. The document also briefly introduces control statements like for-each loop, break, continue statements.

Uploaded by

Muhammad Tayyab
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

SE241: Advanced Computer

Programming
Lecture # 04: Operators and Control Statements

Muhammad Imran
(Based on Java, The Complete Reference)
http://www.secscourses.tk

1
Outline
• Operators

• Arithmetic Operators

• Bitwise Operators

• Relational Operators

• Logical Operators

• Operator Precedence

• Control Statements

• The For-Each Version of the for Loop

• Jump Statement: break

• Using break as a form of goto

• Jump Statement: continue

2
Operators
• Most of the Java’s operators can be divided into the
following four groups:
1. Arithmetic

2. Bitwise

3. Relational

4. Logical

3
1. Arithmetic Operators
• The operands of the arithmetic operators must be of a
numeric type

• We cannot use them on boolean type, but we can use


them with char type, since the char type in Java is
essentially, a subset of integers

4
1. Arithmetic Operators
Operator Result
+ Addition
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
-- Decrement
5
Integer Arithmetic
// Demonstrate the basic arithmetic operators.
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a; Output
int e = -d;
a=2
System.out.println("a = " + a);
System.out.println("b = " + b); b=6
System.out.println("c = " + c); c=1
System.out.println("d = " + d); d = -1
System.out.println("e = " + e);
e=1
}
6
Floating Point Arithmetic
// Demonstrate the basic arithmetic operators.
class BasicMath {
public static void main(String args[]) {
// arithmetic using doubles
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a; Output
double de = -dd;
da = 2.0
System.out.println("da = " + da);
System.out.println("db = " + db); db = 6.0
System.out.println("dc = " + dc); dc = 1.5
System.out.println("dd = " + dd); dd = -0.5
System.out.println("de = " + de);
de = 0.5
}
7
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.

8
Example: The Modulus Operator
// 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);
}
}

Output
x mod 10 = 2
y mod 10 = 2.3
9
2. The Bitwise Operators
• Bitwise operators can be applied to the integer types:
long, int, short, char, and byte.

• These operators act upon the individual bits of their


operands.

10
2. The Bitwise Operators
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
11
2. The Bitwise Operators
• Example: the byte value for 42 in binary is 00101010
• To represent negative numbers, Java uses two’s complement
encoding
 Inverting all of the bits in a value, then adding one to the result.
 Example: -42 is represented by inverting all of the bits in 00101010, which
yields11010101, then adding 1, which results in 11010110, or –42.

• The high-order bit determines the sign of an integer.

12
Example: The Bitwise Logical Operators

// Demonstrate the bitwise logical operators.


class BitLogic {
public static void main(String args[]) {
String binary[] = {
"0000", "0001", "0010", "0011", "0100", "0101",
"0110", "0111", "1000", "1001", "1010", "1011", "1100",
"1101", "1110", "1111" };
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
13
Example: The Bitwise Logical Operators

int f = (~a & b) | (a & ~b);


System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
}
}
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b | a&~b = 0101
~a = 1100 14
The left shift
• The left shift operator <<, shifts all of the bits in a value to
the left a specified number of times.
• It has this general form
 value << num
• For each shift left, the high order bit is shifted out (and
lost), and a zero is brought in on the right.
• Each left shift has the effect of doubling the original
value.

15
Example: The left shift
// 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);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
}
} Output
The original value of a: 64
i and b: 256 0
16
The Right Shift
• The right shift operator, >>, shifts all of the bits in a value to the
right a specified number of times.
• Its general form is
 value >> num
• For each shift right, the low order bit is shifted off (and lost), and the
leftmost bit exposed by the right shift are filled in with the previous
contents of the leftmost bit.
• This preserves the sign of the value.
• Each time we shift a value to the right, it divides that value by two,
and discards any remainder.

17
The Right Shift Zero Fill
• The right shift zero fill operator, >>>, always shifts zero in
the high order bit.

• This is known as an unsigned shift.

18
3. Relational Operators
• The relational operators determine the relationship that
one operand has to the other.

• Specifically, they determine the equality and ordering.

• The outcome of these operations is a boolean value.

19
3. Relational Operators
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

20
3. Relational Operators
int a = 4;
int b = 1;
boolean c = a < b; //c=false
• If using boolean type, we can write statements like
if(!done) ... // done is boolean
if(done) ... // done is boolean
• If using numeric type, we need to use relational operators explicitly
if(done == 0)) ... // done is int
if(done != 0) ... // done is int

21
4. Boolean Logical Operators
• The boolean logical operations operate only on boolean
operands.

• All of the binary logical operators combine two boolean


values to form a resultant boolean value.

22
4. Boolean Logical Operators
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
23
Short-Circuit Logical Operators

• The secondary versions of the Boolean OR (||) and AND


(&&) operators, are known as short-circuit logical
operators.
• If 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.

24
Operator Precedence

25
Control Statements

• Control statements are used to cause the flow of


execution to advance and branch based on changes to
the state of a program.

• Program control statements are categorized into:


 Selection: if and switch
 Iteration: for, while, and do-while
 Jump: break, continue, and return

26
The For-Each Version of the for Loop
• A for-each style loop is designed to cycle through a collection of
objects, such as an array, in strictly sequential fashion, from start to
finish.
• Java adds the for-each capability by enhancing the for statement.
• The general form of the for-each version is:
 for (type itr-var: collection) statement-block
 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.

27
The For-Each Version of the for Loop
• 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.
• The type of itr-var must be the same as (or compatible with) the
type of elements in the collection.
• Thus, when iterating over arrays, type must be compatible with the
base type of the array.

28
The For-Each Version of the for Loop
• Using a traditional for loop to compute the sum of the values in an
array:
int nums[]={1,2,3,4,5,6,7,8,9,10};
int sum=0;
for(int i=0; i<1; i++)
sum+=nums[i];
• Rewritten using for-each version:
int nums[]={1,2,3,4,5,6,7,8,9,10};
int sum=0;
for(int x : nums)
sum+=x;

29
The For-Each Version of the for Loop
//use a for-each for loop
public class ForEach {
public static void main(String[] args) {
int nums[]={1,2,3,4,5,6,7,8,9,10};
int sum=0;
for(int x : nums){
System.out.println("The value is: " + x);
Output
sum+=x; The value is: 1
} The value is: 2
The value is: 3
System.out.println("Summation is: "+sum); The value is: 4
} The value is: 5
The value is: 6
} The value is: 7
The value is: 8
The value is: 9
The value is: 10
Summation is: 55
30
The For-Each Version of the for Loop
//using break with a for-each style for loop
public class ForEach2 {
public static void main(String[] args) {
int nums[]={1,2,3,4,5,6,7,8,9,10};
int sum=0;
for(int x : nums){
System.out.println("The value is: " + x);
sum+=x;
if(x==5)
break;
Output
} The value is: 1
The value is: 2
System.out.println("Summation is: "+sum); The value is: 3
} The value is: 4
The value is: 5
} Summation is: 15
31
The For-Each Version of the for Loop
//use a for-each style for loop on a 2D array
public class ForEach3 {
public static void main(String[] args) {
int nums[][]=new int[3][5];
int sum=0; Output
for(int i=0; i<3; i++) The value is: 1
The value is: 2
for(int j=0; j<5;j++) The value is: 3
nums[i][j]=(i+1)*(j+1); The value is: 4
for(int x[] : nums){ The value is: 5
The value is: 2
for(int y: x){ The value is: 4
System.out.println("The value is: " + y); The value is: 6
The value is: 8
sum+=y; The value is: 10
} The value is: 3
} The value is: 6
The value is: 9
System.out.println("Summation is: "+sum); The value is: 12
} The value is: 15
} Summation is: 90
32
Jump Statement: break
• The break statement has three uses:
 It terminates a statement sequence in a switch statement.

 It can be used to exit a loop.


• When used inside a set of nested loops, the break statement will
only break out of the innermost loop.

 It can be used as a civilized form of goto.

33
Example: Using break to Exit a Loop
// Using break with nested loops.
class BreakLoop3 {
public static void main(String args[]) {
for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");
for(int j=0; j<100; j++) {
if(j == 10) break; // terminate loop if j is 10
System.out.print(j + " ");
}
System.out.println();
}
System.out.println("Loops complete."); Output
Pass 0: 0 1 2 3 4 5 6 7 8 9
} Pass 1: 0 1 2 3 4 5 6 7 8 9
} Pass 2: 0 1 2 3 4 5 6 7 8 9
Loops complete.
34
Using break as a form of goto
• Java doesn’t have a goto statement, because goto provides
a way to branch in an arbitrary and unstructured manner.
• This usually makes goto-ridden code hard to understand and
hard to maintain.
• There are, however, a few places where the goto is valuable
and legitimate construct for flow control.
 Example: the goto can be useful when we are exiting from a deeply
nested set of loops.
• Java defines an expanded form of break statement.
 By using this form of break, we can break out of one or more blocks
of code.

35
Using break as a form of goto
• Further, we can specify precisely where execution will resume,
because this form of break works with a label.
• Labeled break gives us the benefits of a goto without its problems.
• The general form of the labeled break is:
 break label;
• label is the name of the label that identifies a block of code.

36
Using break as a form of goto
• When this form of break executes, control is transferred out of the
named block of code.
• The labeled block of code must enclose the break statement, but it
does not need to be the immediate enclosing block.
• This means:
 We can use a labeled break statement to exit from a set of
nested blocks.
 But we cannot use break to transfer control to a block of code
that does not enclose the break statement.

37
Using break as a form of goto
• To name a block, put a label at the start of it.

• A label is any valid Java identifier followed by a colon.

• Once we have labeled a block, we can then use this label as the
target of a break statement.
 Doing so causes execution to resume at the end of the labeled block.

38
Example: Using break as a form of goto
// Using break as a civilized form of goto.
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
} 39
Example: Using break as a form of goto
// Using break to exit from nested loops
class BreakLoop4 {
public static void main(String args[]) {
outer: for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");
for(int j=0; j<100; j++) {
if(j == 10) break outer; // exit both loops
System.out.print(j + " ");
}
System.out.println("This will not print");
}
System.out.println("Loops complete.");
}
} Output
Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.
40
Example: Using break as a form of goto
// Cannot break to any label which is not defined for an enclosing
block.

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

one: for(int i=0; i<3; i++) {


System.out.print("Pass " + i + ": ");
}

for(int j=0; j<100; j++) {


if(j == 10) break one; // WRONG undefined label: one
System.out.print(j + " ");
}
}
}
41
Jump Statement: continue
• Sometimes, it is useful to force an early iteration of a loop

• That is, we might want to continue running the loop, but stop
processing the remainder of the code in its body for this particular
iteration

• continue may specify a label to describe which enclosing loop to


continue

42
Example: continue
// 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) {
System.out.println(); Output
continue outer; 0
} 01
System.out.print(" " + (i * j)); 024
0369
}
0 4 8 12 16
} 0 5 10 15 20 25
System.out.println(); 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
43
Recommended Readings
• Page # 61 to 79, Chapter # 4: Operators from Herbert
Schildt, Java: The Complete Reference, J2SETM 9th Edition

• Page # 81 to 108, Chapter # 5: Control Statements from


Herbert Schildt, Java: The Complete Reference, J2SETM 9th
Edition

44

You might also like