简体   繁体   中英

Commented code gives compilation error in Java?

Hi I was creating simple program and got unseen compilation error in commented code.My code is as below :

public class Static_Method_Call
{               
    public static Character character=getMe();

    public static void main(String[] args)
    {
        System.out.println("Inside main() 1 : "+character); 
        //Static_Method_Call.character=new Character('\u000d'); 
        //System.out.println("Inside main() 2 : "+character);
    }

    static
    {
        System.out.println("Inside static block : "+character);
        Static_Method_Call.character=new Character('\u003d');       
    }

    public static Character getMe()
    {
        System.out.println("Inside getMe() : "+character);
        return new Character('\u002d');
    }
}

Error is as below :

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Invalid character constant

What does this error mean in Java ?

\ is a Unicode character that stands for the CR special character. Even before the compiler transforms the source code, this character is pre-processed and causes the source code to be invalid. So I guess at pre-processing, the commented line would look something like:

//Static_Method_Call.character=new Character('
 ');

Hence the compiler error. You can use \\r to add a carriage return.

\ is a newline character, so next line is starting with ' which is unclosed that is what it is complaining. this is explained here A unicode newline character(\ ) in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM