Control flow statements: if-else, switch-case, loops
Control flow statements allow you to control the flow of execution in your Java programs. They include if-else statements for decision-making, switch-case statements for multi-way branching, and loops for repetitive execution.
Examples
In order to run the Java code examples, you need to create a Java class with a main method. See the example. Copy and paste the examples within your main method to run them.
public class Examples { public static void main(String[] args) { } }
// Example 1: Using if-else statement to check for a condition int num = 10; if (num > 0) { System.out.println("Positive number"); } else { System.out.println("Negative number"); } // Example 2: Using switch-case to perform different actions based on a variable int choice = 2; switch (choice) { case 1: System.out.println("Option 1 selected"); break; case 2: System.out.println("Option 2 selected"); break; default: System.out.println("Invalid choice"); } // Example 3: Using loops to iterate through a collection String[] fruits = {"Apple", "Banana", "Orange"}; for (String fruit : fruits) { System.out.println(fruit); }
FAQ (interview questions and answers)
-
What is the purpose of if-else statement?
To declare variables
To make decisions based on conditions
To perform arithmetic operations
-
When would you use a switch-case statement?
When you need to repeat a block of code
When you need to declare variables
When you have multiple options to choose from
-
What does a for loop do?
Performs a single action
Iterates through a collection of items
Checks a condition
-
How do you handle multiple conditions in Java?
Using loops
Using variables
Using if-else or switch-case statements
-
Can you use multiple conditions in a switch-case statement?
No
Yes
Depends on the compiler
Your Total Score: 0 out of 5
Remember to just comment if you have any doubts or queries.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.