Compiler doesn't complain when I ended a line with two semicolons. Why?

后端 未结 7 2174
不思量自难忘°
不思量自难忘° 2021-01-19 01:29

I thought bad thing would happen when I ended a line like this. But compiler didn\'t even complain. Does anybody have an idea, why this is legal in java.

displ

相关标签:
7条回答
  • 2021-01-19 01:49

    The compiler uses semicolon to denote an 'end of statement'. Having two consecutively ends the statement prior to the first, and then creates a second empty statement.

    Really, you could even do this:

    displayDataMap.put("dateInterval", getDateInterval());;;;;;;;;;;;;;;
    
    0 讨论(0)
  • 2021-01-19 01:58

    It's an empty statement, it's the same as if you did this:

    int x = 0;
    ;
    

    No problems there!

    0 讨论(0)
  • 2021-01-19 02:00

    Here's a practical example in C:

    #ifndef NDEBUG
    #define Dprintf printf
    #else
    #define Dprintf(X)
    #endif
    
    if(some_test)
       Dprintf("It's true!");
    else
       Dprintf("It's false.");
    

    If NDEBUG is defined, the compiler will see:

    if(some_test)
       ;
    else
       ;
    

    This can be useful in some cases.

    Since Java is heavily inspired by C/C++, it's something they kept, even though it is not useful and there is no preprocessor.

    You can, if you want, run the C preprocessor cpp on your code to do this kind of behaviour.

    Some languages may say it's an error instead, it's up to them to choose.

    0 讨论(0)
  • 2021-01-19 02:00

    ; represents the empty statement or you can say, it's represent termination line of a any statement in Java, even if you put more than one it's valid in Java. Compiler will not gives you any error because this is valid. even the below statement is also valid:

    System.out.println("HI");;;;;;;;
    
    0 讨论(0)
  • 2021-01-19 02:10

    ; means end of statement.

    for ;; , the second ; will imply that the statement consists of nothing.

    0 讨论(0)
  • 2021-01-19 02:11

    Compiler wont complain even when you just create an empty file with .java extension. Its an empty compilation unit and its valid. Same way a semicolon is an empty statement which is valid.

    0 讨论(0)
提交回复
热议问题