Algorithm
Algorithm to Convert Character to String:
- Start
- Declare a character variable (e.g.,
charValue
) and assign the desired character. - Create a string using the
String.valueOf(charValue)
method. - The resulting string now contains the character representation.
- End
Algorithm to Convert String to Character:
- Start
- Declare a string variable (e.g.,
stringValue
) and assign the desired string containing a single character. - Use the
charAt(0)
method to extract the first character from the string. - Assign the extracted character to a character variable (e.g.,
charValue
). - Now,
charValue
holds the character representation of the initial string. - End
Code Examples
#1 Code Example- Convert char to String
Code -
Java Programming
public class CharString {
public static void main(String[] args) {
char ch = 'c';
String st = Character.toString(ch);
// Alternatively
// st = String.valueOf(ch);
System.out.println("The string is: " + st);
}
}
Copy The Code &
Try With Live Editor
Output
The string is: c
#2 Code Example- Convert char array to String
Code -
Java Programming
public class CharString {
public static void main(String[] args) {
char[] ch = {'a', 'e', 'i', 'o', 'u'};
String st = String.valueOf(ch);
String st2 = new String(ch);
System.out.println(st);
System.out.println(st2);
}
}
Copy The Code &
Try With Live Editor
Output
aeiou
aeiou
aeiou
#3 Code Example- Convert String to char array
Code -
Java Programming
import java.util.Arrays;
public class StringChar {
public static void main(String[] args) {
String st = "This is great";
char[] chars = st.toCharArray();
System.out.println(Arrays.toString(chars));
}
}
Copy The Code &
Try With Live Editor
Output
[T, h, i, s, , i, s, , g, r, e, a, t]
Demonstration
Java Programing Example to Convert Character to String and Vice-Versa-DevsEnv