Sponsored Link

Tuesday, March 26, 2013

Java :: How to convert primitive char to String in Java

Char is 16 bit unsigned data type in Java used to store characters and String is an immutable array of char. In Java you cannot cast a primitive char element to String.

Below I have given five methods to convert a char to String. Also I have included common mistakes that gives compile time errors.

package com.deepumohan.tech.chartostring;

public class CharToString {

   public static void main(String[] args) {
     char x = 'x';
     System.out.println(concatBlankString(x));
     System.out.println(stringValueOf(x));
     System.out.println(characterToString(x));
     System.out.println(characterObjectToString(x));
     System.out.println(charArray(x));
   }
 
   // append a blank string
   public static String concatBlankString(char x) {
      return x + "";
   }

   // use String.valueOf(char) static function
   public static String stringValueOf(char x) {
      return String.valueOf(x);
   }

   // use Character.toString(char) static function
   public static String characterToString(char x) {
      return Character.toString(x);
   }

   // create new Character object from the given char and
   // then use object's toString() method
   public static String characterObjectToString(char x) {
      return new Character(x).toString();
   } 

   // create new char[] array from the char and pass it to
   // String constructor
   public static String charArray(char x) {  
      return new String(new char[]{x});
   }

/*
   // Compile time error
   // No suitable constructor found
   public static String noConstructor(char x) { 
      return new String(x);
   }

   // Compile time error
   // Inconvertible types
   public static String inconvertibleTypes(char x) {
      return (String) x;
   }
*/
}

I wonder why Java doesn't include String constructor that accept a single char as argument.

Also see

Related Posts Plugin for WordPress, Blogger...

Next To Read