Skip to content

Commit 7b3b52c

Browse files
committed
[int-to-short] add intToShort()
1 parent 809460c commit 7b3b52c

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

core-java-modules/core-java-numbers-conversions-2/src/test/java/com/baeldung/inttoshort/ConvertIntToShortUnitTest.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.baeldung.inttoshort;
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
45

56
import org.junit.jupiter.api.Test;
67

@@ -33,4 +34,22 @@ void whenIntOutOfShortRange_thenGetTheUnexpectedResult() {
3334
assertEquals(-31616, result);
3435
}
3536

37+
short intToShort(int i) {
38+
if (i < Short.MIN_VALUE || i > Short.MAX_VALUE) {
39+
throw new IllegalArgumentException("Int is out of short range");
40+
}
41+
return (short) i;
42+
}
43+
44+
@Test
45+
void whenCheckShortRangeBeforeCasting_thenGetExpectedResult() {
46+
short expected = 42;
47+
int int42 = 42;
48+
assertEquals(expected, intToShort(int42));
49+
50+
int oneMillion = 1_000_000;
51+
assertThrows(IllegalArgumentException.class, () -> intToShort(oneMillion));
52+
53+
}
54+
3655
}

0 commit comments

Comments
 (0)