0% found this document useful (0 votes)
24 views17 pages

ControlStatementsinJavapdf 2024 08-28-16!17!42

Uploaded by

Ayush Batra
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)
24 views17 pages

ControlStatementsinJavapdf 2024 08-28-16!17!42

Uploaded by

Ayush Batra
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/ 17

Study Material by Ms Manmeet Kaur

Decision Making in Java


(if, if-else, switch, break, continue, jump)

Decision Making in programming is similar to decision-making in real life. In


programming also face some situations where we want a certain block of code to be
executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of
a program based on certain conditions. These are used to cause the flow of execution
to advance and branch based on changes to the state of a program.
Java’s Selection statements:
 if
 if-else
 nested-if
 if-else-if
 switch-case
 jump – break, continue, return

1.if statement: if statement is the most simple decision-making statement. It is used


to decide whether a certain statement or block of statements will be executed or not
i.e if a certain condition is true then a block of statements is executed otherwise not.

Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}

Here, the condition after evaluation will be either true or false. if statement accepts
boolean values – if the value is true then it will execute the block of statements
under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default
if statement will consider the immediate one statement to be inside its block. For
example,
if(condition) //Assume condition is true
statement1; //part of if block
Study Material by Ms Manmeet Kaur

statement2; // separate from if block

// Here if the condition is true


// if block will consider statement1 as its part and executes in only true condition
// statement2 will be separate from the if block so it will always executes whether the condition
is true or false.

2. if-else: The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won’t. But what if we want to do
something else if the condition is false? Here comes the else statement. We can use
Study Material by Ms Manmeet Kaur

the else statement with the if statement to execute a block of code when the
condition is false.
Syntax:

if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

3. nested-if: A nested if is an if statement that is the target of another if or else.


Nested if statements mean an if statement inside an if statement. Yes, java allows us
to nest if statements within if statements. i.e, we can place an if statement inside
another if statement.
Study Material by Ms Manmeet Kaur

Syntax:

if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

4. if-else-if ladder: Here, a user can decide among multiple options.The if


statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that ‘if’ is executed, and the
rest of the ladder is bypassed. If none of the conditions is true, then the final else
Study Material by Ms Manmeet Kaur

statement will be executed. There can be as many as ‘else if’ blocks associated with
one ‘if’ block but only one ‘else’ block is allowed with one ‘if’ block.
Syntax:
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;

5. switch-case: The switch statement is a multiway branch statement. It provides an


easy way to dispatch execution to different parts of code based on the value of the
expression.
Syntax:
Study Material by Ms Manmeet Kaur

switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Study Material by Ms Manmeet Kaur
Study Material by Ms Manmeet Kaur

6. jump: Java supports three jump statements: break, continue and return. These
three statements transfer control to another part of the program.
 Break: In Java, a break is majorly used for:
o Terminate a sequence in a switch statement (discussed above).
o To exit a loop.
o Used as a “civilized” form of goto.
 Continue: Sometimes it is useful to force an early iteration of a loop. That is,
you might want to continue running the loop but stop processing the remainder of
the code in its body for this particular iteration. This is, in effect, a goto just past
the body of the loop, to the loop’s end. The continue statement performs such an
action.

 Return: The return statement is used to explicitly return from a method. That is,
it causes program control to transfer back to the caller of the method.

Conditional Operator
Study Material by Ms Manmeet Kaur

Conditional operators are used in programming just as we make decisions in real


life. It controls the flow of the program and produces outcomes based on the
provided conditions. There are three types of Conditional Operators: Conditional
AND, Conditional OR and Ternary Operator.

Introduction to Conditional Operator in Java

Suppose you are given a number of regular polygons; you need to categorize them
into their types. Three-sided polygon into a triangle, four-sided into a quadrilateral
and so on. How do we execute these conditions and obtain the correct output? Here
comes the role of Conditional Operators in Java.

Conditional Operators in Java are used to work on conditions. It is a unique


operator used in place of 'If-else' statements. They make complex code much easy
to write and understand. How? you ask! Let's dive in and and find out.

Three Types of Conditional Operator in java

There are three types of the conditional operators in Java:

1. Conditional AND
2. Conditional OR
3. Ternary Operator
Study Material by Ms Manmeet Kaur

Conditional AND (&&)

 Syntax: &&

The best way to remember the output of AND operator is: The output is only true
whenever both the expressions surrounding the operator are true.

Conditional OR (||)

 Syntax: ||
 The best way to remember the output of OR operator is: The output is only
true whenever either of the expressions surrounding the operator is true.
 Ternary Operator
 The word ternary is the amalgamation of three parts. It is so named because
it consists of three operands. A ternary operator is a condensed form of an if-
else statement that evaluates a condition and executes the code based on the
evaluated condition. Let's clearly understand how a ternary operator is
written and used.
 Teranry Operator Syntax:
result = (condition) ? expression1: expression2

result: The final variable which gets the value.

condition: This is the test condition statement that gets evaluated to true or false.

expression1: If condition gets evaluated to true then expression1 is assigned to


result.

expression2 : If condition gets evaluated to false then expression 2 is assigned to


result.

The only thing to remember when using ternary operation is: The very first
operand must be a Boolean expression, and the second and third operands can
be any expression that returns some value.
Study Material by Ms Manmeet Kaur

Loops in Java (for, while, do-while)


Looping is a feature that facilitates the execution of a set of instructions repeatedly
until a certain condition holds false. Java provides three types of loops namely
the for loop, the while loop, and the do-while loop. Loops are also known as Iterating
statements or Looping constructs in Java.

Need for Looping Constructs in Java

A computer is most suitable for performing repetitive tasks and can tirelessly do tasks tens of
thousands of times. We need Loops because

 Loops facilitates 'Write less, Do more' - We don't have to write the same code again and again.
 They reduce the size of the Code.
 Loops make an easy flow of the control.
 They also reduce the Time Complexity and Space Complexity - Loops are faster and more
feasible as compared to Recursion.

Elements of the Loops in Java

1. Initialization Expression(s): Initialization is carried out only once before entering the loop.
Here, we either declare and initialize a control variable(s) or only initialize the variable(s) we are
going to use in looping. We can initialize multiple variables as well.
2. Test Expression (Condition): It is a boolean expression. Its value decides whether the loop will
be executed or terminated. If the condition is satisfied, the control goes inside the loop, otherwise,
it is terminated. In an exit-controlled loop, the test expression is evaluated before exiting from the
loop whereas in an entry-controlled loop the test expression is evaluated before entering the loop.
3. Body of the Loop: The statements that are to be executed repeatedly are written in the body of
the Loop. They are executed until the condition of the loop is true.
4. Update Expression(s): Here, we update the value of the loop variable(s). It is used so that after
some point of time the loop terminates. It is executed at the end of the loop when the loop-body
has been executed and the next iteration is to start. It is also
called Increment/Decrement expression since in most of the cases value of loop variables is
either incremented or decremented.

Types of Loops in Java

There are three types of Loops. They are:

1. while Loop
2. do-while Loop
3. for Loop
Study Material by Ms Manmeet Kaur

while Loop

The while loop is used when the number of iterations is not known but the terminating condition
is known. Loop is executed until the given condition evaluates to false. while loop is also
an entry-controlled loop as the condition is checked before entering the loop. The test condition
is checked first and then the control goes inside the loop.

Although for loop is easy to use and implement, there may be situations where the programmer
is unaware of the number of iterations, it may depend on the user or the system. Thus, when the
only iterating and/or terminating condition is known, a while loop is to be used.

While loop is much like repeating if statement.

Syntax:

Initialization;

while(Test Expression){

// Body of the Loop (Statement(s))

Updation;

}
Working of a while Loop

Firstly, the test expression is checked. If it evaluates to true, the statement is executed and again
condition is checked. If it evaluates to false the loop is terminated.
Study Material by Ms Manmeet Kaur

Example: Let us look at an example where we find the factorial of a number. So,
until i is not equal to 0, while loop will be executed, and i will be multiplied to
variable fact.

public class Main {

public static void main(String args[]) {

int factorial = 1, number = 5, tempNum = 0;

tempNum = number; // Initialization;

while (tempNum != 0) { // Test Expression

factorial = factorial * tempNum;

--tempNum; //Updation;

System.out.println("The factorial of " + number + " is: " + factorial);

do-while Loop

The do-while loop is like the while loop except that the condition is checked after evaluation of
the body of the loop. Thus, the do-while loop is an example of an exit-controlled loop.

The loop is executed once, and then the condition is checked for further iterations. This loop runs
at least once irrespective of the test condition, and at most as many times the test condition
evaluates to true. It is the only loop that has a semicolon(;).

Need for do-While Loop: The instructions inside for and while loops are not evaluated if the
condition is false. In some cases, it is wanted that the loop body executes at least once
irrespective of the initial state of test expression. This is where the do-while loop is used.

Syntax:

Initialization;
Study Material by Ms Manmeet Kaur

do {

// Body of the loop (Statement(s))

// Updation;

while(Test Expression);

Working of a do-while Loop

The body of do-while loop is executed once no matter what the initial condition is. Then the
condition is checked. If it is true then the loop is executed else it is terminated. Condition is
checked at the end of the execution of the body

Example:

import java.util.Scanner;

public class Main {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

do {

// Take numbers as input

System.out.print("Enter First Number: ");


Study Material by Ms Manmeet Kaur

int first = sc.nextInt();

System.out.print("Enter Second Number: ");

int second = sc.nextInt();

// Print the choice list

System.out.println(

"Enter your choice \n1 Add\n2 Subtract\n3 Multiply\n4 Divide"

);

// Perform the required operation

switch (sc.nextInt()) {

case 1:

first += second;

break;

case 2:

first -= second;

break;

case 3:

first *= second;

break;

case 4:

first /= second;

break;
Study Material by Ms Manmeet Kaur

// Print the output

System.out.println("Result is " + first + ".");

System.out.println("To continue enter 1, to exit enter 0");

} while (1 == sc.nextInt()); // test Expression

for Loop

When we know the exact number of times the loop is going to run, we use for loop. It provides a
concise way of writing initialization, test condition, and increment/decrement statements in one
line. Thus, it is easy to debug and also has no risk of forgetting any part of the loop, since the
condition is checked before.

For loop is an entry-controlled loop as we check the condition first and then evaluate the body
of the loop.

Syntax:

for(Initialization ; Test Expression ; Updation){

// Body of the Loop (Statement(s))

Working of a for Loop

Firstly Initialization expression is executed. Then the test expression is evaluated. If it


is true then control goes inside the body of the loop, otherwise, loop is terminated. After
execution update expression is carried out. If the test expression evaluates to false the loop is
terminated else the body of the loop is again executed. This process continues until the test
Study Material by Ms Manmeet Kaur

expression becomes false. If the test expression never becomes false, it is the case of an infinite
loop.

Example

public class Main {

public static void main(String[] args) {

int maxNum = 5;

/* loop will run 5 times until test condition becomes false */

for (int i = 1; i <= maxNum; i++) {

System.out.println(i);

You might also like