Illegal Character When Trying to Compile Java Code

Illegal Character when trying to compile java code

The BOM is generated by, say, File.WriteAllText() or StreamWriter when you don't specify an Encoding. The default is to use the UTF8 encoding and generate a BOM. You can tell the java compiler about this with its -encoding command line option.

The path of least resistance is to avoid generating the BOM. Do so by specifying System.Text.Encoding.Default, that will write the file with the characters in the default code page of your operating system and doesn't write a BOM. Use the File.WriteAllText(String, String, Encoding) overload or the StreamWriter(String, Boolean, Encoding) constructor.

Just make sure that the file you create doesn't get compiled by a machine in another corner of the world. It will produce mojibake.

Illegal character error when compiling a program made using geany \u0000

This might be a problem with encoding that Geany uses when saving the source file.

If you compile the file with javac without specifying the -encoding parameter the platform's default encoding is used. On a modern Linux this is likely to be UTF-8; on Windows it is one of the ANSI character sets or UTF-16, I think.

To find out what the default encoding is, you can compile and run a small java program:

public class DefaultCharsetPrinter {
public static void main(String[] argv) {

This should print the name of the default encoding used by java programs.

In Geany you can set the file encoding in menu Document > Set Encoding. You need to set this to the same value used by javac. The Geany manual describes additional options for setting the encoding.

As you are seeing a lot errors complaining about the null character it is most likely that Geany stores the file in an encoding with multiple bytes per character (for instance UTF-16) while javac uses an encoding with a single byte per character. If I save your source file as UTF-16 and then try to compile it with javac using UTF-8 encoding, I get the same error messages that you see. After saving the file as UTF-8 in Geany, the file compiles without problems.

Why I can't compile this simple Java Code on CMD, but compile it on an online compiler?

You file was saved in UTF-16, but you didn't tell the compiler that (-encoding).

Suggest you open the file in Notepad and save it again in the default code page of your system.

Related Topics

Leave a reply