Pablo_06
Pablo_06

Reputation: 35

String with one character can be casted to char?

String message = "a";
char message1 = (char) message;
System.out.println(message1);

Gives me an output error,

This should be converted with ease because the string is one character "a"

I know I can do it explicitly sorry, why the two are incompatible to cast if they are storing the same (only one character)?

Upvotes: 0

Views: 499

Answers (4)

Maarten Bodewes
Maarten Bodewes

Reputation: 94038

No you cannot do that. You can cast a char to Character because the Character object type is the "boxed" version of the char base type.

Character charObject  = (Character) 'c';
char charBase = (char) charObject;

actually, because of auto-boxing and auto-unboxing, you don't need the explicit cast:

Character charObject  = 'c';
char charBase = charObject;

However, a String is an object type much like any other object type. That means you cannot cast it to char, you need to use the charAt(int index) method to retrieve characters from it.

Beware though that you may want to use codePointAt(int index) instead, since Unicode code points may well extend out of the 65536 code points that can be stored in the 16 bits that a char represents. So please make sure that no characters defined in the "supplementary planes" are present in your string when using charAt(int index).

As in Java any type can be converted to String, it is possibly to directly append characters to a string though, so "strin" + 'g' works fine. This is also because the + operator for String is syntactic sugar in Java (i.e. other objects cannot use + as operator, you would have to use a method such as append()). Do remember that it returns a new string rather than expanding the original "strin" string. Java strings are immutable after all.

Upvotes: 1

Vignesh T I
Vignesh T I

Reputation: 872

You cannot cast a String to a char. Below is a snippet to always pick the first character from the String,

char c = message.charAt(0);

In case you want to convert the String to a character array, then it can be done as,

String g = "test";
char[] c_arr = g.toCharArray(); // returns a length 4 char array ['t','e','s','t']

Upvotes: 1

Rogue
Rogue

Reputation: 11483

A String with one char is more akin to a char[1]. Regardless, retrieve the character directly:

String ex = /* your string */;
if (!ex.isEmpty()) {
    char first = ex.charAt(0);
}

Upvotes: 0

Mureinik
Mureinik

Reputation: 311998

As you've seen, no, you cannot cast a single character String to a char. But you could extract it explicitly:

String message = "a";
char message1 = message.charAt(0);

Upvotes: 2

Related Questions