BUGSPOTTER

Control statements in core Java

Control statement in core Java

Control statements in Java manage the flow of execution, enabling decision-making and repetition. The if, else, and switch statements allow conditional execution, while loops like for, while, and do-while enable repeated execution of code. These statements are essential for controlling program behavior based on conditions or iteration.

Types of control Statements

  1. Decision-Making: if, if-else, if-else if-else, switch
  2. Loops: for, while, do-while
  3. Jump Statements: break, continue, return

1. Decision-Making Statements

if: Executes a block of code if the condition is true.

if (condition) { // code to execute  }

if-else: Executes one block of code if the condition is true, and another if false.

if (condition) { // code for true 
} else { // code for false }

if-else if-else: Allows multiple conditions to be tested sequentially.

if (condition1) { 
// code for condition1
} else if (condition2) {
// code for condition2
} else {
// code if no conditions are true }

switch: Compares a variable to multiple possible values and executes the corresponding block.

switch (variable) {
case value1: // code for value1
break;
case value2:
// code for value2
break;
default:
// default code
}

2.Looping Statements

for: Executes a block of code for a specific number of iterations.

for (int i = 0; i < 5; i++) {
// code to execute
}

while: Repeats a block of code as long as the condition is true (condition checked before execution).

while (condition) {
// code to execute
}

do-while: Similar to while, but checks the condition after execution (ensures at least one execution).

do { // code to execute 
} while (condition);

3.Jump Statements

break: Exits the current loop or switch statement.

for (int i = 0; i < 5; i++) { 
if (i == 3) {
break; // exits the loop when i is 3
}
}

continue: Skips the current iteration of a loop and moves to the next iteration

for (int i = 0; i < 5; i++) { 
if (i == 3) {
continue; // skips when i is 3
}
System.out.println(i);
}

return: Exits from the current method and optionally returns a value.

int sum(int a, int b) { 
return a + b;
// exits the method and returns the result
}

Latest Posts

  • All Posts
  • Software Testing
  • Uncategorized
Load More

End of Content.

Enroll Now and get 5% Off On Course Fees