Languages
[Edit]
EN

Java - convert String to char

11 points
Created by:
JustMike
3506

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

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.