There are 8 primitive datatypes in Java.
char
is one of them. When compiler
sees a char
datatype is defined. It allocates 1 Bytes of memory from JVM heap and expects a value after =
symbol with two conditions.
- value enclosed inside
'
(single quotes).
- value to be single character long. It can be either a single character or valid code corresponding single character, which you can't type using English Keyboard.
In the same way, a datatype of String type should be enclosed with "
(double quotes) and can have any length characters sequence.
In the given example you have mixed concepts of both char
and String
datatype. the compiler clearly saying:
Unclosed Character Literal
Means, you started with '
single quote, so compiler just expects a single character after opening '
and then a closing '
. Hence, the character literal is considered unclosed
and you see the error.
So, either you use char
data type and '
single quotes to enclose single character.
Or use String
datatype and "
double quotes to enclose any length of character sequence.
So, correct way is:
String y = "hello";
System.out.println(y);
"hello"
.String
s in " " andchar
in ' ' ?char y;y = 'hello';
char
can only take one character. It is a character by definition, and called a character for that exact reason.