Java Control Structures
Java Control Structures
Program control structures in Java include:
Sequential Structure: The program executes code sequentially according to the order of statements.
For example:int a = 1; int b = 2; int c = a + b; System.out.println(c);Branching Structures:
- if Statement: Selects different code paths based on conditions.
For example:int num = 10; if (num > 0) { System.out.println("num is positive"); } else if (num < 0) { System.out.println("num is negative"); } else { System.out.println("num is zero"); } - switch Statement: Selects different code paths based on the value of a variable.
For example:int dayOfWeek = 2; switch (dayOfWeek) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; default: System.out.println("Weekend"); break; }
- if Statement: Selects different code paths based on conditions.
Loop Structures:
- for Loop: Repeats a block of code until a specific condition is met to stop execution.
For example:for (int i = 0; i < 5; i++) { System.out.println(i); } - while Loop: Repeats a block of code while a specified condition remains true.
For example:int i = 0; while (i < 5) { System.out.println(i); i++; } - do-while Loop: Executes a block of code once first, then repeats it as long as a specified condition is met.
For example:int i = 0; do { System.out.println(i); i++; } while (i < 5);
- for Loop: Repeats a block of code until a specific condition is met to stop execution.
Jump Structures:
- break Statement: Exits the current loop or switch statement.
For example:for (int i = 0; i < 5; i++) { if (i == 3) { break; } System.out.println(i); } - continue Statement: Skips the remaining code in the current loop iteration and proceeds to the next iteration.
For example:for (int i = 0; i < 5; i++) { if (i == 3) { continue; } System.out.println(i); } - return Statement: Returns the execution result of a function.
For example:public int add(int a, int b) { int c = a + b; return c; }
- break Statement: Exits the current loop or switch statement.