Languages
[Edit]
EN

Java - convert String to char

11 points
Created by:
JustMike
26120

In Java, we can convert String to char in couple of different ways.

Short solutions:

// solution 1
char char1 = "abc".charAt(0); // a
        
// solution 2
char char2 = "abc".toCharArray()[0]; // a
        
// solution 3
Character char3 = new Character("abc".charAt(0)); // a

1. Using String.charAt(0)

public class Example1 {

    public static void main(String[] args) {
        String str = "abc";
        char charVal = str.charAt(0);
        System.out.println(charVal); // a
    }
}

Output:

a

2. Using String.toCharArray()

public class Example2 {

    public static void main(String[] args) {
        String str = "abc";
        char[] chars = str.toCharArray();
        char charVal = chars[0];
        System.out.println(charVal); // a
    }
}

Output:

a

3. Using constructor - new Character(char value)

public class Example3 {

    public static void main(String[] args) {
        String str = "abc";
        Character charVal = new Character(str.charAt(0));
        System.out.println(charVal); // a
    }
}

Output:

a

4. Convert entire String to characters

public class Example4 {

    public static void main(String[] args) {
        String str = "abc";

        for (int i = 0; i < str.length(); i++) {
            char charVal = str.charAt(i);
            System.out.println("index: " + i + ", char: " + charVal);
        }
    }
}

Output:

index: 0, char: a
index: 1, char: b
index: 2, char: c

 

Java - String conversion

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join