0% found this document useful (0 votes)
72 views22 pages

Unit 3 Operators and Control Statements: Structure

This document discusses operators and control statements in Java. It covers various arithmetic, comparison, logical and increment/decrement operators. It also explains operator precedence. For control flow, it describes conditional statements like if-else and switch statements as well as looping statements like for, while and do-while loops. It provides examples to demonstrate the use of various operators and control statements in Java programs.

Uploaded by

Pavan Thakur
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)
72 views22 pages

Unit 3 Operators and Control Statements: Structure

This document discusses operators and control statements in Java. It covers various arithmetic, comparison, logical and increment/decrement operators. It also explains operator precedence. For control flow, it describes conditional statements like if-else and switch statements as well as looping statements like for, while and do-while loops. It provides examples to demonstrate the use of various operators and control statements in Java programs.

Uploaded by

Pavan Thakur
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
You are on page 1/ 22

Object Oriented Programming – Java Unit 3

Unit 3 Operators and Control Statements


Structure:
3.1 Introduction
Objectives
3.2 Operators
Arithmetic Operators
Increment and Decrement Operators
Comparison Operators
Logical Operators
Operator Precedence
3.3 Control Flow Statements
If-else Statement
Switch Statement
For Loop
While Loop
Do…While Loop
Break Statement
Continue Statement
3.4 Summary
3.5 Terminal Questions
3.6 Answers

3.1 Introduction
In the last unit, you have learnt the basic program structure in Java. In this
unit, we will explore various operators and control statements in Java.
There are many constructs in Java to implement conditional execution. For
example, flow of a program can be controlled using the if construct. The if
construct allows selective execution of statements depending on the value
of the expressions associated with the if construct. Similarly, repetitive tasks
can be done using for constructs which would be discussed in detail in this
unit.

Objectives:
After studying this unit, you should be able to:
 explain different operators in Java
 discuss various control statements in Java

Sikkim Manipal University – DDE B2119 Page No. 34


Object Oriented Programming – Java Unit 3
3.2 Operators
In Java, operator play an important role. Three different kinds of operator in
Java are as follow:
i) Arithmetic Operators
ii) Comparison / Relational Operators and
iii) Logical Operators

3.2.1 Arithmetic Operators


Addition, Subtraction, Multiplication, Division and Modulus are the various
arithmetic operations that can be performed in Java. Table 3.1 lists different
Arithmetic Operators.
Table 3.1: List of Arithmetic Operators

Operator Meaning Use Meaning


+ ADD op1+op2 Adds two or more operators.
Performs subtraction of two or more
- SUBTRACT op1-op2
operators.
PRODUCT Performs multiplication between two or
* op1*op2
(MULTIPLY) more operators.
/ DIVISION op1/op2 Performs division between two operators.
Calculates the reminder left in division
% MODULOUS op1 % op2
between two operators.

The Java program in the figure 3.1 adds two numbers and prints the result.

Figure 3.1: Java Program to add two numbers and printing the result

Sikkim Manipal University – DDE B2119 Page No. 35


Object Oriented Programming – Java Unit 3
The compilation and running of the program is shown in figure 3.2

Figure 3.2: Compilation and Running of Java Program

3.2.2 Increment and Decrement Operators


In Java, ++ is called the increment operator; its function is to increment the
value by 1; and – is called the decrement operator; and its function to
decrease the value by 1. Figure 3.3 shows and example of increment
operators in Java.

Figure 3.3: Example showing increment operators in Java

Sikkim Manipal University – DDE B2119 Page No. 36


Object Oriented Programming – Java Unit 3
The compilation and running of the program is shown in figure 3.4.

Figure 3.4: Program Compilation and Running

When the operator ++ is placed after the variable name, first the assignment
of the value of the variable is done; then the value of the variable is
incremented by 1. This operation is also called post increment. Therefore,
the value of y1 will remain as 5 and the value of x1 will be 6. When the
operator is placed before the variable, first increment of the variable takes
place and then the assignment occurs. Hence the value x2 and y2 both will
be 6. This operation is also called as pre increment. Similarly – – operator
can be used to perform post decrement and pre decrement operations. If
there is no assignment and only the value of variable has to be incremented
or decremented, then placing the operator after or before does not make
difference.
3.2.3 Comparison Operators
In Java, to compare the values of two or more operators, comparison
operators are used. Table 3.2 lists various Comparison Operators in Java.
Table 3.2: List of Comparison Operators in Java

Operator Meaning Example Remarks


== Equal op1 = = op2 Checks if both the operators are equal or
not.
!= Not Equal op1 != op2 Checks if the operators are not equal to
each other or not.
< Less than op1 < op2 Checks if the first operator is lesser than
the other operator or not.
> Greater than op1 > op2 Checks if the first operator is greater than
the other operator or not.

Sikkim Manipal University – DDE B2119 Page No. 37


Object Oriented Programming – Java Unit 3

<= Less than or op1 <= op2 Checks if the operator is lesser than or
equal equal to the other operator.
>= Greater than op1 >= op2 Checks if the first operator is greater than
or equal or equal to the other operator.

3.2.4 Logical Operators


In Java, to perform Boolean operation on operands we use Logical
operators. Table 3.3 lists various Logical Operators in Java.
Table 3.3: List of Logical Operators in Java
Operator Meaning Example Remarks
&& Short-circuit op1 && Returns TRUE if and only if both the
AND op2 operands are TRUE.
|| Short-circuit OR op1 || op2 Returns true if any of the two operators
are TRUE.
! Logical unary !op Return compliment of the value of the
NOT operands. For example if the operand
value is TRUE it will return FALSE.
& Logical AND Op1 & op2 Returns true if both are true. Always
op1 and op2 will be evaluated.
| Logical OR Op1 | op2 Returns true if anyone is true. Always
op1 and op2 will be evaluated.

3.2.5 Operator Precedence


When more than one operator is used in an expression, Java will use
operator precedence rule to determine the order in which the operators will
be evaluated. For example, consider the following expression:
Result=10+5*8-15/5
In the above expression, multiplication and division operations have higher
priority over the addition and subtraction. Hence they are performed first.
Now, Result = 10+40-3.
In Java the operators are evaluated from left to right in the order they
appear in the given expression if in case they have same priority. Hence the
value of the result will become 47. In general, the following priority order is
followed when evaluating an expression:
 Increment and decrement operations.
 Arithmetic operations.
 Comparisons.
 Logical operations.
 Assignment operations.

Sikkim Manipal University – DDE B2119 Page No. 38


Object Oriented Programming – Java Unit 3
To change the order of evaluation of any given expression we use
parenthesis. The expression within the parenthesis are to be evaluated first.
When the parentheses are nested together, the expressions in the
innermost parentheses are evaluated first. Parentheses also improve the
readability of the expressions. When the operator precedence is not clear,
parentheses can be used to avoid any confusion. The examples of operator
precedence have been shown in the figure 3.5.

Figure 3.5: Operator Precedence Example

Self Assessment Questions


1. Give the symbol for modulus operator.
2. Give the symbol for logical AND operator.

3.3 Control Flow Statements


To control the flow of execution in a program the following statements are
used:
1. Decision Making Statements
 If-else statement
 Switch – case statement
2. Looping Statements
 For loop
 While loop
 Do-while loop
3. Other statements
 Break
 Continue

Sikkim Manipal University – DDE B2119 Page No. 39


Object Oriented Programming – Java Unit 3
3.3.1 If-else statement
IF statement is a conditional branch statement which can be used to route
the program execution through two different paths. The syntax for if stamen
is as follow:
if (condition) statement1;
else statement2;
In the above syntax statement 1 and statement 2 can be a single statement
or a group of statement, in case if it is a group of statement then it is written
with in curly bracket { }. The condition is an expression which returns a
Boolean value based on which the choice between the two stament is
made. The else part is optional and can be left also in case the program
doesn’t need it.
Working of If statement is as follow: if the condition is TRUE then in the
above syntax, statement 1 is execute; the statement 1 part is called the
TRUE part and that block is executed only when the condition is TRUE i.e.
value 1 is returned; and if the condition is FALSE, i.e. after condition
checking 0 is returned then else part is executed, i.e. statement 2 is
executed. The else part is the False block of if – else statement which is
executed when the condition is FALSE. An example of If… else statement
shown in the figure 3.6.

Figure 3.6: If… else statement example

Relational operators are mostly used in condition part but we can also use a
single Boolean variable also. The code given below shows the working of an
if statement:
boolean singleValue;
// ...
if (singleValue)
Perform1();

Sikkim Manipal University – DDE B2119 Page No. 40


Object Oriented Programming – Java Unit 3
else
WaitForCorrectData();
In the above example we have only used a single value (Boolean type) for
condition checking and each TRUE and FALSE block have just one
statement. We will see one more example where we will see how to include
more than one statement in the TRUE and FALSE block.
int checkCondition;
// ...
if (checkCondition > 0) {
Perform1();
Perform2();
Perform3();
} else
{
Perform4();
Perform5();
}
Here, both statements within the if block will execute more than one
statement. The statements are included with curly brackets { }. One set of
{ } brackets forms one block. Here if we forget to define the block then it will
cause error. 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,
as you recall, whitespace is insignificant to Java, and 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.

Sikkim Manipal University – DDE B2119 Page No. 41


Object Oriented Programming – Java Unit 3
The preceding example is fixed in the code that follows:
int bytesAvailable;
// ...
if (bytesAvailable > 0) {
ProcessData();
bytesAvailable -= n;
} else {
waitForMoreData();
bytesAvailable = n;
}
The if-else-if Ladder
When there are more than one condition that is needed to suffice and the
condition occurs in a sequence, or based on the result of one condition
there are other set of conditions or condition that is needed to be fulfilled we
use if-else-if ladder. It is basically nesting of if-else statement where we use
an if statement within another if statement. The example given below
explains further the use of nested if else statement:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;
The if statements follow top down approach. In the above demonstration of
nested if else as soon as the condition of the first if statement is true then
ten the statement in the TRUE part is executed. In case the statement is
FALSE it goes to else part where it meets with another if statement and the
whole process is repeated again until the program control executes all the
statements accordingly.

Sikkim Manipal University – DDE B2119 Page No. 42


Object Oriented Programming – Java Unit 3
The below program demonstrates the use of nested if-else statement. The
following program prints the type of month it is based on the month number:
// Demonstration nested if-else statements.
class IfElse {
public static void main(String args[ ]) {
int month_number = 4; // April
String season;
if(month_number == 12 || month_number == 1 || month_number == 2)
season = "Winter";
else if(month_number == 3 || month_number == 4 || month_number == 5)
season = "Spring";
else if(month_number == 6 || month_number == 7 || month_number == 8)
season = "Summer";
else if(month_number == 9 || month_number == 10 || month_number == 11)
season = "Autumn";
else
season = "Bogus month_number ";
System.out.println("April is in the " + season + ".");
}
}
Here is the output produced by the program:
April is in the Spring.
In the following program you can change the month_number and check the
output for the purpose of learning and better understanding of the nested if
else statement.
3.3.2 Switch Statement
The switch statement in Java provides multi – way branching. By multi way
I mean that by using one condition it can transfer the program control to
different set of instructions for execution. Switch statement proves to be
better alternative to nested if else, we do not have to write the if statement
multiple times.
Syntax of switch statement:
switch (expression) {

Sikkim Manipal University – DDE B2119 Page No. 43


Object Oriented Programming – Java Unit 3
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
The expression in the above mentioned syntax for the switch statement
must be of a valid type: int, float, etc. The value of case (value1, value2,..)
must comply with the datatype of expression. The value of cases must be
unique that is it must not have repetition, these values must be constant as
we cannot use variables. The break statements are not compulsory.
However, if we do not give break statement then once the execution
command is switched to the case which holds true, the cases falling after it
will also be execute. So to avoid it we use break statement.
The switch statement work as follow: once the command enters the switch
statement it checks the condition. After it checking the condition the value is
matched with values following the cases. Where the match is set, i.e.
whichever case have the correct value that corresponds to the expression;
the execution command is shifted to that case. The statements within the
case ae executed. If you use break statement, then after execution of the
statements in the following case the command jumps out of the switch
statement. In case you do not use break statement then all the cases after
the case with which the match had been set; are executed. An example of
switch…case statement is shown in the figure 3.7.

Sikkim Manipal University – DDE B2119 Page No. 44


Object Oriented Programming – Java Unit 3

Figure 3.7: The switch…case statement example

For example, consider the following program:


// In a switch, break statements are optional.
class NOBreak {
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:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more");
}
}
}

Sikkim Manipal University – DDE B2119 Page No. 45


Object Oriented Programming – Java Unit 3
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
Nested switch Statements
A switch statement can be used within another switch statement. This
procedure is called nested switch statement. The following example
shows the working of nested switch statement:
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: // ...
In the above example, the case 1 of inner switch do not conflict with the
case 1 of outer switch. Once the outer switch shifts the command control to
case 1 then inner switch is executed. You must not get confused with the
case 1 of inner switch with the case 1 of outer switch.
In summary, there are three important features of the switch statement to
note:
 The switch statement only checks equality compared to if else
statement where other relational operations can also be performed.

Sikkim Manipal University – DDE B2119 Page No. 46


Object Oriented Programming – Java Unit 3
 In same switch you cannot have two cases with similar value, however
you must not get confused with inner and outer switch as they different
and work differently, their cases can have same value as they are part of
two distinct switch statements.
 A switch statement are often more efficient compared to nested if
statements.
The last statements explain the working of Java compiler. When in Java, the
compiler encounters a switch statement it creates a jump table and based
on this table and expression of switch statement compiler jumps the
execution to different appropriate case that comply with the expression.
Henceforth if you have to select among a large pool of value switch
statements prove to be faster and more efficient compared to nested if
statements as in later case the compiler does not have any pre information
of long set of relational operations formed in a nested if-else statement.
3.3.3 For Loop
Syntax of for loop is as follow:
for (initial statement; termination condition; increment/decrement
instruction)
statement;
In a for loop the initialization of the variable used for condition checking, the
termination condition and the increment or decrement statement; need to
change the value of variable initialized in the first part are included in same
statement. They are separated by semicolon ‘;’. When the command enters
a for loop the initialization statement is executed first and then the
command shift to condition part. If the condition is TRUE, then the
statement included within the for loop is executed. Once execution is
completed the command shifts to increment/decrement part of the loop
statement. The value is changed accordingly and then again the command
shifts to condition part. Again if the condition is TRUE the above part is
repeated and if the condition becomes FALSE then the program control
exits the loop. Remember that the initialization statement is executed only
once and that too in the start of the for loop when the program statement
enters the for statement for the first time.
When multiple statements are to be included in the for loop, the statements
are included inside flower braces as below:

Sikkim Manipal University – DDE B2119 Page No. 47


Object Oriented Programming – Java Unit 3
for (initial statement; termination condition; increment instruction)
{
statement1;
statement2;
}

The example in the figure 3.8 prints numbers from 1 to 10.

Figure 3.8: For loop example program

The result of the above program is shown in the figure 3.9:

Figure 3.9: Result of the above for loop program

In Java for loop can be nested too, i.e. you can use a for loop within another
for loop. Following example shows the working of a nested for loop:
// Nested Loop.
class Nested {
public static void main(String args[ ]) {
int i, k;
for(i=0; i<5; i++) {
for(k=i; k<5; k++)
System.out.print("*");

Sikkim Manipal University – DDE B2119 Page No. 48


Object Oriented Programming – Java Unit 3
System.out.println();
}
}
}
The output produced by this program is shown here:
*****
****
***
**
*
Enhanced for statement: An another form of for statement also exists. It
performs iteration through collections and arrays. This form is also called
the enhanced for statement. Use of enhanced for statement makes loops
more compact and easy to understand. For the understanding of enhanced
for statement I am discussing array in advance, you will study about arrays
in details in next unit. For demonstrating the use of enhance for statement,
consider the example given below:
Example:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};

class EnhancedForDemo {
public static void main(String[] args){
int[] numbers =
{1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
In this example, the variable item holds the current value from the numbers
array. The output from this program is as follow:
Count is: 1
Count is: 2
Count is: 3

Sikkim Manipal University – DDE B2119 Page No. 49


Object Oriented Programming – Java Unit 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
It is recommended to use this enhance form of for statements wherever it is
possible to use.
3.3.4 While Loop
Like for statement while statement is used to create a loop based on
condition. As long as the condition is TRUE the block of statement (body of
loop) that falls under the while statement i.e. the while block is executed
repeatedly. Unlike for we just have the condition expression or statement
associated with the while statement. Here is its general form:
while (condition) {
// body of loop or while block
}
Figure 10.3 shows an example of while loop.

Figure 3.10: While loop example

3.3.5 Do…. While Loop


Do While Loop serve the same purpose as other loop statement but the
operation is a bit different than the other loops statements mentioned earlier.
Here the statement is executed first and then the condition is checked,
unlike other two loop where the condition was checked during the beginning.

Sikkim Manipal University – DDE B2119 Page No. 50


Object Oriented Programming – Java Unit 3
do While loop is exit control loop where as other are entry control loop.
Sometimes it is required the loop’s body has to be executed at least once
before the command exits the loops, in such cases do While loop is very
useful. Syntax of do While loop:
do {
// body of loop
} while (condition);
It’s clear from the syntax that once the program control enters a do while
loop then the body of the loop is executed before it checks the condition. If
the condition is TRUE, then the body of the loops is executed and then the
condition is checked. This process is repeated as long as the condition is
TRUE. Program control exits the loop if the condition in the while part
becomes FALSE. Following example in the figure 3.11 shows the working
of do while loop:

Figure 3.11: Do…while loop example

The do-while loop is useful for programs where we have to create some
Menu Selection List, as in a Menu Selection the Menu has to be executed at
least once before the user can enter choice. Consider the following program
which implements a very simple help system for Java's selection and
iteration statements:
// Using a do-while to process a menu selection
class Menu {
public static void main(String args[])
throws java.io.IOException {
char choice;

Sikkim Manipal University – DDE B2119 Page No. 51


Object Oriented Programming – Java Unit 3
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\\n");
System.out.println("Choose one:");
choice = (char) System.in.read();
} while( choice < '1' || choice > '5');
System.out.println("\\n");
switch(choice) {
case '1':
System.out.println("The if:\\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The while:\\n");
System.out.println("while(condition) statement;");
break;
case '4':
System.out.println("The do-while:\\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\\n");

Sikkim Manipal University – DDE B2119 Page No. 52


Object Oriented Programming – Java Unit 3
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break; } } }
Here is a sample run produced by this program:
Help on:
1. if
2. switch
3. while
4. do-while
5. for
Choose one:
The do-while:
do {
statement;
} while (condition);
In the above program the first do while loop is used to check for correct
input. Check the condition part, until the given input “choice” is not valid the
program control doesn’t exit the loop. Later we use switch statement to
perform the action based on the choice made.
3.3.6 Break Statement
Break statement is used to immediately terminate the loop. When the
program control encounters a break statement it jumps out of the loop. Here
is a simple example:
// Using break to exit a loop
class BreakLoop {
public static void main(String args[ ]) {
for(int i=0; i<50; i++) {
if(i == 5) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
This program generates the following output:
i: 0
i: 1
i: 2
Sikkim Manipal University – DDE B2119 Page No. 53
Object Oriented Programming – Java Unit 3
i: 3
i: 4
Loop complete.
The for loop is made to execute until the value of i reaches 49 however the
loop breaks when the value of i is equal to 5. Use of break statement leads
the termination of loop once i is equal to 5.
3.3.7 Continue Statement
Sometimes in some program we need to bypass immediate code and jump
back to the loop; condition part for a while and do while loop and
increment/decrement part in for loop; in such cases we use continue
statement.
The following program demonstrate the use of continue statement:
// Demonstration of continue statement.
class Continue {
public static void main (String args[ ]) {
for (int j=0; j<10; j++) {
System.out.print (j + " ");
if (j%2 == 0) continue;
System.out.println ("");
}
}
}
This code uses the % operator to check if j 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 loops to continue.
Self Assessment Questions
3. If-else is a looping statement. True or False.
4. Do…While is a decision making statement. True or False.

Sikkim Manipal University – DDE B2119 Page No. 54


Object Oriented Programming – Java Unit 3
3.4 Summary
This unit has given a brief overview of various operators and conditional
statements in Java. Let us summarize the concepts:
 Implementing Conditional Execution
You can control the flow of a program using the if construct. The if
construct allows selective execution of statements depending on the
value of the expressions associated with the if construct.
 Performing Repetitive Tasks Using Loop Construct
You can perform repetitive tasks by making use of the for construct.

3.5 Terminal Questions


1. What are the different types of operators used in Java?
2. What do you understand by operator precedence?
3. What are the different types of control statements?
4. Write Java program to print the address of the study center.
5. Write Java program to convert the Rupees to Dollars.
6. Write a Java program to compare whether your height is equal to your
friends height.
7. Write a Java program to find the sum of 1+3+5+…. for 10 terms in the
series.

3.6 Answers
Self Assessment Questions:
1 %
2 &
3 False
4 False
Terminal Questions
1. Arithmetic, Comparison and Logical Operators. (Refer Section 3.2.1 to
3.2.4)
2. When more than one operator is used in an expression, Java will use
operator precedence rule to determine the order in which the operators
will be evaluated. (Refer Section 3.2)
3. If…else, Switch…Case, For, While, Do…While, Break, and Continue.
(Refer Section 3.3.1 to 3.3.7)
(Terminal Questions 4 to 7 are programming exercises. For this, you should
go through this unit thoroughly.)
Sikkim Manipal University – DDE B2119 Page No. 55

You might also like