EN
Java - convert String to char
11 points
In Java, we can convert String to char in couple of different ways.
Short solutions:
xxxxxxxxxx
1
// solution 1
2
char char1 = "abc".charAt(0); // a
3
4
// solution 2
5
char char2 = "abc".toCharArray()[0]; // a
6
7
// solution 3
8
Character char3 = new Character("abc".charAt(0)); // a
xxxxxxxxxx
1
public class Example1 {
2
3
public static void main(String[] args) {
4
String str = "abc";
5
char charVal = str.charAt(0);
6
System.out.println(charVal); // a
7
}
8
}
Output:
xxxxxxxxxx
1
a
xxxxxxxxxx
1
public class Example2 {
2
3
public static void main(String[] args) {
4
String str = "abc";
5
char[] chars = str.toCharArray();
6
char charVal = chars[0];
7
System.out.println(charVal); // a
8
}
9
}
Output:
xxxxxxxxxx
1
a
xxxxxxxxxx
1
public class Example3 {
2
3
public static void main(String[] args) {
4
String str = "abc";
5
Character charVal = new Character(str.charAt(0));
6
System.out.println(charVal); // a
7
}
8
}
Output:
xxxxxxxxxx
1
a
xxxxxxxxxx
1
public class Example4 {
2
3
public static void main(String[] args) {
4
String str = "abc";
5
6
for (int i = 0; i < str.length(); i++) {
7
char charVal = str.charAt(i);
8
System.out.println("index: " + i + ", char: " + charVal);
9
}
10
}
11
}
Output:
xxxxxxxxxx
1
index: 0, char: a
2
index: 1, char: b
3
index: 2, char: c