Convert Char to String

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to convert a character char to a string String in Java.

Convert Char to String Using valueOf() Method

  • Open your terminal and create a Java file using the below command:

    touch ConvertCharToString.java
  • Open the file using a text editor and paste the below code:

    public class ConvertCharToString {
      public static void main(String[] args) {
        char ch = 's';
        System.out.println(ch);
        String str = String.valueOf(ch);
        System.out.println(str);
        System.out.println(str.getClass().getName());
      }
    }
  • Compile the Java code using the below command in the terminal:

    javac ConvertCharToString.java
  • Run the Java code using the below command in the terminal:

    java ConvertCharToString
  • The output will be:

    s
    s
    java.lang.String

Convert Char to String Using toString() Method

  • Open the same ConvertCharToString.java file in the text editor and replace the main method with the below code:

    public static void main(String[] args){
      char ch = 's';
      System.out.println(ch);
      String str = Character.toString(ch);
      System.out.println(str);
      System.out.println(str.getClass().getName());
    }
  • Compile the Java code using the below command in the terminal:

    javac ConvertCharToString.java
  • Run the Java code using the below command in the terminal:

    java ConvertCharToString
  • The output will be:

    s
    s
    java.lang.String

Convert Char to String Using + Operator

  • Open the same ConvertCharToString.java file in the text editor and replace the main method with the below code:

    public static void main(String[] args){
      char ch = 's';
      System.out.println(ch);
      String str = ""+ch;
      System.out.println(str);
      System.out.println(str.getClass().getName());
    }
  • Compile the Java code using the below command in the terminal:

    javac ConvertCharToString.java
  • Run the Java code using the below command in the terminal:

    java ConvertCharToString
  • The output will be:

    s
    s
    java.lang.String

Summary

In this lab, you have learned how to convert a character char to a string String in Java using different methods. You can use either valueOf() or toString() methods or plus (+) operator to convert a character to a string.

Other Java Tutorials you may like