Welcome to my blog, hope you enjoy reading
RSS

Friday 8 February 2013

How to convert Character to String and a String to Character Array in Java


How to convert Character to String and a String to Character Array in Java

In this short tutorial we are going to see how to convert  a Character to a String and a String to a StringArray.
In the first Java program we convert a Character to String. Basically there are two ways to do that:
  • the Character.toString(char ) method of the Character class
  • the String.valueOf(char ) method of the String Class.
To be precise the  Character.toString(char ) method internally uses  String.valueOf(char ) method. So you are be better off withString.valueOf(char).

package com.javanotes2all.java.string; public class CharToString { public static void main(String[] args) { char ch = 'J'; String string1 = Character.toString(ch); String string2 = String.valueOf(ch); System.out.println("character is : " + ch + ". String using String.valueOf(char c): " + string2); System.out.println("character is : " + ch + ". String using Character.toString(char c): " + string1); } }
OUTPUT:
character is : J. String using String.valueOf(char c):  J
character is : J. String using Character.toString(char c):  J

Now we are going to use String.toCharArray() to convert a string into an array of characters.



package com.javanotes2all.java.string;

import java.util.Arrays;

public class StringToCharArray {

 public static void main(String[] args) 
        {

 String string = "javanotes2all";

 char[] charArray = string.toCharArray();

 System.out.println("String is:" + string + " Character Array : "
   + Arrays.toString(charArray));
 }

}
As you can see I am using Arrays.toString(char[]) in order to print the character array in a more readable way. So the output will be:
OUTPUT:

String is:javanotes2all Character Array : [j, a, v, a, n, o, t, e, s, 2, a, l, l]

0 comments: