Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unclosed Character Literal error

Tags:

java

string

char

Got the error "Unclosed Character Literal" , using BlueJ, when writing:

class abc
{
   public static void main(String args[])
   {
       String y;
       y = 'hello';
       System.out.println(y);
   }
}

But I can't figure out what is wrong. Any idea?

Thanks.

like image 520
Gaurang Tandon Avatar asked Jun 27 '13 13:06

Gaurang Tandon


People also ask

How do you fix 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.

What does it mean by unclosed string literal?

As its name implies, the unclosed string literal error refers to a string literal which has not been closed. More specifically, this means that the Java compiler has failed to interpret a string literal due to being unable to locate the double quote expected to close i.e., mark the end of it.

How do you represent a string in Java?

In Java, a string is a sequence of characters. For example, "hello" is a string containing a sequence of characters 'h' , 'e' , 'l' , 'l' , and 'o' . We use double quotes to represent a string in Java.


2 Answers

In Java, single quotes can only take one character, with escape if necessary. You need to use full quotation marks as follows for strings:

y = "hello"; 

You also used

System.out.println(g); 

which I assume should be

System.out.println(y); 

Note: When making char values (you'll likely use them later) you need single quotes. For example:

char foo='m'; 
like image 197
nanofarad Avatar answered Sep 21 '22 17:09

nanofarad


Java uses double quotes for "String" and single quotes for 'C'haracters.

like image 43
Ravi K Thapliyal Avatar answered Sep 25 '22 17:09

Ravi K Thapliyal