Skip to content

Commit 29bfac0

Browse files
shouvikbhattacharyapivovarit
authored andcommitted
BAEL-1305: A Simple Guide to Java Loops. (eugenp#3133)
1 parent 1b0f99a commit 29bfac0

2 files changed

Lines changed: 80 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.baeldung.loops;
2+
3+
public class LoopsInJava {
4+
5+
public int[] simple_for_loop() {
6+
int[] arr = new int[5];
7+
for (int i = 0; i < 5; i++) {
8+
arr[i] = i;
9+
System.out.println("Simple for loop: i - " + i);
10+
}
11+
return arr;
12+
}
13+
14+
public int[] enhanced_for_each_loop() {
15+
int[] intArr = { 0, 1, 2, 3, 4 };
16+
int[] arr = new int[5];
17+
for (int num : intArr) {
18+
arr[num] = num;
19+
System.out.println("Enhanced for-each loop: i - " + num);
20+
}
21+
return arr;
22+
}
23+
24+
public int[] while_loop() {
25+
int i = 0;
26+
int[] arr = new int[5];
27+
while (i < 5) {
28+
arr[i] = i;
29+
System.out.println("While loop: i - " + i++);
30+
}
31+
return arr;
32+
}
33+
34+
public int[] do_while_loop() {
35+
int i = 0;
36+
int[] arr = new int[5];
37+
do {
38+
arr[i] = i;
39+
System.out.println("Do-While loop: i - " + i++);
40+
} while (i < 5);
41+
return arr;
42+
}
43+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.baeldung.loops;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
public class WhenUsingLoops {
7+
8+
private LoopsInJava loops = new LoopsInJava();
9+
10+
@Test
11+
public void shouldRunForLoop() {
12+
int[] expected = { 0, 1, 2, 3, 4 };
13+
int[] actual = loops.simple_for_loop();
14+
Assert.assertArrayEquals(expected, actual);
15+
}
16+
17+
@Test
18+
public void shouldRunEnhancedForeachLoop() {
19+
int[] expected = { 0, 1, 2, 3, 4 };
20+
int[] actual = loops.enhanced_for_each_loop();
21+
Assert.assertArrayEquals(expected, actual);
22+
}
23+
24+
@Test
25+
public void shouldRunWhileLoop() {
26+
int[] expected = { 0, 1, 2, 3, 4 };
27+
int[] actual = loops.while_loop();
28+
Assert.assertArrayEquals(expected, actual);
29+
}
30+
31+
@Test
32+
public void shouldRunDoWhileLoop() {
33+
int[] expected = { 0, 1, 2, 3, 4 };
34+
int[] actual = loops.do_while_loop();
35+
Assert.assertArrayEquals(expected, actual);
36+
}
37+
}

0 commit comments

Comments
 (0)