Descision making and Looping
Descision Making
• Decision-making statements in Java execute a
block of code based on a condition
• Conditional Statements: if, if-else, nested-if,
if-else-if
• Switch-Case: For multiple fixed-value checks
• Jump Statements: break, continue, return
– Labelled Loop
Conditional Statements
if Statement
• 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
}
if-else Statement
• if(condition){
• // Executes this block if
• // condition is true
• }else{
• // Executes this block if
• // condition is false
• }
nested-if Statement
• if (condition1) {
• // Executes when condition1 is true
• if (condition2)
• {
• // Executes when condition2 is true
• }
• }
if-else-if ladder
• if (condition1) {
• // code to be executed if condition1 is true
• } else if (condition2) {
• // code to be executed if condition2 is true
• } else {
• // code to be executed if all conditions are
false
• }
Switch Case
• switch (expression) {
• case value1:
• // code to be executed if expression == value1
• break;
• case value2:
• // code to be executed if expression == value2
• break;
• // more cases...
• default:
• // code to be executed if no cases match
• }
Loops in Java
Loops
• Execution of a set of instructions repeatedly
while some condition evaluates to true
• Java Loops
– for loop
– while loop
– do…while loop
For Loop
• Used when we know the number of
iterations
• Syntax
for (initialization; condition;
increment/decrement) {
// code to be executed
}
For Loop
Nested Loop
Enhanced For Loop[for each]
• Used to iterate over arrays or collections
• Syntax
Enhance For Loop
While Loop
• Used when we want to check the condition
before executing the loop body
• Syntax
While Loop
Do---while Loop
• do-while loop ensures that the code block
executes at least once before checking the
condition
• Syntax
Do---while Loop
Jump Statements
Jump Statements
break
• Used to jump out of switch statement
• Used to jump out of loop
• Keyword
• break;
break
continue
• Breaks one iteration (in the loop), if a
specified condition occurs, and continues
with the next iteration in the loop
• Keyword
• continue;
continue
return
• Used to explicitly return from a method
• Keyword:
–return
return
Labelled Loop
• Labeled loops provide a convenient way
to break or continue execution from within
nested loops, especially when dealing with
complex and deeply nested structures
• A label is a valid variable name (or identifier)
in Java that represents the name of the loop
to where the control of execution should jump
Labelelled Loop
Labelled Loop : break
Labelled Loop: continue