Java entry-level instance classpath and Package

Source: Internet
Author: User

From http://www.programbbs.com/doc/437.htm

 

Java is very attractive, but for beginners who have just entered the Java threshold, compile and run a very simple Java program
It's a nightmare. Mingming Program
No
Wrong, but a variety of confusing error messages really make you think twice. 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 also
After experiencing this very painful stage, the problem of difficulty in compilation lies in classpath settings and understanding of package. This article uses examples to solve the problems in the compilation process one by one.
Classpath settings. The running environment of this instance is Windows XP + JDK 1.5.0. For other environments, the reader should easily
.

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:

'Javac' is neither an internal or external command nor a running program.
Or batch files.

This
This is because the javac command cannot be found in windows. This is not clear. Java and javac both have two JDK files in the same subdirectory. Why can they be run directly?
What if Java cannot directly run javac? Originally, Sun quietly added the Java command to the background to run Java files immediately after installing JDK.
Path, so we can directly run the Java command (but we cannot see where it is set, this is not found in the user's path or system's path settings.
Java directory ). However, no other JDK commands need to be added to the search path by the user.

5. In this case, I
You can add your own path search path. Right-click "my computer", select "properties", select "advanced" in the "System Properties" window, and then click "environment variables" to bring up an "environment variable"
In the user Variable Window, create a new variable named "path" 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 to exit by "OK" (a total of 3
Times ). 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
. However, this is not a good solution. As we study Java in the future, we will use JUnit, ant, netbeans, and other application tools.
, These tools
In
During installation, an environment variable named "java_home" pointing to the JDK path is required. Otherwise, the installation will fail. Therefore, we need to improve step 1 to prepare for the future. Follow Step 1
In the "environment variables" window, create a new variable in the user variable named "java_home" 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 variable" window and double-click the path we set to change
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, just add "% java_home %. Now, all path settings are complete. All the way to exit, open a new command line window, and enter
Inbound

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 and save it to the javatest folder.
In the "file name" text box, enter "Hello. Java ". Note: Add a double quotation mark (double quotation mark) before and after the file name. Otherwise, the notepad will save it.
Is a text file of "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
Compile a hello. Class class file in the javatest folder. If the word "1 error" or "XX errors" appears, it indicates the source code
Incorrect input. Follow the error prompt and carefully follow the code in step 1 to locate and correct the error. Check for incorrect code input and incorrect classpath settings. Because this article is about
Set classpath and package correctly. Therefore, we assume that the code entered by the reader is correct. So far, because we are compiling under the current path of the source code
The classpath settings are incorrect.

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 store the source code in javatest.
Of
Folder. Therefore, some important issues are not exposed. In fact, the "javac hello. Java" and
"Java hello" involves two issues: first, how the operating system looks for commands such as "javac" and "Java", and second, how the operating system looks for "hello. Java" and
"Hello. Class" files created by users. For commands such as "javac" and "Java", since they are all executable files, the operating system will follow our steps in step 1.
Search in the configured path. For files such as "Hello. Java" and "hello. Class", the path setting does not work. Because we are currently working on the road
Java and javac will find corresponding java files in the current working path. (For details, refer to 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:
Transferred to the C-drive root directory. The current path leaves the source code.
. 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

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

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"
Come 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
When you call the. Class file in Java or javac, JDK automatically comes here to find the file. 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

JDK
In this case, first find the. Class File Based on the path specified in the classpath option in the command line, and then find 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.

This
In addition, you can use CP, short for classpath, to replace classpath in Java commands, such as Java-cp c:/javatest hello. Special
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
Java and javac can both 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

JDK
The system prompts that the person class cannot be found. Why is javac "C:/Java test/Hello. Java" feasible in step 1, but not here? In step 2
The Hello. Java file is not used for other classes. Therefore, JDK does not need to look for other classes. Here, we modify hello. Java to use 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
Inbound

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

Editing
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
Hello. Java: How many other classes are used in this main class. As long as this class is compiled, JDK automatically compiles other classes, 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

Editing
Translation successful. 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
All. class files only specify 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
Overview. The Package concept is introduced in Java to solve naming conflicts. For example, in our example, we designed a very simple person class.
I sent a class library, which happens to have a person class. When we use this class library, two person classes have a name conflict. JDK does not know which person we want to use.
Class. 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. In general, you cannot avoid the class name and
The class names developed by others are the same, so that each programming
All the people have racked their brains to forcibly rename a class that should have been called writer to sarkuyawriter, mikewriter, and smithwriter?

Now
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, organization leaders announced at the meeting that Zhang San was appointed as the office director. You
I don't know 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 the country, because the other Zhang San is distributed across the country and other cities, and you cannot see it.
You can't touch them. Naturally, you don't have to worry.

Sun has been inspired by this issue of "Michael Jacob". To solve the naming conflict problem, Sun adopted the "Blind-eyed" strategy:
Classes belong 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.

The name of the custom package can be
Members are free to create. As a way to avoid name conflicts, the package name is better than other programs.
Employee
. 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 probably because
You are not shy enough to apply for a domain name. You may not see a conflict between your hypothetical domain name and other domain names. For example, the domain name I assume is sarkuya.com, which is currently unique, so my
The 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
Different sub-packages, such as com. sarkuya. util, Com. sarkuya. Swing, and so on, can be included in the package.

Set
You can add "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 this
COM/sarkuya/util and the sub-path of the folder.

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.

Before
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, because JDK only uses
For other packages, JDK ignores the following class: "You don't have to worry ". If you want to reference the classes of other packages, you must use import to introduce the corresponding classes in other packages. Only in this
JDK will conduct further review, that is, to check whether the usage requirements are met based on the visibility of these classes, class variables and methods in other packages. If this review fails, compilation gets stuck until you give up.
Use these classes, class variables, and methods, or change the modifier of the 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 you find
Name Conflict. 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

Me
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 you want to use the. Class with 100 different paths
File, we have to set classpath as a particularly long string, very tired. The introduction of package solves this problem well. Package and
The classpath is combined to use the import command as an intermediary to skillfully transfer the classpath-based classpath search function to the import body.
Make classpath settings 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;
3.
Is to convert its content to classpath in the background according to the import command. JDK reads the global environment variable classpath and the classpath option in the command line.
And then combine each classpath with the imported content converted to the path form to form the final classpath. In our example, JDK reads all
Obtain the environment variable classpath and the classpath option Information in the command line to obtain C:/Java test. Next, Set
Content, that is, DF. Person is converted to DF/person, and then C:/Java test is merged into C:/Java test/DF/person,
This is the path of the person. class we need. The number of import statements in hello. Java that are automatically converted. In the command line
You only need to tell JDK the top-level classpath, and the rest will be handled by the import commands in each class. This method is manually set in the command line.
Classpath provides great convenience.

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 the source code of data. Java or other JDK class libraries
(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.

Me
You can use WinRAR's search function to locate the package of a class. In the "file search" window, enter date. Class in the "file name to be searched" text box, and
There are two date. class files in the Rt. jar file, one is Java/SQL/date. class, and the other is 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 mine.
.

The Rt. jar file is the only entry to the JDK class library, just like C:/Java test in this article. We can
The classpath option specifies the. jar file. Note that the classpath of the. jar file sets some special items. In the previous example, when we set classpath
You can set the path. For. Jar files, you must add the. jar file name directly to 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 you are a beginner in Java
As soon as Java compilation is so complicated, most of them will 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.

Related Article

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.