Read Also: [Solved] Empty character literal error in Java
[Fixed] Unclosed Character Literal Error
Example 1: Producing the error by enclosing the string in single quotes
We can easily produce this error by enclosing the string in single quotes as shown below:
public class UnclosedCharacterLiteral {
public static void main(String args[]) {
String str;
str = 'Hello World';
System.out.println(str);
}
}
Output:
UnclosedCharacterLiteral.java:3: error: unclosed character literal
char ch = 'Hello World';
^
UnclosedCharacterLiteral.java:3: error: unclosed character literal
char ch = 'Hello World';
^
2 errors
Explanation:
The cause of this error is due to the string declared in single quotes. Single quotes denote a char(' ') in Java, not a String.Solution:
In Java string should always be declared in double-quotes. The above compilation error can be resolved by providing the string in double-quotes as shown below: public class UnclosedCharacterLiteral {
public static void main(String args[]) {
String str;
str = "Hello World";
System.out.println(str);
}
}
Output:
Hello World
Example 2: Producing the error by providing an incorrect Unicode form
We can easily produce this error by providing incorrect Unicode form character as shown below: public class UnclosedCharacterLiteral2 {
public static void main(String args[]) {
char ch;
ch = '\201A';
System.out.println(ch);
}
}
Output:
UnclosedCharacterLiteral2.java:4: error: unclosed character literal
ch = '\201A';
^
UnclosedCharacterLiteral2.java:4: error: unclosed character literal
ch = '\201A';
^
UnclosedCharacterLiteral2.java:4: error: not a statement
ch = '\201A';
^
3 errors
Explanation:
The cause of this error is the incorrect Unicode form.Solution:
The correct Unicode form is '\u201A' as shown below: public class UnclosedCharacterLiteral2 {
public static void main(String args[]) {
char ch;
ch = '\u201A';
System.out.println(ch);
}
}
Output:
,
That's all for today, please mention in the comments in case you are still facing the unclosed character literal error in Java.