Read Also: Comparing characters in Java
[Fixed] Error: empty character literal
Example 1: Producing the error by printing the empty single quotes character
We can easily produce this error by printing the ' ' (empty single quotes) character as shown below:
public class EmptyCharacterLiteral { public static void main(String args[]) { char ch = ''; System.out.println("Print empty char" + ch); } }
Output:
/EmptyCharacterLiteral.java:3: error: empty character literal
char ch = ' ';
^
1 error
Explanation:
The cause of this compilation error is due to trying to print empty character in Java. As a result, we were getting an error: empty character literal.Solution:
To overcome this compilation error, we can assign the char data type variable ch with the values Character.MIN_VALUE, or '\u0000', or '\0', as shown below:public class EmptyCharacterLiteral { public static void main(String args[]) { // Assign null character to ch variable char ch = Character.MIN_VALUE; //OR //char ch = '\u0000'; //OR //char ch = '\0'; System.out.println("Print empty char" + ch); } }
Output:
Print empty char
Example 2: Producing the error by comparing the empty single quotes character
We can easily produce this error by comparing the ' ' (empty single quotes) character as shown below:
public class EmptyCharacterLiteral2 { public static void main(String args[]) { char ch = 'a'; // Comparing null character to ch variable if (ch == ('')) System.out.println("char is: " + ch); } }
Output:
/EmptyCharacterLiteral2.java:5: error: empty character literal
if (ch == (''))
^
1 error
Explanation:
The cause of this compilation error is due to trying to compare empty single quotes character with the char data type variable ch. As a result, we were getting error: empty character literal.Solution:
To overcome this compilation error, we can replace the empty single quotes character with the values Character.MIN_VALUE, or '\u0000', or '\0', as shown below:public class EmptyCharacterLiteral2 { public static void main(String args[]) { char ch = 'a'; // Comparing null character to ch variable if (ch == Character.MIN_VALUE)// OR (ch == '\u0000') OR (ch == '\0') System.out.println("char is: " + ch); } }
Output:
(No Output Printed)
That's all for today. Please mention in the comments in case you are still facing the error: empty character literal in Java.