How javac works while importing a package?

884 Views Asked by At

I am having a doubt.
My understanding is that jdk has [ jre + development tools (Java, javac, debugger etc.) + source code (src.zip) ].

Now working of java compiler is nothing to do with the running of class file.

If I am compiling a .java file then from where the java compiler is importing the package?
I could find the packages under jre.
If I do not opt to install jre while installing jdk, does that mean I will not be able to compile the java file having import statement?

Please help.

2

There are 2 best solutions below

2
Ralf Kleberhoff On BEST ANSWER

First, as a minor remark, a statement like

import java.util.List;

just introduces an abbreviation, allowing you to use the simple word List later in your code instead of the full class name java.util.List. So it's not so much the import statement itself, but the usage of a class like java.util.List that needs some explanation.

You understand correctly that, to compile your java file, the compiler needs some information about every class you use, and it typically finds this information in some jar file containing that class.

Now, where is this jar file containing the java.util.List class that the compiler reads? You're correct, it comes from the JRE, from the rt.jar that's part of the system classpath (the Java compiler itself is a java program that needs the basic classes itself, so wherever you successfully run javac, you always have an rt.jar available).

If your source code used a class from some other library, you'd have to specify that library on the javac command line, using an option like -cp.

0
Ratish Bansal On

Jdk = JRE + other tools like you mentioned. When you are compiling your java file and you are using java inbuild library then it uses rt.jar to resolve dependency i.e import statements. You can refer below link for the difference What is the difference between JVM, JDK, JRE & OpenJDK?