Skip to content

Commit 47e617f

Browse files
cdjolemaibin
authored andcommitted
Method inlining example. (eugenp#6520)
* Method inlining example. * Test added
1 parent cd57889 commit 47e617f

3 files changed

Lines changed: 57 additions & 0 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.baeldung.inlining;
2+
3+
public class ConsecutiveNumbersSum {
4+
5+
private long totalSum;
6+
private int totalNumbers;
7+
8+
public ConsecutiveNumbersSum(int totalNumbers) {
9+
this.totalNumbers = totalNumbers;
10+
}
11+
12+
public long getTotalSum() {
13+
totalSum = 0;
14+
for (int i = 1; i <= totalNumbers; i++) {
15+
totalSum += i;
16+
}
17+
return totalSum;
18+
}
19+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.baeldung.inlining;
2+
3+
public class InliningExample {
4+
5+
public static final int NUMBERS_OF_ITERATIONS = 15000;
6+
7+
public static void main(String[] args) {
8+
for (int i = 1; i < NUMBERS_OF_ITERATIONS; i++) {
9+
calculateSum(i);
10+
}
11+
}
12+
13+
private static long calculateSum(int n) {
14+
return new ConsecutiveNumbersSum(n).getTotalSum();
15+
}
16+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.baeldung.inlining;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.assertEquals;
6+
7+
public class ConsecutiveNumbersSumUnitTest {
8+
9+
private static final int TOTAL_NUMBERS = 10;
10+
11+
@Test
12+
public void givenTotalIntegersNumber_whenSumCalculated_thenEquals() {
13+
ConsecutiveNumbersSum consecutiveNumbersSum = new ConsecutiveNumbersSum(TOTAL_NUMBERS);
14+
long expectedSum = calculateExpectedSum(TOTAL_NUMBERS);
15+
16+
assertEquals(expectedSum, consecutiveNumbersSum.getTotalSum());
17+
}
18+
19+
private long calculateExpectedSum(int totalNumbers) {
20+
return totalNumbers * (totalNumbers + 1) / 2;
21+
}
22+
}

0 commit comments

Comments
 (0)