Cross-Java tickets-details about classpath and package (zz matrix)

Source: Internet
Author: User
Java is very attractive, but for beginners who have just entered the Java threshold, compiling and running a very simple Java program is simply a nightmare. Clearly, the program is correct, but all kinds of confusing error messages really make you feel at ease. Many beginners who have been wandering for a long time at the Java gate gave up the opportunity to learn Java, which is a pity. I have also experienced this very painful phase, and I feel that the difficulty in compiling lies in the classpath setting and understanding of package. This article uses examples to solve various classpath settings during compilation. The running environment of this instance is Windows XP + JDK 1.5.0. For other environments, the reader should easily switch accordingly.

1. Download and install jdk1.5.0, and install it in C:/program files/Java/jdk1.5.0 by default.

2. Click Start> run in Windows XP, Enter cmd in the displayed run window, and press OK or press enter to open a command line window.

3. Enter the following in the command line:

Java

A long foreign Article rolled out. This is how JDK tells us how to use the Java command. It implies an important message, that is, JDK is successfully installed. You can use the Java command in the command line.

4. Enter

Javac

Screen Display:

& #39; javac & #39; it is neither an internal or external command, nor a program or batch processing file that can be run.

This is because the javac command cannot be found in windows. This is not clear. Java and javac are both two files in the same subdirectory of JDK. Why can we directly run Java instead of directly running javac? Originally, Sun quietly added the Java command to the path search path in the background to run Java files immediately after JDK is installed, therefore, we can directly run the Java command (but we cannot see where it is set, the path stored in Java is not found in the user's path or system's path setting ). However, no other JDK commands need to be added to the search path by the user.

5. In this case, add the path search path. Right-click "my computer", select "properties", select "advanced" in the "System Properties" window, and then click "environment variables, the "environment variable" window is displayed. Create a new variable named "path" in the user variable and the variable value is "C:/program files/Java/jdk1.5.0/bin; % PATH % ". The last % PATH % indicates that the original path settings are retained and the current path settings are added to the beginning. All the way, press "OK" to exit (three times in total ). Close the original command line window and follow Step 1 to open a new command line window. In this window, enter

Javac

A long foreign article has appeared again. This is to introduce the usage of javac. Set successfully.

6. So far so good. So far, we can program it. However, this is not a good solution. As we learn Java in the future, we will use JUnit, ant, netbeans, and other application tools. During installation, you need an environment variable named "java_home" pointing to the JDK path. Otherwise, the installation will fail. Therefore, we need to improve step 1 to prepare for the future. In step 2, the "environment variables" window is displayed. Create a new variable named "java_home" in the user variable and the variable value is "C: /program files/Java/jdk1.5.0 ". Note that the variable value here is only in jdk1.5.0 and cannot be extended to bin. After confirming, return to the "environment variables" window, double-click the PATH variable we set, and change its value to "% java_home %/bin; % PATH % ". This effect is exactly the same as step 1, except that there is an additional java_home variable. In this way, when we need to point to the JDK path, we only need to add "% java_home %. Now, all path settings are complete. All the way to exit, open the new command line window, enter

Javac

If a long foreign text appears, the path has been set correctly and everything is normal. If not, check whether this step is fully set correctly.

7. Start programming. Create a subdirectory named "javatest" in the root directory of drive C to store the Java source code. Open notepad in XP, save it to the javatest folder, and enter "Hello. Java" in the "file name" text box ". Note that a double quotation mark is added before and after the file name. Otherwise, the notepad will save the text file as "hello.java.txt. Enter the following code:

Public class Hello {
Public static void main (string [] ARGs ){
System. Out. println ("Hello, world ");
}
}

Save the file again.

8. In the command line window, enter

Cd c:/javatest

Transfer the current path to javatest. Then, enter

Javac hello. Java

JDK compiles a hello. Class class file in the javatest folder. If "1 error" or "XX errors" is displayed, it indicates that the source code is entered incorrectly. Follow the error prompt and follow the code in step 1 to find and correct the error. Check for incorrect code input and incorrect classpath settings. This article describes how to correctly set classpath and package. Therefore, it is assumed that the code entered by the reader is correct. So far, the classpath settings are not incorrect because we compile the source code in the current path.

9. In the command line window, enter

Java hello

The screen appears

Hello World

We have successfully compiled and run the first Java program.
However, steps 8th and 9th are not perfect because we compile and run them in the javatest folder where the source code is stored. Therefore, some very important issues are not exposed. In fact, the "javac hello. java and Java hello in step 2 involve two issues: first, how the operating system looks for "javac" and "Java" commands, and second, how the operating system looks for "hello. java and hello. class. For commands such as "javac" and "Java", since they are all executable files, the operating system will search for them based on the path we set in step 1. For files such as "Hello. Java" and "hello. Class", the path setting does not work. Because we work in the current working path, Java and javac will find the corresponding Java file in the current working path (the class file is quite special, see Step 1 ),
So everything works. Next we start to artificially complicate the problem, compile and run it in a non-current working path, and see how the result is.

10. In the command line window, enter

Cd c:
Go to the C-drive root directory, and the current path leaves the workspace where the source code is stored. Input

Javac hello. Java

Screen Display:

Error: cannot read: Hello. Java
1 error

Hello. Java cannot be found. We need to specify a path for it and tell it to C:/javatest to find the hello. Java file. Input

Javac C:/javatest/Hello. Java

OK. No error is returned this time. The compilation is successful.

11. Enter

Java C:/javatest/Hello

This screen appears:

Exception in thread "Main" Java. Lang. noclassdeffounderror: C:/javatest/Hello

The class definition cannot be found in "C:/javatest/hello. Clearly C:/javatest/Hello Is A. Class file. Why can't I find it? Originally, Java treats. java files and. class files differently. You can directly specify a path for the. Java file, and the. Class file required by the Java command cannot have an extension or an additional path.

So how to specify the path? The. Class file required by Java must be specified through classpath.

12. In Step 2, the "environment variables" window is displayed. Create a new variable named "classpath" and the variable value is "C:/javatest ". Click OK to exit. Close the original command line window, open a new command line window, and enter

Java hello

"Hello world" is coming out. It can be seen that the purpose of setting classpath in the "environment variables" window is to tell JDK where to find the. Class file. Once this method is set, JDK automatically comes here when you need to call the. Class file every time you run Java or javac. Therefore, this is a global setting.

13. In addition to setting classpath in the environment variables window, there is another method, that is, adding the option classpath after the Java command, followed by the class file name without the extension. For example,

Java-classpath C:/javatest hello

In this case, the JDK first looks for the. Class File Based on the path specified in the classpath option in the command line, and then finds it in the global classpath environment variable. In this case, even if the global classpath environment variable is not set, it can be run because the class path has been correctly specified in the command line.

To better demonstrate the classpath problem in the following example, we first Delete the global classpath environment variable, and use the command line option-classpath as necessary. In the displayed "environment variables" window, select the variable name of "classpath" and press "delete.

In addition, you can use CP, short for classpath, to replace classpath in Java commands, such as Java-cp c:/javatest hello. Note that before JDK 1.5.0, The javac command cannot use CP instead of classpath, but can only use classpath. In JDK 1.5.0, both Java and javac can use CP and classpath. Therefore, to ensure consistency, we recommend that you use classpath as the option name.

14. We once again artificially complicate the problem. Disable notepad editing hello. Java, and change the javatest folder name to "Java test" with spaces ". Enter

Javac C:/Java test/Hello. Java

Long Yang Wen came out again, but this time it reported an error:

Javac: Invalid flag: C:/Java

JDK separates C:/Java test with spaces into two parts: "C:/Java" and "test/hello. java, and regard C:/Java as an invalid option. In this case, we need to add double quotation marks to the entire path, that is

Javac "C:/Java test/Hello. Java"

This time JDK knows that the quotation marks contain a complete path, so no error is reported. Similarly, this is also required for Java commands, that is

Java-classpath "C:/Java test" Hello

For folders with long names and Chinese characters, double quotation marks are not allowed in XP. But in general, double quotation marks are not prone to errors and are easy to understand. Therefore, we recommend that you use double quotation marks in the classpath option.

15. Let's take a look at other classes used in the. Java file. Create a new person. Java file in C:/Java test with the following content:

Public class person {
Private string name;

Public Person (string name ){
This. Name = Name;
}

Public String getname (){
Return name;
}
}

Then modify hello. Java with the following content:

Public class Hello {
Public static void main (string [] ARGs ){
Person = new person ("Mike ");
System. Out. println (person. getname ());
}
}

Enter

Javac "C:/Java test/Hello. Java"

An error occurred:

C:/Java test/Hello. Java: 3: cannot find symbol
Symbol: class person

The JDK prompts that the person class cannot be found. Why is javac "C:/Java test/Hello. Java" feasible in step 1, but not here? Hello. the Java file is not used for other classes. Therefore, JDK does not need to look for other classes. Here, we modify hello. java, so that it uses a person class. According to step 1, we need to tell JDK where to find the class used, even if the class used is in the same way as hello. Java, under C:/Java test! Input

Javac-classpath "C:/Java test" C:/Java test/Hello. Java"

After compilation, JDK generates both hello. Class and person. class files in the C:/Java test folder. In fact, Because hello. Java uses the person. Java class, JDK first compiles and generates the person. class, and then compiles and generates the hello. Class. Therefore, no matter how many other classes are used in the main class hello. Java, JDK automatically compiles other classes as long as the class is compiled, which is very convenient. Input

Java-classpath "C:/Java test" Hello

The screen appears

Mike

Successful.

16. Step 4 illustrates how to use a person. Java created by ourselves in hello. Java, and this class is in the same folder as hello. java. In this step, we will examine the situation where person. Java is placed under different folders.

Put the person in the C:/Java test folder first. delete the class file, create a folder named DF under the C:/Java test folder, and set the person under the C:/Java test folder. java moves to its bottom. Enter

Javac-classpath "C:/Java test/DF" C:/Java test/Hello. Java"

Compiled. In this case, the javac command is no different. You only need to change classpath to C:/Java test/DF.

Enter

Java-classpath "C:/Java test" Hello

At this time, because Java needs to find two files in different folders. class file, and the command line only tells JDK a path, namely C:/Java test. In this folder, only hello. class, cannot find person. class file. Therefore, errors are expected:

Exception in thread "Main" Java. Lang. noclassdeffounderror: person
At hello. Main (hello. Java: 3)

The person. class cannot be found. When setting more than two classpath, each path is first enclosed by double quotation marks, and then these paths are separated by ";", and each path and ";" cannot contain spaces. Therefore, we re-enter the following in the command line:

Java-classpath "C:/Java test"; "C:/Java test/DF" Hello

Compiled successfully. But it also exposes a problem. If we need to use classes in different folders, isn't the classpath setting very long! Is there a way for all. class files in a folder to specify only the classpath of this folder, and then let JDK automatically search for all corresponding paths under this folder? Yes. You only need to use package.

17. Package introduction. The Package concept is introduced in Java to solve naming conflicts. For example, in our example, we designed a very simple person class. If someone develops a class library, there happens to be a person class. When we use this class library, there is a name conflict between the two person classes. JDK does not know which person class to use. What's more, when we develop a very large class library, there will inevitably be more and more conflicts between the names of our class libraries and those developed by others. To avoid the same class name as the class name developed by others, Every programmer cannot forcibly rename a class named writer to sarkuyawriter or mikewriter, smithwriter?

This is also true in real life. Suppose you are Zhang San, and if several of you in the same unit are Zhang San, then your problem will come. One day, the organization leaders announced at the meeting that Zhang San was appointed as the office director. You have no idea whether to cry or laugh. However, if you are calling Zhang San in your organization, you will not care about the number of people calling Zhang San in China, because the other three are distributed across the country and other cities, and you cannot see them, if you cannot touch them, you will not worry.

Sun was inspired by this issue of "Michael Jacob". To solve the naming conflict problem, Sun adopted the policy of "looking out of sight: each class belongs to a specific region. All classes in the same region cannot have the same name. classes in different regions cannot see each other, A class with the same name is allowed. In this way, the naming conflict is solved, just as Zhang San in Beijing and Zhang San in Shanghai are not the same person after all. This region is called package in Java. Because package is very important in Java, if you do not define your own package, JDK will classify your class into a default untitled package.

Custom package names can be freely created by various programmers. As a way to avoid name conflicts, the name of a package is better than that of other programmers. Every domain name is unique on the Internet. Therefore, Sun recommends that you rename your own domain name as the package name. If you do not have your own domain name, it is likely that you do not apply for it because you are shy. It is not necessarily because your hypothetical domain name conflicts with other domain names. For example, my hypothetical domain name is sarkuya.com, which is currently unique, so my package can be named com. sarkuya. Thanks to Java for giving us a free chance to use our own domain name, the only premise is to write backwards. Of course, each package can also contain different sub-packages, such as com. sarkuya. util, Com. sarkuya. Swing, and so on.

You can define a package by adding "package packagename;" to the first line of the corresponding. Java file, and each. Java file can have only one package. In fact, the implementation of the package in Java is combined with the computer file system, that is, the package you have and the storage path on the hard disk. For example, if the package name of a class is com. sarkuya. util, the class must be stored in the path of COM/sarkuya/util. As for the sub-path of the COM/sarkuya/util folder, we will talk about it in step 1.

In addition to avoiding naming conflicts, package also provides a function to protect all class files in the current package. It is mainly implemented by defining several modifiers with different visual degrees for the class: public, protected, private, and a non-real friendly type.

For public classes, class variables, and methods, any class in and out of the package can be accessed;
Protected classes, class variables and methods, any classes in the package, and those outside the package that inherit this class can be accessed;
Private classes, class variables, and methods are not accessible to any class outside the package;
If a class, category variable, and method are not modified with these three modifiers, it is of the friendly type, then any class in the package can access it, any class outside the package cannot access it (including the subclass that inherits this class outside the package). Therefore, this type, class variables, and methods are friendly to other classes in the package, is open, while other classes outside the package are closed.

As mentioned above, the package is mainly used to solve naming conflicts. Therefore, classes in different packages do not have to worry about conflicts with the class names of other packages, by default, JDK only uses the classes in this package. For other packages, JDK turns a blind eye to the following: "No worries ". If you want to reference the classes of other packages, you must use import to introduce the corresponding classes in other packages. JDK will conduct further review only at this time, that is, based on the visibility of these classes, class variables and methods in other packages to check whether they meet the requirements for use. If this review fails, compilation gets stuck until you stop using these classes, class variables, and methods, or change the modifier of introduced classes, class variables, and methods to conform to the requirements. If this review is passed, JDK will end up with a review of whether the names conflict with each other. If a name conflict is found, you can explicitly reference the corresponding class by referencing the full name in the Code. For example

Java. util. Date = new java. util. Date ()

Or

Java. SQL. Date = new java. SQL. Date ().

The third major role of package is to simplify classpath settings. Do you still remember the obstacles in step 1? Here we will rereference its Java command:

Java-classpath "C:/Java test"; "C:/Java test/DF" Hello

We must tell JDK the paths of all. class files one by one, regardless of whether DF is actually a subdirectory of C:/Java test. If we want to use 100. class files with different paths, we have to set classpath to a very long string, which is very tiring. The introduction of package solves this problem well. The package is combined with classpath. The import command is used as an intermediary to skillfully transfer the classpath-based classpath search function to the import, so that the classpath settings are concise and clear. Let's take a look at the example below.

18. Import DF. Person in hello. java. The code is modified as follows:

Import DF. person;

Public class Hello {
Public static void main (string [] ARGs ){
Person = new person ("Mike ");
System. Out. println (person. getname ());
}
}

Set "person. Java" in the DF sub-folder to a DF package. The code is modified as follows:

Package DF;

Public class person {
Private string name;
Public Person (string name ){
This. Name = Name;
}

Public String getname (){
Return name;
}
}

Okay, the magic command line appears:

Javac-classpath "C:/Java test" C:/Java test/Hello. Java"
Java-classpath "C:/Java test" Hello

Although we only set the classpath of C:/Java test this time, the compilation and running have passed! In fact, there are three methods for Java to search for. class files:
1. Global settings. For details, refer to Step 1. The advantage is that the configuration is performed at a time;
Second, set classpath in each javac and Java command line. This is also the most widely used method in this article. Its advantage is that it does not burden the system environment variables;
Third, convert the content in the background to classpath according to the import command. JDK reads the global environment variable classpath and the classpath option Information in the command line, and then merges each classpath with the content converted to the path form of import to form the final classpath. in our example, JDK reads the global environment variable classpath and the classpath option Information in the command line to obtain C:/Java test. Next, import DF. the content in person, that is, DF. person is converted to DF/person, and then C:/Java test is merged into C:/Java test/DF/person, which is the person we need. class path. The number of import statements in hello. Java that are automatically converted. In the command line, we only need to tell the JDK's top-level classpath. The rest is done by the import commands in each class. This kind of data shifting method provides great convenience for us to manually set classpath in the command line.

It should be noted that the import command is used together with the package. Only when the package name is set through "package pacakgename;" Can the package be imported to other classes through the import command. If the import attempts to import a class that has not yet set the package, the JVM will report an error.

19. Let's take a look at how to set classpath when using the JDK class library.

20. Modify hello. Java with the following content:

Import DF. person;
Import java. util. date;

Public class Hello {
Public static void main (string [] ARGs ){
Date = new date ();
System. Out. println (date );

Person = new person ("Mike ");
System. Out. println (person. getname ());
}
}

21. JDK inventory is stored in the C:/program files/Java/jdk1.5.0/JRE/lib/RT. jar file. The introduction to jar files is beyond the scope of this article. Interested readers can read the core Java book written by horstmann.

Jar files can be opened with WinRAR. After you open it with WinRAR, you can see some folders in it. Double-click the Java folder and double-click the util folder. You can see the date. Class file in it. If you have read data. java or other JDK Class Library source code (in the C:/program files/Java/jdk1.5.0/src.zip file), you will find that folders such as Java and util are package. This is why the import command is used in line hello. Java 2nd.

We can use WinRAR's search function to locate the package where a class is located. In the "file search" window, enter date in the "file name to be searched" text box. class, it will find the Rt. the jar file contains two dates. class file, one is Java/SQL/date. class, and Java/util/date. class. The date. Class file in SQL is related to the database, which is not required here. Java/util/date. Class is what we need.

The Rt. jar file is the only entry to the JDK class library, just like C:/Java test in this article. You can specify the. jar file in the classpath option of the command line. Note that the classpath of the. jar file sets some special items. In the previous example, when we set classpath, we only set the path. For the. jar file, we must add the. jar file name directly to the classpath.

22. Enter

Javac-classpath "C:/program files/Java/jdk1.5.0/JRE/lib/RT. jar ";" C:/Java test "" C:/Java test/hello. java"
Java-classpath "C:/program files/Java/jdk1.5.0/JRE/lib/RT. Jar"; "C:/Java test" Hello

Of course there is no problem, because we have specified the Rt. jar file and the C:/Java test classpath. But it is not slow. Enter the following in the command line:

Javac-classpath "C:/Java test" C:/Java test/Hello. Java"
Java-classpath "C:/Java test" Hello

What is incredible is that the compilation and operation are successful! Surprisingly, when we set classspath to only C:/Java test, how does JDK obtain the classpath of Java. util. Date?

The reason is that, just as the Java path has been quietly set in the background, the classpath path of RT. jar is also quietly set in the background. Therefore, we do not need to manually set its classpath.

23. the last thing to mention is that if the main class happens to be in a package (in large-scale development, this is actually the most common phenomenon ), the package name must be added before the class name of the Java command line.

Create a folder named NF under C:/Java test. Delete hello. Class under C:/Java test and move hello. Java to the NF folder. Open hello. Java in the NF folder and set the package attribute for it.

Package NF;

Import DF. person;
Import java. util. date;

Public class Hello {
Public static void main (string [] ARGs ){
Date = new date ();
System. Out. println (date );

Person = new person ("Mike ");
System. Out. println (person. getname ());
}
}

The compilation is no different from the previous one, except that the path after modification is corrected.

Javac-classpath "C:/Java test" C:/Java test/NF/Hello. Java"

The Java command line has changed.

Java-classpath "C:/Java test" NF. Hello

In the preceding command line statement, NF. Hello tells JDK that hello. Class is under the package of NF.

So far, the classpath and package discussions in this article are all over. It can be seen that Java is indeed very difficult to get started. If Java programmers learn how complex Java compilation is, they will mostly leave. Therefore, I believe that sun deliberately simplifies compilation in j2se tutorial to attract more java beginners. Once you have tasted the delicious Java taste, you don't have to worry about them exiting, because coffee is very addictive.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.