Fix: error: unclosed character literal in Java


error unclosed character literal

Code Example:

public class JavaExamples {

    public static void main(String[] args) {
        char myChar = 'a;
    }
}
Compilation Error:
javac JavaExamples.java
JavaExamples.java:6: error: unclosed character literal
        char myChar = 'a;
                      ^
1 error

You will get the unclosed character literal if you do not enclose a character value within single quotes, or if you have more than one character enclosed within a character literal.

Example:
char myChar = 'ab';
 % javac JavaExamples.java
JavaExamples.java:6: error: unclosed character literal
        char myChar = 'ab';
                      ^
JavaExamples.java:6: error: unclosed character literal
        char myChar = 'ab';
                         ^
JavaExamples.java:6: error: not a statement
        char myChar = 'ab';
                        ^
3 errors

Based on what has caused this error, below are some fixes possible.

  • Make sure the character literal is enclosed within single quotes: e.g. 'a'
  • If literal contains more than one character than it should be considered as a String and not a char datatype.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap