Following is the puzzle code,
public class Puzzle { public static void main(String... args) { System.out.println( "Hi Guys!" ); Character myChar = new Character( '\u000d' ); } } |
Puzzle.java:4: error: illegal line end in character literal
Character myChar = new Character(‘\u000d’);
^
1 error
One thing is clear that, there is something wrong with the ‘myChar’ line. So, commented that line to make this work for now (so that is what we do in development right) and the code now looks as below,
public class Puzzle { public static void main(String... args) { System.out.println( "Hi Guys!" ); // Character myChar = new Character('\u000d'); } } |
Puzzle.java:4: error: unclosed character literal
// Character myChar = new Character(‘\u000d’);
^
1 error
The expectation is the code should compile now. Since there is only one System.out.println statement and that is straight forward. But what we get is an error and that too out of the commented code.
Let there be anything inside the commented code, how can the Java compiler complain about it. So by this time you might have found the issue.
Solution to the Puzzle
Character myChar = new Character(‘\u000d’);In the above line, we are trying to instantiate a unicode character. It is ok, syntactically we can do something like this. But the problem is with the unicode character we trying to instantiate. \u000d represents a newline character in unicode.
Java compiler, just before the actual compilation strips out all the unicode characters and coverts it to character form. This parsing is done for the complete source code which includes the comments also. After this conversion happens then the Java compilation process continues.
In our code, the when Java compiler encounters \u000d, it considers this as a newline and changes the code as below,
public class Puzzle { public static void main(String... args) { System.out.println( "Hi Guys!" ); // Character myChar = new Character(' '); } } |
Not because of this, its always better to remove the commented code from the source. Do not rely on comments to save something for the future. Use the version control system for that
No comments:
Post a Comment