Merge pull request #16479 from sk1418/int-to-short

[int-to-short] int to short
This commit is contained in:
Liam Williams 2024-04-29 01:34:13 +01:00 committed by GitHub
commit 8cabe509a5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 71 additions and 0 deletions

View File

@ -0,0 +1 @@
### Relevant Articles:

View File

@ -0,0 +1,14 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-conversions.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-numbers-conversions-2</artifactId>
<packaging>jar</packaging>
<name>core-java-numbers-conversions-2</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
</project>

View File

@ -0,0 +1,55 @@
package com.baeldung.inttoshort;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class ConvertIntToShortUnitTest {
@Test
void whenUsingCasting_thenCorrect() {
short expected = 42;
int i = 42;
short result = (short) i;
assertEquals(expected, result);
}
@Test
void whenUsingIntegerShortValue_thenCorrect() {
short expected = 42;
Integer intObj = 42;
short result = intObj.shortValue();
assertEquals(expected, result);
}
@Test
void whenIntOutOfShortRange_thenGetTheUnexpectedResult() {
int oneMillion = 1_000_000;
short result = (short) oneMillion;
assertEquals(16960, result);
int twoMillion = 2_000_000;
result = (short) twoMillion;
assertEquals(-31616, result);
}
short intToShort(int i) {
if (i < Short.MIN_VALUE || i > Short.MAX_VALUE) {
throw new IllegalArgumentException("Int is out of short range");
}
return (short) i;
}
@Test
void whenCheckShortRangeBeforeCasting_thenGetExpectedResult() {
short expected = 42;
int int42 = 42;
assertEquals(expected, intToShort(int42));
int oneMillion = 1_000_000;
assertThrows(IllegalArgumentException.class, () -> intToShort(oneMillion));
}
}

View File

@ -36,6 +36,7 @@
<!-- <module>core-java-modules/core-java-18</module> --> <!-- JAVA-26056 -->
<!-- <module>core-java-modules/core-java-19</module> --> <!-- JAVA-26056 -->
<module>core-java-numbers-conversions</module>
<module>core-java-numbers-conversions-2</module>
<module>core-java-9-improvements</module>
<module>core-java-9-streams</module>
<module>core-java-9</module>