Great job diving into data types and variables! Now, let’s explore the dynamic nature of Java through control flow statements.
Control Flow Statements in Java:
- If Statement: The if statement allows you to execute a block of code if a certain condition is true. Here’s a simple example:
javaCopy code
int score = 85; if (score >= 80) { System.out.println(“Excellent!”); }
- If-Else Statement: Use if-else when you want to execute different code blocks based on a condition:
javaCopy code
int temperature = 25; if (temperature > 30) { System.out.println(“It’s hot outside!”); } else { System.out.println(“The weather is pleasant.”); }
- Switch Statement: When dealing with multiple possible conditions, the switch statement is handy:
javaCopy code
int day = 3; switch (day) { case 1: System.out.println(“Monday”); break; case 2: System.out.println(“Tuesday”); break; // … additional cases default: System.out.println(“Invalid day”); }
- Loops – For Loop: The for loop is used for iterating over a set of statements a specific number of times:
javaCopy code
for (int i = 1; i <= 5; i++) { System.out.println(“Iteration ” + i); }
- Loops – While Loop: The while loop repeats a block of code while a given condition is true:
javaCopy code
int count = 0; while (count < 3) { System.out.println(“Count: ” + count); count++; }
- Loops – Do-While Loop: Similar to the while loop, but guarantees the code block is executed at least once:
javaCopy code
int attempts = 0; do { System.out.println(“Attempt #” + attempts); attempts++; } while (attempts < 3);
Now, with control flow statements at your disposal, you can create more dynamic and responsive Java programs.
Next up: Classes and Objects in Java – where we’ll step into the world of object-oriented programming.
Keep coding and exploring the vast possibilities of Java!