Controlling The Flow Of A Java Program

 

Conditional Statements:

  1. if-else Statement:

    • Syntax:
    • if (condition) { // Code to execute if condition is true } else { // Code to execute if condition is false }

    • Example:
      int num = 10; if (num > 0) { System.out.println("Positive number"); } else { System.out.println("Non-positive number"); }

  2. switch Statement:

    • Syntax:
    • switch (expression) { case value1: // Code to execute if expression equals value1 break; case value2: // Code to execute if expression equals value2 break; default: // Code to execute if expression doesn't match any case }

    • Example:
      char grade = 'B'; switch (grade) { case 'A': System.out.println("Excellent"); break; case 'B': System.out.println("Good"); break; case 'C': System.out.println("Average"); break; default: System.out.println("Not a valid grade"); }

Looping Constructs:

  1. for Loop:

    • Syntax:
    • for (initialization; condition; update) { // Code to execute repeatedly }

    • Example:
      for (int i = 0; i < 5; i++) { System.out.println("Iteration " + (i + 1)); }

  2. while Loop:

    • Syntax:
    • while (condition) { // Code to execute repeatedly }

    • Example:
      int i = 0; while (i < 5) { System.out.println("Iteration " + (i + 1)); i++; }

do-while Loop:

  • Syntax:
  • do { // Code to execute repeatedly } while (condition);

  • Example:
    int i = 0; do { System.out.println("Iteration " + (i + 1)); i++; } while (i < 5);

These constructs allow you to control the flow of your Java program based on conditions and perform repetitive tasks using looping mechanisms.

Post a Comment

0 Comments