Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

Converting char to String instances is a very common operation. In this article, we will show multiple ways of tackling this situation.

2. String.valueOf()

The String class has a static method valueOf() that is designed for this particular use case. Here you can see it in action:

@Test
public void givenChar_whenCallingStringValueOf_shouldConvertToString() {
    char givenChar = 'x';

    String result = String.valueOf(givenChar);

    assertThat(result).isEqualTo("x");
}

3. Character.toString()

The Character class has a dedicated static toString() method. Here you can see it in action:

@Test
public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString() {
    char givenChar = 'x';

    String result = Character.toString(givenChar);

    assertThat(result).isEqualTo("x");
}

4. Character's Constructor

You could also instantiate Character object and use a standard toString() method:

@Test
public void givenChar_whenCallingCharacterConstructor_shouldConvertToString() {
    char givenChar = 'x';

    String result = new Character(givenChar).toString();

    assertThat(result).isEqualTo("x");
}

5. Implicit Cast to String Type

Another approach is to take advantage of widening conversion via type casting:

@Test
public void givenChar_whenConcatenated_shouldConvertToString() {
    char givenChar = 'x';

    String result = givenChar + "";

    assertThat(result).isEqualTo("x");
}

6. String.format()

Finally, you can use the String.format() method:

@Test
public void givenChar_whenFormated_shouldConvertToString() {
    char givenChar = 'x';

    String result = String.format("%c", givenChar);

    assertThat(result).isEqualTo("x");
}

7. Conclusion

In this article, we explored multiple ways of converting char instances to String instances.

All code examples can be found in the GitHub repository.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Junit footer banner
Comments are closed on this article!