How do I run Java .class files? - java

I've compiled a HelloWorld program, and I'm using the command prompt to run it. The .class file is named HelloWorld2.class
The file is located in C:\Users\Matt\workspace\HelloWorld2\bin
Here's what I'm getting when I go to command prompt, and type "Java HelloWorld2" :
C:\Users\Matt>Java HelloWorld2
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld2
Caused by: java.lang.ClassNotFoundException: HelloWorld2
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)
Could not find the main class: HelloWorld2. Program will exit.
I was expecting to see a HelloWorld printed out. What am I doing wrong? I have the JDK installed.

If your class does not have a package, you only need to set the classpath to find your compiled class:
java -cp C:\Users\Matt\workspace\HelloWorld2\bin HelloWorld2
If your class has a package, then it needs to be in a directory corresponding to the package name, and the classpath must be set to the root of the directory tree that represents the package.
// Source file HelloWorld2/src/com/example/HelloWorld2.java
package com.example;
...
Compiled class file: HelloWorld2/bin/com/example/HelloWorld2.class
$ java -cp HelloWorld2/bin com.example.HelloWorld2

To run Java class file from the command line, the syntax is:
java -classpath /path/to/jars <packageName>.<MainClassName>
where packageName (usually starts with either com or org) is the folder name where your class file is present.
For example if your main class name is App and Java package name of your app is com.foo.app, then your class file needs to be in com/foo/app folder (separate folder for each dot), so you run your app as:
$ java com.foo.app.App
Note: $ is indicating shell prompt, ignore it when typing
If your class doesn't have any package name defined, simply run as: java App.
If you've any other jar dependencies, make sure you specified your classpath parameter either with -cp/-classpath or using CLASSPATH variable which points to the folder with your jar/war/ear/zip/class files. So on Linux you can prefix the command with: CLASSPATH=/path/to/jars, on Windows you need to add the folder into system variable. If not set, the user class path consists of the current directory (.).
Practical example
Given we've created sample project using Maven as:
$ mvn archetype:generate -DgroupId=com.foo.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
and we've compiled our project by mvn compile in our my-app/ dir, it'll generate our class file is in target/classes/com/foo/app/App.class.
To run it, we can either specify class path via -cp or going to it directly, check examples below:
$ find . -name "*.class"
./target/classes/com/foo/app/App.class
$ CLASSPATH=target/classes/ java com.foo.app.App
Hello World!
$ java -cp target/classes com.foo.app.App
Hello World!
$ java -classpath .:/path/to/other-jars:target/classes com.foo.app.App
Hello World!
$ cd target/classes && java com.foo.app.App
Hello World!
To double check your class and package name, you can use Java class file disassembler tool, e.g.:
$ javap target/classes/com/foo/app/App.class
Compiled from "App.java"
public class com.foo.app.App {
public com.foo.app.App();
public static void main(java.lang.String[]);
}
Note: javap won't work if the compiled file has been obfuscated.

This can mean a lot of things, but the most common one is that the class contained in the file doesn't have the same name as the file itself. So, check if your class is also called HelloWorld2.

Go to the path where you saved the java file you want to compile.
Replace path by typing cmd and press enter.
Command Prompt Directory will pop up containing the path file like C:/blah/blah/foldercontainJava
Enter javac javafile.java
Press Enter. It will automatically generate java class file

Related

Unable to compile using Picocli

I'm a dev student
I would love to use Picocli in my project, unfortunately I doesn't understand how to compile using Picocli
I trie to follow the instruction given here https://picocli.info/ or here https://picocli.info/quick-guide.html but the step to compile aren't detailed. I'm not using Gradle nor Maven but they aren't really listed as required.
This is how it tried to compile the Checksum example given in the picocli.info webpage :
jar cf checksum.jar Checksum.java ; jar cf picocli-4.6.1.jar CommandLine.java && echo "hello" > hello
Then I simply copy paste this gived command : https://picocli.info/#_running_the_application
java -cp "picocli-4.6.1.jar:checksum.jar" CheckSum --algorithm SHA-1 hello
And get the following result :
Error: Could not find or load main class CheckSum
Caused by: java.lang.ClassNotFoundException: CheckSum
I tried to compile everything myself and then add the .jar like this :
java CheckSum -jar picocli-4.6.1.jar
But then the error output looks like this:
Exception in thread "main" java.lang.NoClassDefFoundError: picocli/CommandLine
at CheckSum.main(Checksum.java:33)
Caused by: java.lang.ClassNotFoundException: picocli.CommandLine
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 1 more
Witch I don't understand since I added the dependency.
What am I missing ?
Thanks in advance
The problem is that the command jar cf checksum.jar Checksum.java only creates a jar file (jar files are very similar to zip files) that contains the Checksum.java source file.
What you want to do instead is compile the source code first. After that, we can put the resulting Checksum.class file (note the .class extension instead of the .java extension) in the checksum.jar. The Java SDK includes the javac tool that can be used to compile the source code. Detailed steps follow below.
First, open a terminal window and navigate to a directory that contains both the Checksum.java source file and the picocli-4.6.1.jar library.
Now, the command to compile (on Windows) is:
javac -cp .;picocli-4.6.1.jar Checksum.java
Linux uses : as path separator instead of ;, so on Linux, the command to compile is:
javac -cp .:picocli-4.6.1.jar Checksum.java
The -cp option allows you to specify the classpath, which should contain the directories and jar/zip files containing any other class files that your project uses/depends on. Since Checksum.java uses the picocli classes, we put the picocli jar in the classpath. Also add the current directory . to the classpath when the current directory contains any classes. I just add . habitually now.
Now, if you list the files in the current directory, you should see that a file Checksum.class has been created in this directory.
Our Checksum class has a main method, so we can now run the program with the java tool:
On Windows:
java -cp .;picocli-4.6.1.jar Checksum
On Linux:
java -cp .:picocli-4.6.1.jar Checksum
Note that when running the program with java you specify the class name Checksum, not the file name Checksum.class.
You can pass arguments to the Checksum program by passing them on the command line immediately following the class name:
java -cp .:picocli-4.6.1.jar Checksum --algorithm=SHA-1 /path/to/hello
When your project grows, you may want to keep the source code and the compiled class files in separate directories. The javac compile utility has a -d option where you can specify the destination for the compiled class files. For example:
javac -cp picocli-4.6.1.jar:otherlib.jar -d /destination/path /path/to/source/*.java
This should generate .class files for the specified source files in the specified destination directory (/destination/path in the example above).
When you have many class files, you may want to bundle them in a single jar file. You can use the jar command for that. I often use the options -v (verbose) -c (create) -f (jar file name) when creating a jar for the compiled class files. For example:
jar -cvf MyJar.jar /destination/path/*.class /destination/path2/*.class
Enjoy!

java able to compile but unable to find class error with cmd

Hello so recently I have started to transfer from c++ to java and one exercise is to compile and run a java program using cmd.
So okay, I coded my simple HelloWorld program using netbeans and saved it,
package helloworld;
public class Helloworld
{
public static void main(String[] args)
{
System.out.println("Hello world");
}
}
so now my saved .java file is in C:\Users\eatmybuns\Documents\NetBeansProjects\Helloworld\src\helloworld
now I open the cmd and I change the directory to the above and typed
javac Helloworld.java
and now I can see Helloworld.class in the same folder, I read from somewhere that I have to include the package name as well for it to run so I typed
java helloworld.Helloworld
it gave me an error so I tried running it from the src folder instead but it also gave me the same error.
Error: Could not find or load main class Helloworld
Caused by: java.lang.ClassNotFoundException: Helloworld
I have read some possible solutions such as using -cp or using -d but it keeps giving me the same error. I am currently using jdk1.8.0_161. on windows 10.
You have to use
java helloworld.Helloworld
and from the parentfolder of helloworld, which is the src directory, in your case.
There is a tight relationship between package and directory structure.
There are many flags you can set for the compiler, like srcdir, targetdir to keep classes and sources apart. But basically, when you invoke your class helloworld.Helloworld, the JVM looks for a directory helloworld/ and expects a Helloworld.class there.
To achive this without compiler flags, you have to put the source into the helloworld/ folder too.
The whole name of your class is helloworld.Helloworld and java should look there and find it there.
mkdir helloworld
mv Helloworld.java helloworld/
javac helloworld/Helloworld.java
java helloworld.Helloworld
Hello world
It's a bit surprising in the beginning, if you don't know it and started with classes without package declaration. But the logic is simple and straight forward: Every package is reflected by the directory structure.
With a distinction of sourcedir and targetdir, the directory structure below has to be the same as without, just the starting point differs. Common target dirs are classes or bin, like in:
javac -s . helloworld/Helloworld.java -d classes
or
javac -s ./src helloworld/Helloworld.java -d bin
But bin or classes don't get part of the package name, and you can't extend the invocation of the class by prepending that dir to the invocation path:
java bin.helloworld.Helloworld
won't work. But
java -cp ./bin helloworld.Helloworld
should. If you read the documentation carefully, you will find, that it carefully distinguishes source file (Helloworld.java), class (Helloworld) and file (Helloworld.class).

Eclipse compiled files are not runnable by java command

When you write a simple Java Application in Eclipse in automatically compiles those files and stores them in the bin/ folder of the root folder of the project.
Now if I navigate to the /bin folder and to the folder that contains the .class file I want to run via the java command below I am getting the following error - :
java A
Error: Could not find or load main class A
Class A:
package assurance;
public class A {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
While the class A has a main method and runs fine when I right click on the file and do a Run As Java Application. But it does not run from the command like java command.
Why is this happening ?
Update:
Tried with the following commands-:
java -cp "A.class" assurance.A
java -cp "A" assurance.A
java -cp "*" assurance.A
It works in Eclipse, because Eclipse just runs it with correct -cp and correct command :)
Run your code with the following command:
java -cp "./" assurance.A ("" for some odd cmd interpreters like Windows XP)
it is important that the command is run from the "default package" directory (top-level package directory).
Java interprets package name (assurance) as directory path to the class file. Imagine if it replaces . with / and adds .class extension
(assurance.A => ./assurance/A.class)
More details here: http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html

Run from command line, Wrong Name error

I want to run a Java project from the command line which I start using a batch file, but I get the wrong name error.
The directory setup:
srcMVC
bin (folder with .class files)
src (folder with .java files)
Batch file
Batch file:
set path=C:\Program Files\Java\jdk1.7.0_09\bin
javac src\model\*.java -d bin -cp src
javac src\controller\*.java -d bin -cp src
javac src\view\*.java -d bin -cp src
javac src\main\*.java -d bin -cp src
PAUSE
java bin\main.Main
PAUSE
Compiling works, but I get the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: bin\main/Main (wrong name: main/Main)
Any suggestions?
package main;
// omitted imports
public class Main {
// omitted variables
public static void main(String[] args) {
// omitted implementation
}
}
The following statement resolved my error:
java -cp bin; main.Main
NoClassDefFoundError in Java comes when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time.
For example if we have a method call from a class or accessing any static member of a Class and that class is not available during run-time then JVM will throw NoClassDefFoundError.
By default Java CLASSPATH points to current directory denoted by "." and it will look for any class only in current directory.
So, You need to add other paths to CLASSPATH at run time. Read more Setting the classpath
java -cp bin main.Main
where Main.class contains public static void main(String []arg)
you are wrongly exicuting java bin\main.main
main() is your main method but you should supply java interpreter the Class Name which implements main()
So if your class name is Test and file name is Test.java which has main() method
java Test
if your Test.java/Test class in is package my.test e.g - package com.my.test;
than, java com.my.test.Test
hope you got it !!
java bin/main.Main is wrong, you must specify -cp here:
java main.Main -cp bin
Here the first argument is the class name which should be found in the classpaths, rather than the class file location. And -cp just adds the logical path to classpaths. You should make the root of your project searchable in the classpath.
and for those javac commands, you have already specified the correct path, so you don't need -cp src. The difference here is the javac command uses logical path for .java files, while using java command you could only specify the path in -cp attribute.
You could also execute java main.Main without -cp if you enter the directory bin:
cd bin
java main.Main
Since the current path will be automatically be searched by java as a classpath.
Assuming you have a class called Main you have to run it with this command:
java bin\Main
It will call your main method.
Java run time (in your case the java.exe command), takes the class file name that containst the main() method as input. I guess you should be invoking it as "java bin\main" assuming there is a main.class which has a public static void main (String[]) method defined.
Note: General practice is to capitalize the first literal of any class name.

How to run Java program in terminal with external library JAR

This should be simple but I have never done it before and didn't find any solution.
I am currently using Eclipse to code my program, which imports some external JAR library such as google data api library. I can use Eclipse to compile/build/run the program.
But now I want to run it in terminal, so where should I put those JAR files, and how to build and run the program?
Thanks!
You can do :
1) javac -cp /path/to/jar/file Myprogram.java
2) java -cp .:/path/to/jar/file Myprogram
So, lets suppose your current working directory in terminal is src/Report/
javac -cp src/external/myfile.jar Reporter.java
java -cp .:src/external/myfile.jar Reporter
Take a look here to setup Classpath
For compiling the java file having dependency on a jar
javac -cp path_of_the_jar/jarName.jar className.java
For executing the class file
java -cp .;path_of_the_jar/jarName.jar className
you can set your classpath in the in the environment variabl CLASSPATH.
in linux, you can add like
CLASSPATH=.:/full/path/to/the/Jars, for example ..........src/external
and just run in side ......src/Report/
Javac Reporter.java
java Reporter
Similarily, you can set it in windows environment variables.
for example, in Win7
Right click Start-->Computer
then Properties-->Advanced System Setting --> Advanced -->Environment Variables
in the user variables, click classPath, and Edit and add the full path of jars at the end.
voila
Suppose your jar application "myapp.jar" has the following code snippet written inside it.
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
// write your code here
System.out.println("Hello World!");
JSONObject jo = new JSONObject("{ \"abc\" : \"def\" }");
System.out.println(jo.toString());
}
}
It is using the external library json.jar from which we imported "org.json.JSONObject".
Running the following command will result in an error.
java -jar myapp.jar
Exception message:
Exception in thread "main" java.lang.NoClassDefFoundError: org/json/JSONObject at com.reve.Main.main(Main.java:10)
Caused by: java.lang.ClassNotFoundException: org.json.JSONObject 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)
... 1 more
We must include the json.jar file while running the jar file. We have to specify the class path of the file before building our myapp.jar file.
Inside META-INF/MANIFEST.MF file:
Manifest-Version: 1.0
Class-Path: lib/json.jar lib/example2.jar
Main-Class: com.reve.Main
Specify the external libraries separated by spaces under the Class-Path keyword. Then after building the project and the artifact, we can run the jar file by simply writing the same command we discussed above.

Categories