The Classpath,package in Java

Source: Internet
Author: User
Tags modifiers

Screen appears:
Exception in thread "main" Java.lang.noclassdeffounderror:c:/javatest/hello

Hello.class clearly in why say class is not, the reason in Classpath does not point to the class path.

1. SET classpath= 、、、、

2, Java-classpath c:/、、、

The JDK separates C:/java Test with spaces into two parts, "C:/java" and "Test/hello.java", and sees C:/java as an invalid option. In this case, we need to enclose the entire path in double quotes, that is,

Javac "C:/java Test/hello.java"

This time the JDK knows that a full path is inside the quotation mark, so there is no error. Also, this is necessary for Java commands, i.e.

Java-classpath "C:/java Test" Hello

Java is tempting, but for beginners who just crossed the threshold of Java, compiling and running an incredibly simple Java program is a nightmare. Clearly the procedure is correct, but all kinds of people do not touch the mind of the error message really let you baffled, many in the Java door lingered for a long time beginners so give up the opportunity to learn Java, it is a pity. The author also experienced this extremely painful stage, feel that the problem of compiling difficult to classpath in the setting of the package and understanding. This paper solves the problem of setting up various classpath in the process of compiling in the way of example. The instance of this article is running in Windows XP + JDK 1.5.0. For other environments, readers should be able to make the appropriate conversion.

1. Download and install JDK1.5.0 and press the default path to install to C:/Program files/java/jdk1.5.0.

2. With the mouse click Windows XP "Start"-> "Run", enter CMD in the pop-up Run window, press OK or enter, open a command line window.

3. At the command line, enter:

Java

There's a long foreign language rolling out, and this is how the JDK tells us how to use the Java command. An important message is implied that the JDK installation was successful and you can use the Java command at the command line.

4. Enter in the command line

Javac

Screen display:

& #39;javac& #39; is not an internal or external command, nor a running program or batch file.

This is because Windows cannot find the reason for Javac this command. This is not clear, Java and Javac are JDK in the same subdirectory of the two files, why can directly run Java and not directly run Javac it. Originally, the Sun company in order to facilitate the installation of the JDK immediately after the Java class file can be run, silently in the background to the Java command added to the path of the search path, so we can run the Java command directly (but we do not see where it is set in the end, This java-stored path is not found in either the user's path or the system's path setting. But as far as sun has done, other JDK commands, regardless, need to be added to the search path by the user themselves.

5. That being the case, we add our path search path. Right-click My Computer, select "Properties", select the "Advanced" tab in the System Properties window, and press the "Environment variables" button to pop up an "environment variable" window and create a new variable in the user variable named "Path" with the variable value "C:/Program files/java/ jdk1.5.0/bin;%path% ". The last%path% means to keep the original path setting and add the current path setting to its front. Press OK to exit (total 3 times). Turn off the original command line window and reopen a new command line window in step 2nd. Enter in this window

Javac

The long foreign language again appeared, this time is to introduce the usage of Javac. Setup succeeded.

6. So far good. So far, we've been able to program. However, this is not a good idea. Because as we delve into JAVA in the future, we'll use applications such as JUnit, Ant, or NetBeans, which, when installed, require an environment variable named "Java_home" that points to the JDK path, otherwise it will not be installed. Therefore, we need to improve the 5th step to prepare for the future. In step 5th, pop the "Environment variables" window and create a new variable in the user variable named "java_home" with the variable value "C:/Program files/java/jdk1.5.0". Note that the variable value here is only jdk1.5.0 and cannot be extended to the bin. When you are sure, return to the "Environment Variables" window, double-click the PATH variable we originally set, and modify its value to "%java_home%/bin;%path%". This effect is exactly the same as the 5th step, except for a java_home variable. In this way, when we need to point to the JDK path, we just need to join the "%java_home%" line. At this point, the path path is all set. All the way OK exit, open a new command line window, enter

Javac

If the long foreign language appears, path is set correctly and everything is OK. If not, carefully check that this step is fully set correctly.

7. Start programming. Create a new subdirectory in the root of C disk, called "Javatest," as a place to store Java source code. Open Notepad in XP, first save it to the Javatest folder, and enter Hello.java in the File name text box. Note that you add a double quotation mark around the filename, or Notepad will save it as a text file for "Hello.java.txt." Then enter the following code:

public class Hello {
public static void Main (string[] args) {
System.out.println ("Hello, World");
}
}

Save the file again.

8. Enter in the Command line window

CD C:/javatest

Transfer the current path into javatest. Then, enter

Javac Hello.java

The JDK compiles and generates a Hello.class class file in the Javatest folder. If the word "1 error" or "XX errors" appears, the source code input is incorrect, according to the error prompts, carefully follow the 7th step of the code to find and correct the error. Please pay attention to the problem that the screening code input error and the CLASSPATH setting are incorrect. Because this article is about how to set up Classpath and package correctly, here's the assumption that the reader's code is accurate. So far, because we are compiling in the current path of the source code, there is no problem with classpath setting.

9. Enter in the Command line window

Java Hello

The screen appears.

Hello World

Successfully, we have successfully compiled and run the first Java program.
However, steps 8th and 9th are not perfect because we compile and run in the Javatest folder, so some very important questions are not exposed. In fact, the 8th step of "Javac Hello.java" and step 9th "Java Hello" involves two questions, one is how the operating system to find "Javac" and "Java" commands, and the second is how the operating system to find "Hello.java" and " Hello.class the files created by these users themselves. For commands such as "Javac" and "Java", because they are executables, the operating system looks for the path paths that we set up in step 6th. For the "Hello.java" and "Hello.class" files, the path setting does not work. Since we are working in the current work path, Java and Javac will find the appropriate Java files in the current work path (the search for class files is special, as detailed in step 11th),
So everything is fine. Let's start by artificially complicating the problem, compiling and running the non current work path to see what happens.

10. Enter in the Command line window

CD C:
into the C-packing directory, the current path away from the storage source of the workspace. Input

Javac Hello.java

Screen appears:

Error:cannot Read:Hello.java
1 Error

I can't find the Hello.java. We're going to give it a path and tell it to C:/javatest to find Hello.java files. Input

Javac C:/javatest/hello.java

OK, this time no error, compile successfully.

11. Input

Java C:/javatest/hello

This back screen appears:

Exception in thread "main" Java.lang.noclassdeffounderror:c:/javatest/hello

The definition of a class is not found in "C:/javatest/hello". Clearly C:/javatest/hello is a. class file, why not find it. It turns out that Java treats. java files differ from. class files. You can specify the path to the. java file directly, and the. class file required by the Java command cannot have an extension or specify an additional path to it.

So, how do you specify the path. For Java-Required. class files, you must specify them by Classpath.

12. In accordance with step 5th, pop the "Environment variables" window and create a new variable in the user variable named "classpath" with the variable value "C:/javatest". Press "OK" to exit all the way. Close the original command Line window, open a new command line window, and enter

Java Hello

"Hello World" came out. This shows that the purpose of setting up classpath in the Environment Variables window is to tell the JDK where to look for the. class file. Once this method is set up, the JDK will automatically come here to look for each time Java or Javac is run, when a. class file needs to be invoked. Therefore, this is a global setting.

13. In addition to this method of setting classpath in the Environment Variables window, there is another way to add an option classpath following the Java command followed by a class file name without the extension. For example

Java-classpath c:/javatest Hello

When the JDK encounters this situation, it 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 when it is not found. In this case, even if the global CLASSPATH environment variable is not set, it can be run because the CLASSPATH has been specified correctly on the command line.

To better illustrate the classpath problem in the following example, we first remove the global CLASSPATH environment variable and replace it with command-line options if necessary-classpath. pops up the Environment Variables window, selects the variable name of "Classpath", and presses the "delete" key.

In addition, the Java command can also use the CP, or classpath abbreviation to replace the classpath, such as JAVA-CP c:/javatest Hello. It is particularly noted that before JDK 1.5.0, javac commands cannot be replaced with CP instead of Classpath, but only with classpath. In JDK 1.5.0, both the CP and the classpath can be used by Java and Javac. Therefore, for consistency, it is recommended that you use Classpath as the option name.

14. We again artificially complicate the issue. Close the Notepad that is editing Hello.java, and then change the Javatest folder name to "Java Test" with space. On the command line, enter

Javac C:/java Test/hello.java

The long foreign language came out again, but this time it was an error:

Javac:invalid Flag:c:/java

The JDK separates C:/java Test with spaces into two parts, "C:/java" and "Test/hello.java", and sees C:/java as an invalid option. In this case, we need to enclose the entire path in double quotes, that is,

Javac "C:/java Test/hello.java"

This time the JDK knows that a full path is inside the quotation mark, so there is no error. Also, this is necessary for Java commands, i.e.

Java-classpath "C:/java Test" Hello

For long file names and folders in Chinese, XP can be without double quotes below. But in general, double quotes are not error-prone and easy to understand, so it is recommended that you use double quotes in the CLASSPATH option.

15. Let's take another look. java files use other classes. Create a new Person.java file in C:/java test, which reads as follows:

public class Person {
private String name;

Public person (String name) {
THIS.name = name;
}

Public String GetName () {
return name;
}
}

Then, modify the Hello.java, which reads as follows:

public class Hello {
public static void Main (string[] args) {
person who = new Person ("Mike");
System.out.println (Person.getname ());
}
}

Entering at the command line

Javac "C:/java Test/hello.java"

The error came:

C:/java Test/hello.java:3: Cannot find Symbol
Symbol:class person

The JDK hint could not find the person class. Why Javac "C:/java Test/hello.java" is feasible in the 14th step, but not here. The Hello.java file in step 14th is not used for other classes, so the JDK does not need to look for other classes, and here we have modified the Hello.java to use a person class. According to step 11th, we need to tell the JDK where to look for the classes that are used, even if the class being used is with Hello.java, under C:/java test. Input

Javac-classpath "C:/java Test" "C:/java Test/hello.java"

Compiled, the JDK generated both Hello.class and person.class two files under the C:/java Test folder. In fact, because Hello.java uses the Person.java class, the JDK compiles and builds the Person.class, and then compiles the hello.class. So, no matter how many other classes the main class uses, it's convenient for the JDK to compile the class Hello.java automatically. Input

Java-classpath "C:/java Test" Hello

The screen appears.

Mike

Success.

16. Step 15th explains how to use a Person.java that we created in Hello.java, and this class is in the same folder as Hello.java. In this step, we'll examine the situation where person.java is placed under different folders.

Delete the Person.class file under the C:/java Test folder, and then create a new folder named DF under the C:/java Test folder and move the Person.java under the C:/java Test folder below it. Entering at the command line

Javac-classpath "C:/java test/df" "C:/java Test/hello.java"

Compiled through. At this time Javac command no different, just change classpath to C:/java TEST/DF on the line.

Entering at the command line

Java-classpath "C:/java Test" Hello

This is because Java needs to find two. class files in different folders, and the command line tells the JDK only one path, C:/java Test, in this folder, Hello.class can only be found, person.class files cannot be found, so errors are predictable:

Exception in thread "main" Java.lang.NoClassDefFoundError:Person
At Hello.main (Hello.java:3)

Really can't find Person.class. When setting more than two classpath, each path is enclosed in double quotes, and the paths are ";" And each path is separated from the ";" Cannot have spaces between them. So, we re-enter at the command line:

Java-classpath "C:/java Test"; C:/java TEST/DF "Hello

Compilation succeeded. But it also exposes a problem, if we need to use a lot of classes in different folders, then this classpath setting is not very long. There is no way, for all the. class files under a folder, specify only the classpath of this folder, and then have the JDK automatically search for all the appropriate paths under this folder. There, just use package.

Package Introduction. Java introduces the concept of package, mainly to solve the problem of naming conflicts. For example, in our case, we've designed a very simple person class, and if someone has developed a class library that happens to have a class, and when we use this class library, two person classes have a naming conflict, and the JDK doesn't know which one to use. What's more, when we have developed a very large class library, it is inevitable that there will be more and more naming conflicts in our class libraries that are developed with others in the class library. In order to avoid their own class name and others to develop the same class name, and let each programmer racked their brains to a class that should be called writer forcibly renamed to Sarkuyawriter,mikewriter, Smithwriter bar.

This is true in real life. If your name is John, and if there are several of you in the same unit called John, then your question will come. One day the unit leader announced at the meeting, John was appointed director of the Office, you simply do not know whether to cry or laugh. But if your unit is only your name John, you will not care about the country called John Number of people, because the other John are distributed throughout the country, other cities, you can not see them, touch them, naturally do not worry.

Sun from this "John problem" has been greatly inspired, in order to solve the naming conflict problem, the "blind Mind" strategy has been adopted: each class is assigned to a specific area, all classes in the same zone are not allowed to have the same name, and classes in different areas are allowed to exist with the same name because they are not visible to each other. In this way, it solves the problem of naming conflict, just as Beijing's John and Shanghai's John are not the same person after all. This area is called package in Java. Because package is very important in Java, if you don't define your own package,jdk your classes will be grouped into a default nameless package.

The name of a custom package can be created freely by each programmer. As a means of avoiding naming conflicts, package's name is best enough to distinguish it from other programmers. On the Internet, each domain name is unique, so Sun recommends that you write down your own domain name as package. If you do not have your own domain name, it is likely that only because the bag is shy and not to apply for it, not necessarily your imaginary domain name and other domain names conflict. For example, the author's hypothetical domain name is sarkuya.com, is currently the only, so my package can be named Com.sarkuya. Thank you Java gave us a free use of our own domain name opportunities, the only prerequisite is to write backwards. Of course, each package can also carry a different sub-package, such as com.sarkuya.util,com.sarkuya.swing, and so on.

The way to define package is to add "package PackageName" to the first line of the corresponding. java file. , and there can be only one package per. java file. In fact, the implementation of package in Java is a combination of the computer file system, that is, what kind of package you have, what kind of storage path on the hard disk. For example, the package name of a class is Com.sarkuya.util, and the class should be stored under the Com/sarkuya/util path. As to which folder the Com/sarkuya/util is, the 18th step will be discussed.

In addition to the problem of avoiding naming conflicts, package also extends the ability to protect all class files under the current package, mainly by defining several different modifiers for the class: public, Protected, private, Plus a friendly type that doesn't really exist.

For classes, generic variables and methods that are labeled public, any class in the package and outside the package can be accessed;
Protected classes, generic variables and methods, any classes within the package, and those inherited from this class are accessible;
Private classes, generic variables and methods, the package of any class outside the package can not access;
If a class, generic variable, and method are not modified with these three modifiers, it is the friendly type, then any class within the package can access it, and none of the classes outside the package will be able to access it (including subclasses of this class outside the package), so this class, generic variable, and method are friendly to the other classes in the package, Open, while the other classes outside the package are closed.

As I said earlier, package is primarily to solve the naming conflict problem, therefore, classes that are in different packages do not have to worry about conflicts with the class names of other packages, because JDK uses only the classes below this package by default, and the JDK ignores all other packages: "No eyes, no mind." If you are referencing a class of another package, you must import the corresponding class in the other package by importing. Only then will the JDK conduct further review, that is, to review compliance with usage requirements based on the visibility of these classes, generic variables, and methods in other packages. If this review does not pass, the compilation is stuck until you discard the use of these classes, generic variables and methods, or change the modifiers of the class, generic variables and methods that are introduced to match the requirements. If this review is passed, the JDK is finally named whether the conflict is reviewed. If you find a naming conflict, you can explicitly reference the corresponding class by referencing the full name in your code, such as using the

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

Or

Java.sql.Date = new Java.sql.Date ().

The third major role of package is to simplify the setting of classpath. Remember the obstacles in step 16th? Here is a new reference to its Java command:

Java-classpath "C:/java Test"; C:/java TEST/DF "Hello

We must tell the JDK all the path to the. class file, regardless of whether DF is actually a subdirectory of C:/java test. If you want to use a. class file with 100 different paths, we have to set the classpath to a particularly long string, which is tiring. The introduction of package is a good solution to this problem. Package and Classpath combined, through the import instructions for the intermediary, the original must be completed by the classpath of the classpath search function, very cleverly transferred to the body, so that the classpath set concise and clear. Let's take a look at the following examples first.

18. First 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 who = new Person ("Mike");
System.out.println (Person.getname ());
}
}

Then set the Person.java in the DF subfolder 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;
}
}

Well, the Magic command line appears:

Javac-classpath "C:/java Test" "C:/java Test/hello.java"
Java-classpath "C:/java Test" Hello

Although this time we only set the C:/java test Classpath, but the compilation and the operation actually all passed. In fact, there are three ways in which Java searches for. class files:
One is the overall setting, as detailed in step 12th, the advantage is one set, each use;
The second is to set up classpath in each javac and Java command line, which is also the most used way in this paper, its advantage is not to aggravate the burden of system environment variables;
Third, according to the import instruction, its contents are converted to classpath in the background. The JDK reads the Global environment variable classpath and the CLASSPATH option information on the command line, and then merges each classpath with the contents of the import converted to a path to form the final classpath. In our example, the JDK reads the Global environment variable classpath and the CLASSPATH option information in the command line to get C:/java Test. Next, import DF. The content in person, that is, Df.person, is converted to Df/person, and then the C:/java Test is merged into C:/java Test/df/person, which is the path of the person.class we need. How many import statements are in the Hello.java and how often such conversions are done automatically. And we just tell the JDK at the top of the classpath on the command line, and the rest is done by the import instructions in each class. This deceitful act approach provides a great convenience for us to manually set up classpath in the command line.

It should be noted that the import instructions are used in connection with package, only in a certain class through the "package pacakgename;" After you set the package name, you can import the other classes through the import directive. If the import attempts to import a class that has not yet set up a package, the JVM will complain.

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

20. Modify the Hello.java as follows:

Import DF. person;
Import Java.util.Date;

public class Hello {
public static void Main (string[] args) {
Date date = new Date ();
SYSTEM.OUT.PRINTLN (date);

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

JDK class inventory is placed in the C:/Program Files/java/jdk1.5.0/jre/lib/rt.jar file. The introduction to the jar file is beyond the scope of this article, and interested readers can read the core Java book written by Horstmann.

Jar files can be opened with WinRAR. With WinRAR open, you can see that there are some folders, double-click the Java folder, and then double-click the Util folder, you can see the Date.class file in it. If you've seen the source code for Data.java or other JDK libraries (in the C:/Program files/java/jdk1.5.0/src.zip file), you'll find that folders like Java and Util are package. This is also why the import directive was used in line 2nd of Hello.java.

We can use the WinRAR lookup function to locate the package where a class resides. In the Find File window, in the file name to find text box, enter Date.class to find out that 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. Among them, the Date.class file under SQL is related to the database, not what we need here, Java/util/date.class is what we want.

The Rt.jar file, like the C:/java test in this article, is the only portal to the JDK class library. We can specify the. jar file at the command line classpath option. Note that the. jar file's classpath settings have some special beads. In the previous example, when we set the Classpath, we set the path, and for the. jar file, we must add the. jar file name directly to the CLASSPATH.

22. Enter at command line

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

This is certainly not a problem, because we have specified the Rt.jar file and C:/java test two classpath. But wait a minute, enter at the command line:

Javac-classpath "C:/java Test" "C:/java Test/hello.java"
Java-classpath "C:/java Test" Hello

Amazingly, the compilation and operation was successful. Surprisingly, when we set the Classspath only to C:/java test, how did the JDK draw the classpath of Java.util.Date.

The reason is that, just as Java's path path has been quietly set up in the background, Rt.jar's classpath path is quietly set in the background as well. Therefore, we do not have to bother to set its classpath manually.

23. The last point to mention is that if the main class happens to be in a package (in fact this is the most common phenomenon in large development), then the class name of the Java command line must precede the package name.

Under C:/java Test, create a new folder named NF. Remove the Hello.class under C:/java test and move Hello.java to the NF folder. Open the Hello.java under the NF folder and set the Package property for it.

Package NF;

Import DF. person;
Import Java.util.Date;

public class Hello {
public static void Main (string[] args) {
Date date = new Date ();
SYSTEM.OUT.PRINTLN (date);

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

The compilation is no different from the previous one, except that it fixes the path after the correction.

Javac-classpath "C:/java Test" "C:/java Test/nf/hello.java"

And the Java command line has changed.

Java-classpath "C:/java Test" NF. Hello

In the command line above, NF. Hello tells Jdk,hello.class under the package of NF.

At this point, the discussion about Classpath and package is all over. This shows that the introduction of Java is indeed very difficult. If the beginner Java programmers see Java compilation is so complicated, most of them will withdraw. Therefore, the author believes that sun in the J2SE tutorial deliberately to compile the problem as simple as possible to attract more Java beginners. Once you've tasted the delicious Java flavor, you don't have to worry about quitting, because coffee is a very addictive one.

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.