How to execute a java .class from the command line - java

I have a compiled java class:
Echo.class
public class Echo {
public static void main (String arg) {
System.out.println(arg);
}
}
I cd to the directory and enter: java Echo "hello"
I get this error:
C:\Documents and Settings\joe\My Documents\projects\Misc\bin>java Echo "hello"
Exception in thread "main" java.lang.NoClassDefFoundError: Echo
Caused by: java.lang.ClassNotFoundException: Echo
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Could not find the main class: Echo. Program will exit.
What is the simplest way to get my java code in a form that I can run from the command line as apposed to having to use Eclipse IDE?

Try:
java -cp . Echo "hello"
Assuming that you compiled with:
javac Echo.java
Then there is a chance that the "current" directory is not in your classpath ( where java looks for .class definitions )
If that's the case and listing the contents of your dir displays:
Echo.java
Echo.class
Then any of this may work:
java -cp . Echo "hello"
or
SET CLASSPATH=%CLASSPATH;.
java Echo "hello"
And later as Fredrik points out you'll get another error message like.
Exception in thread "main" java.lang.NoSuchMethodError: main
When that happens, go and read his answer :)

With Java 11 you won't have to go through this rigmarole anymore!
Instead, you can do this:
> java MyApp.java
You don't have to compile beforehand, as it's all done in one step.
You can get the Java 11 JDK here: JDK 11 GA Release

You need to specify the classpath. This should do it:
java -cp . Echo "hello"
This tells java to use . (the current directory) as its classpath, i.e. the place where it looks for classes. Note than when you use packages, the classpath has to contain the root directory, not the package subdirectories. e.g. if your class is my.package.Echo and the .class file is bin/my/package/Echo.class, the correct classpath directory is bin.

You have no valid main method... The signature should be:
public static void main(String[] args);
Hence, in your case the code should look like this:
public class Echo {
public static void main (String[] arg) {
System.out.println(arg[0]);
}
}
Edit: Please note that Oscar is also right in that you are missing . in your classpath, you would run into the problem I solve after you have dealt with that error.

If you have in your java source
package mypackage;
and your class is hello.java
with
public class hello {
and in that hello.java you have
public static void main(String[] args) {
Then
(after compilation)
changeDir (cd) to the directory where your hello.class is.
Then
java -cp . mypackage.hello
Mind the current directory and the package name before the class name.
It works for my on linux mint and i hope on the other os's also
Thanks Stack overflow for a wealth of info.

My situation was a little complicated. I had to do three steps since I was using a .dll in the resources directory, for JNI code. My files were
S:\Accessibility\tools\src\main\resources\dlls\HelloWorld.dll
S:\Accessibility\tools\src\test\java\com\accessibility\HelloWorld.class
My code contained the following line
System.load(HelloWorld.class.getResource("/dlls/HelloWorld.dll").getPath());
First, I had to move to the classpath directory
cd /D "S:\Accessibility\tools\src\test\java"
Next, I had to change the classpath to point to the current directory so that my class would be loaded and I had to change the classpath to point to he resources directory so my dll would be loaded.
set classpath=%classpath%;.;..\..\..\src\main\resources;
Then, I had to run java using the classname.
java com.accessibility.HelloWorld

First, have you compiled the class using the command line javac compiler? Second, it seems that your main method has an incorrect signature - it should be taking in an array of String objects, rather than just one:
public static void main(String[] args){
Once you've changed your code to take in an array of String objects, then you need to make sure that you're printing an element of the array, rather than array itself:
System.out.println(args[0])
If you want to print the whole list of command line arguments, you'd need to use a loop, e.g.
for(int i = 0; i < args.length; i++){
System.out.print(args[i]);
}
System.out.println();

Related

Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang3.builder.EqualsBuilder

So far I have downloaded Apache Commons library , extracted the library
commons-lang3-3.8.1.jar in Java\jdk1.8.0_172\jre\lib\ext.
Now I have created a class with two fields and I want to compare two objects using
ob1.equals(ob2). Method equals and hashCode have been overridden and the error I'm getting is Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang3/builder/EqualsBuilder at runtime.
import java.util.*;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
class key{
int end;
LinkedList<Integer> via = new LinkedList<>();
key(int x,LinkedList<Integer> ob){
this.end = x;
this.via = ob;
}
#Override
public int hashCode(){
return new HashCodeBuilder().append(end).append(via).toHashCode();
}
#Override
public boolean equals(Object obj)
{
if(!(obj instanceof key))
return false;
if(this==obj)
return true;
key o=(key)obj;
return new EqualsBuilder().append(end,o.end).append(via,o.via).isEquals();
}
}
class main{
public static void main(String[] args)
{
key ob1 = new key(12,new LinkedList<Integer>(Arrays.asList(1,2,3)));
key ob2 = new key(12,new LinkedList<Integer>(Arrays.asList(1,2,3)));
System.out.println(ob1.equals(ob2)); //expecting true
}
}
The details of the error are given below.
Exception in thread "main" java.lang.NoClassDefFoundError:
org/apache/commons/lang3/builder/EqualsBuilder
at key.equals(test.java:29)
at main.main(test.java:43)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang3.builder.EqualsBuilder
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
... 2 more
I have been facing this issue for a long time. I have checked all the class files and I'm quite sure that the libraries are loaded properly but I don't know why I'm getting NoClassDefFoundError at the runtime.
After spending hours on this issue I finally fixed it by setting the CLASSPATH variable.
I tried using -cp command but unfortunately that didn't work for me. If we do this explicitly, then you don't need to supply a "-cp" or "-classpath" switch value to the java compiler and java interpreter, since they will already know the updated classpath.
On my windows machine, I have set the CLASSPATH variable via the following:
set CLASSPATH=/coding #October\lib\commons-lang3-3.8.1.jar;.
Currently, I'm in coding #October directory. The commons-lang3-3.8.1.jar file is located in the       coding #October\lib directory.The myapp.java file is located in the coding #October directory.
After setting the classpath, I can then compile and execute myapp.java via
javac myapp.java command directly and then java myapp to execute the script.
You placed the jar in the correct jre\lib\ext relative path... but it will work only if the java command you run comes from the jre\bin directory of the same jre path where you did the change.
If you copied the correct jar in the extension directory but you get this exception it very probably means that as you run your program you don't use the JRE where you did the change but another one.
The java command from the PATH env variable very probably doesn't refer to the JRE you extended. You can display PATH in your shell to check that.
So either set the PATH with the java home path of the JRE you extended or just run the java command by specifying the absolute path such as /foo/jre/bin/java main.
It should (to not say has to) work.
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang3/StringUtils
at io.appium.java_client.internal.ElementMap.getElementClass
Answer: add selenium jar "commons-lang3-3.8.1" for resolving this issue

Unsure about reason behind NoClassDefFoundError

I have built a DLL which I am attempting to wrap Java code with, however I am having some troubles with running my Java program. I wrote a simple test DLL and Java program and am producing the same error, and although there are plenty of resources regarding NoClassDefFoundError online I can't seem to solve mine with any troubleshooting methods.
Here is my D:\Test1.Java file
public class Test1 {
static {
//System.loadLibrary("HeyLand");
System.load("D://HeyLand.dll");
}
public native void displayHeyLand();
public static void main (String[] args) {
Test1 t = new Test1();
t.displayHeyLand();
}
}
After compiling, attempting to run D:\Test1.classresults in the following:
D:\>java Test1.class
Exception in thread "main" java.lang.NoClassDefFoundError: Test1.class
Caused by: java.lang.ClassNotFoundException: Test1.class
at java.net.URLClassLoader.findClass(URLClassLoader.java:434)
at java.lang.ClassLoader.loadClass(ClassLoader.java:660)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:358)
at java.lang.ClassLoader.loadClass(ClassLoader.java:626)
Could not find the main class: Test1.class. Program will exit.
Why I am stumped :
1. I have set my classpath to be D:\, so I believe my class definition would be in the classpath, and I do not see how my compile-time and run-time classpaths could be any different.
2. I don't see how this could have anything to do with static initialization, and I believe the exception would look different.
Perhaps I'm just missing something incredibly simple, I am very newbie with Java.
Any help is greatly appreciated!
The classpath environmental variable is taking precedence over that in the java run command. You need to specify the class location (as well as removing the .class file extension)
java -cp . Test1
Java normal syntax for executing class file is
Java [<options>....} <class-name> [<arguments>....]
For example
java com.package.name.Test1
here how compiler works
1. Compiler search for complete class name
2. Load that class
3. check for main method - in the same class
4. Call main method with passed arguments in command line string.
Now following are the possibilities why your class may not found main method.
1 - forgot to include package name
I am new developer in java but I found when I run application using eclips or intellJ editor it gives different path and package name and execute code as I noticed it on command line edior. So make sure you are including package name
For example:
java com.package.name.Test1 instead of
java Test1
2. File name or pathname rather then class name
As I noticed output file is in different location. That why class file path was different.
java Test1.class
java com/package/name/Test1.class
3. Typo
also I noticed you are using
static {
//System.loadLibrary("HeyLand");
System.load("D://HeyLand.dll");
}
Is this function ? or constructor? If it is function then where is name of the function? You cant write code without any reference in classs

java relative path vs absolute path on command line

Running into an interesting problem
When I run:
$cd /projects/MyProject/
$java -cp . S3Sample
This works fine. However if I run:
$java -cp /projects/MyProject /projects/MyProject/S3Sample
Error: Could not find or load main class .projects.MyProject.S3Sample
Why is that. Did a quick look and can't find the answer. Thanks!
I have this folder structure:
- home
- org
- test
+ Foo.java
+ Foo.class
And the code in Foo.java is a simple hello world application:
//Note the usage of the package statement here.
package org.test;
public class Foo {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
Then, in command line, in order to execute Foo.class, I should provide the complete name of the class (I'm in "/home" folder in cmd):
$ java -cp "org/test;." Foo
Exception in thread "main" java.lang.NoClassDefFoundError: Foo (wrong name: org/test/Foo)
$ java -cp "org/test;." org.test.Foo
Hello world
Now, I edit the class above and remove the package sentence:
//no package specified
public class Foo {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
After recompiling the class and executing the same command lines:
$ java -cp "org/test;." Foo
Hello world
$ java -cp "org/test;." org.test.Foo
Exception in thread "main" java.lang.NoClassDefFoundError: org/test/Foo (wrong name: Foo)
TL;DR
Make sure to always specify the full name of the class. Check if your class belongs to a package. Specifying the path of the class to execute is the same as writing the full name of the class, java program will replace / by ..
You should run
$ java -cp /projects/MyProject S3Sample
The path for class is already CLASSPATH-relative
With java, you specify the fully qualified name of a class containing the main method you want executed. (The launcher will replace / with .). This class needs to be in the classpath. The argument is not a path to a file.

'Exception in thread "main" java.lang.NoClassDefFoundError' when running java program from command line

What am I doing wrong here:
class Helo {
// main: generate some simple output
public static void main (String[] args) {
System.out.println ("Hello, world."); // print one line
System.out.println ("How are you?"); // print another
}
}
When I go into terminal I do:
cd ~
javac Atempt2.java (//that's the file name)
java Atempt2
and then it gives me this error message:
Exception in thread "main" java.lang.NoClassDefFoundError: Atempt2
So all in all this is what I do and what happens:
david-allenders-macbook-pro:~ davidallender$ cd ~
david-allenders-macbook-pro:~ davidallender$ javac Atempt2.java
david-allenders-macbook-pro:~ davidallender$ java Atempt2
Exception in thread "main" java.lang.NoClassDefFoundError: Atempt2
david-allenders-macbook-pro:~ davidallender$
I am very new at this so please explain things in a very simple manner.
Thanks.
Its been awhile since I've done any java work but I'm pretty sure your class name needs to match your file name.
javac uses the class name to generate the output not the filename.
So it will generate a Helo.class classfile.
java will take a class name and call the main function in the corresponding class file, here Hello.class.
The ClassNotFoundError is thrown because javac never generated an Atemp2 classfile as there is no Atemp2 class in your source file.
Rename your Atempt2.java to Hello.java to get going, then:
javac Helo.java
java Helo
See here for more discussion and the reasoning.
change:
class Helo
to
class Atempt2
in your source file.
A .java file that declares a class must have the file name match the declared class name.
The filename must match the name of the public class defined in the file. In this case, you would either have to name the file "Helo.java" or renamed the class to Atempt2.
This is the very basic to start with java programming.Any program you write the name of the file must match with the public class of the program.
Here in your program public class of the file is Helo so your file name must be Helo.java.Here the compiler is able to compile but JVM will search for Helo.class file to run. As there is no Helo.class file you are getting runtime Exception Exception in thread "main" java.lang.NoClassDefFoundError: Atempt2
to complement josefx's answer.
The argument to the compiler (javac) is the name of the file or files to compile (as you did).
On the other side, the virtual machine (java) gets the name of the class whose main method is to be executed.
One option would be
javac Atempt2.java // the file name
java Helo // the class name
Normally it is a good idea to have the file named the same way as the class. For public class this is a must (checked by compiler).

Java Command Line Trouble with Reading a Class from a Jar Archive

I am trying to run a java based tool using a command line syntax as the following: java -cp archive.jar archiveFolder.theMainClassName.Although the class I am searching for, a main class, "theMainClassName" is in the archive.jar and in the archiveFolder given at input, I keep getting the error that my class is not seen. Does anybody have any ideas concerning this problem? Thank you in advance
Here's a concrete example of what does work, so you can compare your own situation.
Take this code and put it anywhere, in a file called MainClass.java. (I've assumed a directory called src later. Normally you'd arrange the source to match the package, of course.)
package archiveFolder;
public class MainClass
{
public static void main(String[] args)
{
System.out.println("I'm MainClass");
}
}
Then run each of these commands:
# Compile the source
javac -d . src/MainClass.java
# Build the jar file
jar cf archive.jar archiveFolder
# Remove the unpackaged binary, to prove it's not being used
rm -rf archiveFolder # Or rmdir /s /q archiveFolder on Windows
# Execute the class
java -cp archive.jar achiveFolder.MainClass
The result:
I'm MainClass
How are you building your jar file? Is the code in the appropriate package?
Does theMainClassName class have the following package line at the top:
package archiveFolder
You need the class file to be in the same directory structure as the declared package. So if you had something like:
org/jc/tests/TestClass.class
its source file would have to look like this:
package org.jc.tests;
public class TestClass {
public static void main(String[] args) {
System.out.printf("This is a test class!\n");
}
}
Then you could use the following to create the jar file and run it from the command line (assuming the current directory is at the top level, just above org):
$ jar -cf testJar.jar org/jc/tests/*.class
$ java -cp testJar.jar org.jc.tests.TestClass
Perhaps with java -jar archive.jar?
Of course, it supposes the manifest points to the right class...
You should give the exact message you got, it might shed more light.
EDIT: See Working with Manifest Files: The Basics for information on setting the application entry point (Main class) in your jar manifest file.
Usually this happens when a dependent class (static member) is not found - like this, using log4j:
public class MyClass {
private static Logger log = Logger.getLogger("com.example");
}
The reason is that the initialization of such a static member can be understood as part of the class loading - errors causing the class not to be available (loadable), resulting in the error you described.
Static constructors are another possible reason:
public class MyClass {
static {
// <b>any</b> error caused here will cause the class to
// not be loaded. Demonstrating with stupid typecast.
Object o = new String();
Integer i = (Integer) o;
}
}
I think others have covered some common stuff here. I'd jar tf the jar and make sure the class is listed. I'd also double-check that the class is public and the method is "public static void main(String[] arg)".

Categories

Resources