Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
158 views
in JAVA by (117k points)
Explain Java Convert char to String

Please log in or register to answer this question.

1 Answer

0 votes
by (117k points)

In Java, converting a char to a String is a straightforward process. You can achieve this using multiple approaches. 

Here's an example code demonstrating some of the common methods:

public class CharToStringExample {
    public static void main(String[] args) {
        // Method 1: Using String.valueOf(char)
        char c = 'A';
        String str1 = String.valueOf(c);
        System.out.println("Method 1: " + str1); // Output: A

        // Method 2: Using Character.toString(char)
        String str2 = Character.toString(c);
        System.out.println("Method 2: " + str2); // Output: A

        // Method 3: Using concatenation
        String str3 = "" + c;
        System.out.println("Method 3: " + str3); // Output: A

        // Method 4: Using StringBuilder
        StringBuilder sb = new StringBuilder();
        sb.append(c);
        String str4 = sb.toString();
        System.out.println("Method 4: " + str4); // Output: A
    }
}
 

In the example above, we start by declaring a char variable c with the value 'A'. We then proceed to demonstrate four different methods to convert this char into a String.

Method 1 uses String.valueOf(char) to convert the char into a String. Method 2 uses Character.toString(char) to achieve the same result. Both methods produce the output "A".

Method 3 demonstrates a simple concatenation approach. By appending the char to an empty String, the char is implicitly converted to a String. Method 4 involves using a StringBuilder to append the char and then convert it to a String using the toString() method. Both methods yield the same output, "A".

Choose the method that suits your specific use case or personal preference when converting char to String in Java.

Related questions

0 votes
1 answer
asked May 17, 2023 in JAVA by kvdevika (117k points)
0 votes
1 answer
asked May 18, 2023 in JAVA by kvdevika (117k points)
0 votes
1 answer
asked May 17, 2023 in JAVA by kvdevika (117k points)
0 votes
1 answer
0 votes
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...