This commit is contained in:
Bogdan Pistol 2022-12-15 06:03:07 +02:00 committed by GitHub
parent 9e7a6d2b3d
commit df30c2986f
2 changed files with 83 additions and 0 deletions

View File

@ -0,0 +1,47 @@
package com.baeldung.convertinttochar;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class ConvertCharToIntUnitTest {
@Test
public void givenAChar_whenUsingGetNumericValue_thenExpectedNumericType() {
//char value
char c = '7';
// using getNumericValue
int n = Character.getNumericValue(c);
assertEquals(7, n);
}
@Test
public void givenAChar_whenSubtracting0_thenExpectedNumericType() {
//char value
char c = '7';
// subtract '0' from the char
int n = c - '0';
assertEquals(7, n);
}
@Test
public void givenAChar_whenUsingParseInt_thenExpectedNumericType() {
//char value
char c = '7';
// using parseInt
int n = Integer.parseInt(String.valueOf(c));
assertEquals(7, n);
}
@Test
public void givenAChar_whenCastingFromCharToInt_thenExpectedUnicodeRepresentation() {
//char value
char c = '7';
//cast to int
assertEquals(55, (int) c);
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.convertinttochar;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class ConvertIntToCharUnitTest {
@Test
public void givenAnInt_whenAdding0_thenExpectedCharType() {
int num = 7;
//add '0' to convert int to char
char c = (char) ('0' + num);
assertEquals('7', c);
}
@Test
public void givenAnInt_whenUsingForDigit_thenExpectedCharType() {
int num = 7;
// Convert using forDigit() method
char c = Character.forDigit(num, 10);
assertEquals('7', c);
}
@Test
public void givenAnInt_whenUsingToString_thenExpectedCharType() {
int num = 7;
//convert int to char using toString()
char c = Integer.toString(num)
.charAt(0);
assertEquals('7', c);
}
}