Java - Convert a character to string

By IncludeHelp Last updated : January 30, 2024

Problem statement

Given a character and we have to convert it to the string in Java.

Converting a character to string

To convert a character to string, there are two ways:

  1. Using String.valueOf(character) method
  2. Using Character.toString(character) method

Converting a character to string using String.valueOf() method

The valueOf() method is a String class method, it accepts a character (character array also) and returns the string.

Example

public class Main {
  public static void main(String[] args) {
    char char_value = 'X';
    String str = "";

    //converting from char to string
    str = String.valueOf(char_value);

    //printing value 
    System.out.println("str = " + str);

  }
}

Output

str = X

Converting a character to string using Character.toString() method

The toString() method is a Character class method, it accepts the character (character array also) and returns the string.

Example

public class Main {
  public static void main(String[] args) {
    char char_value = 'X';
    String str = "";

    //converting from char to string
    str = Character.toString(char_value);

    //printing value 
    System.out.println("str = " + str);

  }
}

Output

str = X

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.