Java – For-Each Loop
For-Each Loop: Used to iterate over arrays or collections.Example: int[] numbers = {1, 2, 3, 4, 5};for (int num : numbers) { System.out.println(num);}
For-Each Loop: Used to iterate over arrays or collections.Example: int[] numbers = {1, 2, 3, 4, 5};for (int num : numbers) { System.out.println(num);}
Sum of array elements:Example: int[] numbers = {1, 2, 3, 4, 5};int sum = 0;for (int num : numbers) { sum += num;}System.out.println("Total: " + sum);
Loops are control flow statements that repeat code execution until a specified condition is met. Types of loops include For, While, Do-While, and For-Each. Each has specific use cases.
For Loop: Iterates for a specific number of times.Example: for (int i = 1; i
Calculate the sum of numbers:Example: int sum = 0;for (int i = 1; i
While Loop: Executes as long as the condition is true.Example: int i = 1;while (i
Check if a number is prime:Example: int num = 29;int i = 2;boolean isPrime = true;while (i
Do-While Loop: Executes at least once before condition check.Example: int i = 1;do { System.out.println(i); i++;} while (i
Validate user input with do-while loop:Example: Scanner sc = new Scanner(System.in);int input;do { System.out.print("Enter a positive number: "); input = sc.nextInt();} while (input
Sealed Classes restrict which classes can extend or implement them.Example: sealed class Shape permits Circle, Rectangle {}final class Circle extends Shape {}final class Rectangle extends Shape {}