Java in Eclipse: Hello world and Java. Lang. noclassdeffounderror: exception in thread "main"

Source: Internet
Author: User
Tags one more line
Beginning with Java, especially those who use eclipse (including myself), it is very likely that such errors are made on path and classpath. This problem is often encountered by new javer users. I will take a note today and use it myself in the future.

The first is the concept of path and classpath. You can find and change the settings of these two environment variables from system> advanced> environment variables.
The path is actually relatively simple, and is not specific to Java. Its function is to tell the command interpreter where to find the commands we need to execute. This setting needs to be set in many software, such as cygwin.
Classpath is unique to Java. We know that Java adopts the bytecode design to ensure the portability of program source code. That is to say, no matter what the basic system architecture is, any Java source code will be converted to the corresponding bytecode by the Java Virtual Machine. the bytecode is platform-related and needs to be specified during execution, to ensure that the Java Virtual Machine can find the bytecode corresponding to the source code. If classpath is not specified or an error is specified when you run the Java program, the virtual machine cannot find the correct path, and thus the java. Lang. noclassdeffounderror: exception in thread "Main" error occurs. Therefore, when such a similar problem occurs, you should first check whether the classpath has a problem.

In addition, when we use eclipse for development, we may find that we can execute the program in the command line, but when debugging in eclipse, the above problem occurs. I encountered this problem. Later, I found that when I started debugging, because eclipse is the program that was last run by default, so his classpath path is still the last program. When you debug a new program, you will not be able to find it. The possible solution is to fill in the corresponding path of your program in the classpath tab of run.... It should be OK!

The following is a related post I found, which is detailed:

-------------------------------- Post: BBS shuimu Tsinghua station (Mon Apr 9 08:15:01 2001)
In Java, classpath and package ---------------------------------------------------------

Class path)
When you are eager to install Java, write Hello world, compile and run it, and wait for the two beautiful words to appear, unfortunately, only can't find class helloworld or exception in thread "Main" Java. lang. nosuchmethoderror
: Maain. Why? The compiled class is clearly in. let's take a look at the Java program running process. we already know that Java is interpreted and run through the Java Virtual Machine, that is, compiled by javac through Java commands. the class file is the code to be executed by the virtual machine. It is called bytecode. The virtual machine uses classloader to load these bytecode, that is, the class in the general sense. here is a question: where does the classloader know the Java class library and the user's class? Or there is a default value (current path ). A user-specified variable is required to indicate that the variable is a classpath or to pass parameters to the virtual machine during running. this indicates the three methods of classpath. the compilation process is similar to the running process, but one is to find and compile, and the other is to find and load. in fact, Java virtual machines are initialized by Java luncher, that is, Java (or java.exe)
In this program, the virtual machine searches and loads all required classes in the following order:
1. Bootstrap class: a Java platform class, including the classes in rt. jar and i18n. jar.
2. extension class: classes using Java extension mechanism are all located in the extension directory ($ java_home/JRE/lib/E
XT)
. Jar file package.
3. User class: A developer-defined class or a third-party product that does not use the Java extension mechanism. you must use the-classpath option in the command line or use the classpath environment variable to determine the location of these classes. the user class we mentioned above refers to these classes. in this way, the user only needs to specify the location of the user class, And the bootstrap class and extension class are automatically searched. so what should we do? The user class path is a directory containing class files ,. jar ,. for the list of zip files, as for how to find the class, because the package is involved, we will talk about it below. For now, we can think that if this class is included, we will find this class. unix-like systems are basically ":" And windows are mostly ";". the possible sources are:
* ".", That is, the current directory. This is the default value.
* Classpath environment variable. Once set, the default value is overwritten.
* If you specify the command line parameter-CP or-classpath, overwrite the preceding two.
* Specified by the-jar parameter. the jar package overwrites all other values, and all classes are from the specified package. the generated executable. jar files also require other knowledge, such as package and specific configuration files, which will be mentioned at the end of this article. let's take a look at some examples of JDK.
Let's take a helloworld example to illustrate. first make the following assumptions:
* The current directory is/helloworld (or C:/helloworld, the previous one will be used later)
* JDK version 1.2.2 (in Linux)
* The PATH environment variable is correctly set. (You can use tools in any directory)
* The file is helloworld. Java and the content is:
Public class helloworld
{
Public static void main (string [] ARGs)
{
System. Out. println ("Hello world! /N ");
System. Exit (0 );
}
}
First, this file must be written correctly. If you are familiar with C, it is likely to be written as follows:
Public static void main (INT argc, string [] argv)
{
....
}
This is wrong. If you believe it, try it. because there is no Java specification at hand, the following conjecture is made: the Java application must start with public static void main (string []), and none of the other methods can be used. so far, we have set only path.
1. The current path indicates that your. Class file is in the current directory,
[Helloworld] $ javac helloworld. Java // This step won't have much problem,
[Helloworld] $ Java helloworld // This step may be faulty.
If there is a problem like the one at the beginning, first make sure that it is not because of the wrong command. If there is no wrong command,
Next we will do the following:
[Helloworld] $ echo $ classpath
Or
C:/helloworld> echo % classpath %
Check whether the classpath environment variable is set. If so, run the following command:
[Helloworld] $ classpath =
Or
C:/helloworld> set classpath =
To empty it and then run it again. this time, the default user class path is ". ", so there should not be the same problem. another way is to put ". "Add to classpath.
[/] $ Classpath = $ classpath :.
Or
C:/helloworld> set classpath = % classpath % ;.
It can also be successful. Good luck.
2. This method can be used when your program requires third-party class libraries and is commonly used. for example, common database drivers and Servlet packages required by Servlet writing. the setting method is to add classpath to the environment variable. then you can compile and run the program directly. take helloworld as an example. If you want to run it in the root directory, you can directly execute it in the root directory.
$ Java helloworld
Or
C:/> JAVA helloworld
This will certainly lead to errors. If your classpath has not been changed, I think you should know why it is wrong. How can you change it? As mentioned above, user class paths are directories that contain the classes you need ,. jar package ,. zip package. no package is generated now, so we have to put helloworld. the directory where the class is located is added to the classpat. According to the previous practice, run it again and check it out. Haha, it's successful. Change the path and then it's successful !! Not just? Br/> to directly run the class, when you want to import some of the classes, the same processing is done. I don't know if you think of it. With the continuous expansion of your system, (of course, there are some East regions that require Java? If all the variables are added to this environment variable, the variable will become more and more bloated. Although the environment variable space can be opened very large, it is always uncomfortable. Let's take a look at the following method.
3. Specify classpath in the command line parameters.
Or the same goal as above, execute helloworld in any directory. How can this method be implemented?

[/] $ Java-CP/helloworld
Or
C:/> JAVA-cp c:/helloworld
This is the simplest application of this method. When you use another package, can you use it? Br/> method. For example:
$ Javac-classpath apath/apackage. jar:. myjava. Java
$ Java-CP apath/apackage. jar:. myjava
Or
C:/> javac-classpath apath/apackage. jar;. myjava. Java
C:/> JAVA-CP apath/apackage. jar;. myjava
This method is also inconvenient when the third-party package is in a long path or requires more than two bags? Br/> at this time, it is very inconvenient to write for every compilation and running. You can write a script to solve this problem. For example:
Compile (file, permission changed to executable, current directory)
$ Cat compile
---------------------------
#! /Bin/bash
Javac-classpath apath/apackage. jar: anotherpath/anotherpackage. jar:. m
Yjavva. Java
---------------------------
Run (file, permission changed to executable, current directory)
$ Cat run
---------------------------
#! /Bin/bash
Java-CP apath/apackage. jar: anotherpath/anotherpackage. jar:. myjava
---------------------------
Or:
Compile. bat
C:/helloworld> type compile. bat
-------------------------
Javac-classpath apath/apackage. jar: anotherpath/anotherpackage. jar:. m
Yjavva. Java
-------------------------
Run. bat
C:/helloworld> type run. bat
------------------------
Java-CP apath/apackage. jar: anotherpath/anotherpackage. jar:. myjava
------------------------
You can try it.
As mentioned above, what is an extension class? Java extension class is the Java class package (or native code) used by application developers to extend the functions of the core platform ). virtual machines can use these extension classes like system classes. someone suggested that you put the package into the extension directory. In this way, classpath is not required or specified. Isn't it very convenient? It can run correctly, but I personally think it is not good to put everything in it. Some standard extension packages can be used, such as JavaServlet and Java3D.

We recommend that you add an environment variable, such as jarpath, to specify a directory and store your jar zip packages. This will be done by Sun. in Windows 98, I was unable to install it all the time, but it was always dead. It was hard to install it. By default, the tool could not run correctly. jar works normally after being put into classpath. the removal is still correct for testing now. after multiple tests, it was found that if JDK was installed successfully, it would crash when no JDK was installed. Just install it several times. if the installation fails. add classpath to jar and give it a try.
Package)
The "package" in Java is an important concept. The package is defined as follows:
Definition: a package is a collection of related classes and interfacesthat provides access protection and namespace management. that is, a package is a set of classes and interfaces that provide access protection and namespace management. the purpose of using a package is to make the class easy to search and use, prevent name conflicts, and control access. here we will not discuss too many items about the package, but will only discuss and compile, run, and class path related things. for more information about the package, see related documents.
To put it simply, the package is a directory, and the sub-package below is a subdirectory. The class in this package is the file under this directory. We will illustrate it with an example.
First, create the directory structure as follows: packagetest/source/. Later, the root directory refers to the packagetest directory, and our source program is placed under the source directory. The source program is as follows:
Packagetest. Java
Package pktest;
Import pktest. subpk .*;
Public class packagetest
{
Private string value;
Public packagetest (string S)
{
Value = s;
}
Public void printvalue ()
{
System. Out. println ("value of packagetest is" + value );
}
Public static void main (string [] ARGs)
{
Packagetest test = new packagetest ("this is a test package ");
Test. printvalue ();
Packagesecond second = new packagesecond ("I am in packagetest ");
Second. printvalue ();
Packagesub sub = new packagesub ("I am in packagetest ");
Sub. printvalue ();
System. Exit (0 );
}
}
Packagesecond. Java
Package pktest;
Public class packagesecond
{
Private string value;
Public packagesecond (string S)
{
Value = s;
}
Public void printvalue ()
{
System. Out. println ("value of packagesecond is" + value );
}
}
Packagesub. Java
Package pktest. subpk;
Import pktest .*;
Public class packagesub
{
Private string value;
Public packagesub (string S)
{
Value = s;
}
Public void printvalue ()
{
Packagesecond second = new packagesecond ("I am in subpackage .");
Second. printvalue ();
System. Out. println ("value of packagesub is" + value );
}
}
Main. Java
Import pktest .*;
Import pktest. subpk .*;
Public class main ()
{
Public static void main ()
{
Packagesecond second = new packagesecond ("I am in main ");
Second. printvalue ();
Packagesub sub = new packagesub ("I am in main ");
Sub. printvalue ();
System. Exit (0 );
}
}
Here, Main. java is a program outside the package. It is used to test the class in the packagetest of the program access package outside the package. java belongs to the pktest package and is also the main program. packagesecond. java also belongs to pktest, and packagesub belongs to the subpk package under pktest, that is, pktest. subpk. for detailed usage, see the source program.
All right, first place the source program in the source directory, make source into the current directory, and then compile it. Haha, an error occurred,
Main. Java: 1: Package pktest not found in import.
Import pktest .*;
This involves how to find the class path in the package. We previously made a hypothesis: "If this class is included, this class is found." Now there is a problem. in fact, the JDK tool javac javajavadoc needs to look for classes. When you see the directory, it is considered as the package name. For the import statement, a package corresponds to a directory. in this example, import pktest. * We know that the class path can contain a directory, so we will take that directory as the root. For example, if there is a directory/myclass, we will find the/myclass/pktest directory and Its classes. if not, an error is returned. because the current class path only has the current directory, but the current directory does not have the pktest directory, an error will occur. the class path can also contain. jar. ZIP file. These are the compressed packages that can contain directories. jar. the zip file is treated as a virtual directory, and then treated as a directory. well, you should know how to do it. The modified directory structure is as follows:
Packagetest
|
|__ Source main. Java
|
|__ Pktest packagetest. Java packagesecond. Java
|
|__ Subpk packagesub. Java
Then re-compile and run the packagetest.
[Source] $ Java pktest/packagetest
Why Did something go wrong?
Exception in thread "Main" Java. Lang. noclassdeffounderror: pktest/packagetest
In this case, Java is running the name of a class. It can search for this class no matter where your class is located, as we discussed earlier, so it regards pktest/packagetest as the name of a class, and of course there will be errors. This should be done,
[Source] $ Java pktest. packagetest
Everyone should understand the truth. I will not say much. note that javac is different. It indicates the path of the source file. javac only compiles and does not run. The search class is only executed when the import is encountered in the source file. It has nothing to do with the package where the source file is located. there seems to be some bad points, how to generate it. the class files are so scattered. It looks awkward. don't worry, javac has a-d command line parameter, you can specify a directory to generate. class file to you according to the package

Put it in this directory.
[Source] $ mkdir classes
[Source] $ javac-D classes pktest/packagetest. Java
[Source] $ javac-D classes main. Java
How can I run it?
[Source] $ CD classes
[Classes] $ Java pktest. packagetest
[Classes] $ Java main
You can. in fact, this set of JDK tools is small and simple, and has powerful functions. It is not necessary to use or use errors. The key is to understand the principles and necessary knowledge behind the tool. the integration environment is good, but it shields a lot of underlying knowledge and does not make any mistakes. Once an error occurs, it will be difficult to do without the necessary knowledge. I had to go to the BBS to ask, others only tell you how to solve the problem. The next time you encounter a slightly changed problem, you will not understand it. so don't stick to the tools. This set of Java tools can be combined and used. Small and Medium Projects (50 or 60 classes) can still cope with it.
Iii. Jar files
See. Jar. Zip as A. jar file.
1. We can see from the above that the JAR file is very important in Java, which greatly facilitates your use. we can also make our own. jar package. use the previous example, Main. java is a non-package. With the class in the pktest package, we want to make pktest into one. jar package, very simple. We just put. classes are all centralized,
[Classes] $ jar-CVF mypackage. Jar pktest
The mypackage. jar file will be generated and tested. The main. class we generated just now is under the classes directory. Therefore, we can know from the beginning:
[Classes] $ Java-CP mypackage. jar:. Main
You can run it.
2. If you have read the JDK example, you will know that. jar can also be run directly,
[/Demo] $ Java-jar ajar. Jar
Well, let's give it a try,
[Classes] $ Java-jar mypackage. Jar
Failed to load main-class manifest attribute from
Mypackage. Jar
It seems that our jar is different from its jar. What is the difference? Take it as an example to recompile and generate. JAR file. After comparison, it is found that. META-INF/manifest in jar package. the MF file is different. There is one more line, main-class: XXXXX. Check the error message. The main-class is not specified. Check the jar command and find a parameter-M,
-M include manifest information from specified manifest File
It has something to do with the error information. It seems that it has to read a preparation file, so it has to write it as a cat.
[Classes] $ cat mymanifest
Manifest-version: 1.0
Main-class: pktest. packagetest
Created-by: 1.2.2 (Sun Microsystems Inc .)
[Classes] $ jar cvfm mypackage. Jar mymanifest pktest
Added manifest
Adding: pktest/(in = 0) (out = 0) (stored 0%)
Adding: pktest/packagesecond. Class (in = 659) (out = 395) (deflated 40%)
Adding: pktest/subpk/(in = 0) (out = 0) (stored 0%)
Adding: pktest/subpk/packagesub. Class (in = 744) (out = 454) (deflated 38%)

Adding: pktest/packagetest. Class (in = 1041) (out = 602) (deflated 42%)
[Classes] $ Java-jar mypackage. Jar
Value of packagetest is this is a test package
Value of packagesecond is I am in packagetest
Value of packagesecond is I am in subpackage.
Value of packagesub is I am in packagetest
Now, we have a. jar file that can be directly executed. You can try it on your own.
Try to create an executable jar with main as the main program.
Bytes ----------------------------------------------------------------------------------------------

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.