Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

Java - convert String to char

0 contributions
11 points

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

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more