Languages
[Edit]
EN

Java - convert String to char

11 points
Created by:
Lennie-S
439

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

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - String conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join