Unexpected sequence error in Java compilation
When solving challenges online, I found the following behavior of Java, which I found a little strange I started with the following outline writer:
import java.io.*; class WeirdJava { public static void main (String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(system.in)); String input = br.readLine(); HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); System.out.println("Weird Java"); } }
Note that in the above program, there are two errors:
>I didn't handle the exceptions that BufferedReader might throw. > I did not import the standard util library containing HashMap
Now, when I try to compile the above program, the java compiler gives an error that it cannot find the symbol HashMap Please note that the declaration involving HashMap is after BufferedReader Next, I add the following import statement to the program:
import java.util.HashMap;
When I compile the program again, the compiler displays an error this time
My question:
>Why didn't you throw this error in the previous compilation attempt? > The order in which compilation errors occur does not seem natural What are the compiler design principles in this routine?
Solution
It just checks the order of the source by the compiler In particular, before checking code that calls methods that can throw checked exceptions, the compiler checks the import and parses them
If you run javac with - verbose, you will notice that the compiler loads the imported classes, in this case BufferedReader and inputstreamreader, and then it loads public API classes such as object and string:
[loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/io/BufferedReader.class)]] [loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/io/InputStreamReader.class)] ] [loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/lang/Object.class)]] [loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/lang/String.class)]] [checking test.Test] [loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/lang/AutoCloseable.class)]] [loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/lang/System.class)]] [loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/io/InputStream.class)]] [loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/io/Reader.class)]] Test.java:11: error: cannot find symbol HashMap<Integer,Integer>();
By viewing the overview in this link, loading the used class itself is a part of the first stage compilation, which is called "parse and enter":