One of the questions I ran into when preparing for the Java Certification exam dealt with how Java handles nested comments. Since this isn’t something I usually do in my code I wasn’t sure how it worked. It turns out the results were different than I expected.
First lets look at the double slash comments. Since they mark everything to the end of a line as a comment there isn’t really any way to nest them. You can do something like this:
System.out.println("hi"); // Comments // More comments
But the “More comments” is never evaluated because the compiler simply skips the rest of the line. However with /* */
comments can be nested. First lets look at what happens when you nest //
comments inside /* */
comments.
1 /* //important comment */
2 class Comment {
3 public static void main(String args[]){
4 System.out.println("test");
5 }
6 }
So what happens in this code? If the compiler sees the //
and skips the rest of the line then the rest of the code will be marked as a comment because the closing */
will be skipped. This will produce a compile time error. So lets try compiling the code and see what happens.
Continue reading “Comments in Java”