running java from command line - java

I have been mostly using eclipse so far. Now I'm trying to run java from terminal but I have a problem with packages.
This is my Main.java file:
package main;
class Main {
public static void main(String[] args) {
System.out.println("it's working");
}
}
I compile this using javac Main.java and then run with java Main which gives me:
java Main
Exception in thread "main" java.lang.NoClassDefFoundError: Main
Caused by: java.lang.ClassNotFoundException: Main
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: Main. Program will exit.
When I remove package Main everything works fine. What am I missing?
java -version gives:
java version "1.6.0_24"
OpenJDK Runtime Environment (IcedTea6 1.11.4) (6b24-1.11.4-1ubuntu0.12.04.1)
OpenJDK 64-Bit Server VM (build 20.0-b12, mixed mode)

You need to run the java command up one directory level and give it in the fully qualified package name, eg: java main.Main
See How the Java Launcher Finds User Classes to learn how this works.

You can use this command:
java main.Main
Make sure the main (lowercase) package directory is on the classpath.

It is possible that your classpath is not set correctly.
Since you gave your .java file a package it is unnamed no longer.
An example:
java -cp ./package1/ main.Main //from the current directory and
//if main package is contained in package1
You need to fully qualify the class name.
For future reference if you want to run from the command line you must stop the indirection (for lack of a better term) at the package level.
Say your class was in the package package1.package2.Main.java
I would run it like so java -cp /blah/blah package1.package2.Main

Compile
Windows:
javac main\Main.java
Mac:
javac main/Main.java
Run
java main.Main

If you add package Main, then you must put your source file in folder Main/Main.java. After that you can compile. When you run the program, go to Main folder using "cd", then write java -cp Main.Main
See my question similiar to yours noclassdeffounderror

try this...
In window , you just compile the code as
javac - d . Main.java
then a package(folder) with the name you specified in your class is created (in your code, package with name "main" is created) in the same path where your program reside...
Then you just run the program as
java main.Main
or
java main/Main

Related

'java class name' command not working, is there any change in recent version?

If I remember correctly
javac filename.java -> compile and generates classname.class(es)
java classname without .class extension
But when I try java filename.java executes successfully while java classname command gives the following error ,
Error: Could not find or load main class HelloWorld
Caused by: java.lang.ClassNotFoundException: HelloWorld
java -version
openjdk version "11" 2018-09-25
OpenJDK Runtime Environment 18.9 (build 11+28)
OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)
HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" in the terminal window.
System.out.println("Hello, World");
}
}
javap HelloWorld.class is giving below output
Compiled from "HelloWorld.java"
public class HelloWorld {
public HelloWorld();
public static void main(java.lang.String[]);
}
java HelloWorld.java -> executes fine, no class file generated.
java HelloWorld -> didn't execute.
Any idea why the program is behaving like this?
After some help from some stackoverflow veterans in the comment section I was able to understand what went wrong.
The latest version of Java have introduced launching single file source code directly using Java command.
from oracle docs.
To launch a single source-file program:
java [options] source-file [args ...]
To run Helloworld.java, you can directly call execute java Helloworld.java it will execute the java program and gives output without generating .class file in the current directory.
Why old way of running java class file didn't work for me?
I had a class path variable 'CLASSPATH' in my environment, so when I execute java HelloWorld it is not looking for class in current directory. Give java -cp . to explicitly give current directory to classpath.
java -cp . HelloWorld
Credits: Jon Skeet,Joachim Sauer, rzwitserloot

Java Swing Program is not running on command prompt

My java swing code compiled successfully but its not executing from cmd
package swing_1;
public class JavaCalculator implements ActionListener{
the above class contains the main method
when i'm compiling there's no error showing javac JavaCalculator.java
but when I trying to execute javac JavaCalculator.java
its showing
Error: Could not find or load main class JavaCalculator
Caused by: java.lang.NoClassDefFoundError: swing_1/JavaCalculator (wrong name: JavaCalculator)
Its seems you are missing a manifest. Try calling it this way:
java -cp MyJar.jar com.mycomp.myproj.dir2.MainClass2
where the latter part is the location of your Class that contains the main method
That is because you should compile in the directory where the subdirectory swing_1 resides:
javac swing_1/JavaCalculator.java
java -cp . swing_1/JavaCalculator.class
Start with an IDE like NetBeans or IntelliJ (community) or eclipse.

Java run problems from terminal

I'm using a cloud VM in which Ubuntu is installed. Java version installed is:
java version "1.8.0_66"
Java(TM) SE Runtime Environment (build 1.8.0_66-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.66-b17, mixed mode)
I've never used terminal to compile and run programs. However, this program works using Eclipse.
I have to use two jars when I compile my java program: disco-2.1.jar and sqlite-jdbc-3.8.11.2.jar. The terminal command I use is:
javac -cp '/home/ubuntu/workspace/sem/*' USem.java
Using /home/ubuntu/workspace/sem/* adds disco and sqlite jars to the classpath.
This creates my USem.class file in sem directory, without errors. Those jars are contained in sem directory.
USem.java contains this part of code, starting from the beginning:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.lucene.index.CorruptIndexException;
import de.linguatools.disco.CorruptConfigFileException;
import de.linguatools.disco.DISCO;
import de.linguatools.disco.TextSimilarity;
import de.linguatools.disco.DISCO.SimilarityMeasure;
public class USem {
//irrelevant code here
public static void main(String[] args) throws IOException, CorruptConfigFileException, SQLException{
The problem starts when I run this in the terminal:
java USem
The terminal shows me:
Error: A JNI error has occurred, please check your installation and
try again Exception in thread "main" java.lang.NoClassDefFoundError:
de/linguatools/disco/CorruptConfigFileException
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException:
de.linguatools.disco.CorruptConfigFileException
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
I think there's a problem with disco-2.1.jar. I checked the jar classes contained in it and everything was ok.
My workspace is organized like so:
home/ubuntu/workspace/sem
In the sem directory I have my .java file and the .jar files are added there.
What am I doing wrong? I tried uninstalling JDK and reinstalling it, changing the terminal folder in which I run commands, but nothing changed.
--Update--
Now I wrote
java -cp '/home/ubuntu/workspace/sem/*' USem
However, I obtained
Error: Could not find or load main class USem
Add Disco jar (or any other required jar for that matter) to classpath while executing java command
java -cp "Whatever.jar" my.package.MainClass
The default classpath when there's no -classpath argument and no CLASSPATH environment variable is .. Now when your class file is in your working directory and you call java USem, Java finds your class but not the classes in the other jar files because these are not in the classpath.
When you add -cp '/home/ubuntu/workspace/sem/*' Java will find the classes in the jar files. But this also overrides the default classpath, so . is no more in there, therefore Java doesn't find your own class anymore. You need to explicitly add . (or /home/ubuntu/workspace/sem) again: -cp '.:/home/ubuntu/workspace/sem/*'
All your comments were useful. I'd like to post my solution.
I declared CLASSPATH environment
export CLASSPATH=/home/ubuntu/workspace/sem/disco-2.1.jar:**other paths for other external jars**:.
I moved into workspace and compiled .class file
javac -cp 'sem/*' sem/USem.java
Then I moved into sem and run
java USem
and worked.
move all the required jars in thejre/lib/ext folder and simply run the command
java filename
worked for me!

java error: Exception in thread "main" java.lang.NoClassDefFoundError

I am a beginner in java and taking the course Algorithm, which is provided by Princeton. In the course, professor asked us to download algs4.jar to a folder and add algs4.jar to the classpath.[1]
I followed it step by step, and try to program a HelloWorld like
import edu.princeton.cs.algs4.StdOut;
public class HelloWorld {
public static void main(String args[]) {
StdOut.print("Hello World!");
}
}
However when I compile the file, console reminds me that
NPP_EXEC: "java_Compile_Run"
NPP_SAVE: G:\java\helloworld\HelloWorld.java
javac -encoding UTF-8 "G:\java\helloworld\HelloWorld.java"
Process started >>>
<<< Process finished. (Exit code 0)
==========编译成功后开始运行==========
java -cp "G:\java\helloworld" "HelloWorld"
Process started >>>
Exception in thread "main" java.lang.NoClassDefFoundError:
edu/princeton/cs/algs4/StdOut
at HelloWorld.main(HelloWorld.java:5)
Caused by: java.lang.ClassNotFoundException: edu.princeton.cs.algs4.StdOut
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
<<< Process finished. (Exit code 1)
================ READY ================
I have checked my classpath, and my programming file. What does this error mean? And how can I fix it?
Any advice is helpful. Thank you.
[1] http://algs4.cs.princeton.edu/code/
If you're referring to a jar file that should be on the classpath, you must name it explicitly. E.g.
java -cp "G:/java/helloworld;G:/whereever/algs4j.jar" HelloWorld
Do they really provide another name for System.out? In this case you can also safely ignore that jar by using System.out instead of StdOut
According to the instructions of this course you should use javac-algs4 to compile and java-algs4 to execute if you imported their library.
If you want to know the differences between these two commands and original commands javac and java, you could
use type command to find where is this command is
use cat or vim to see what's the content of this command
You can see that java-algs4 added -cp parameter to original java command just as Olaf Kock said.
You'll have to probably use -cp flag to set the class path to include the package.
While using the -cp flag, don't forget to include the current working directory using .
So, something like javac -cp thejar.jar:. should work in linux or javac -cp thejar.jar;. should work for windows
For Mac, using M1, cd in your folder:
javac -classpath ".:./algs4.jar" HelloWorld.java
java -classpath ".:./algs4.jar" HelloWorld
I just included a classpath argument in both javac and java commands like so:
javac -classpath ".;drive\path\to\algs4.jar" Hello.java
and
java -classpath ".;drive\path\to\algs4.jar" Hello
Also if you are manually adding the CLASSPATH environment variable, then remember to close and restart the cmd console.
You imported class StdOut in your java code (import edu.princeton.cs.algs4.StdOut;), you have to tell java how stdOut implement
Accroding to the link you provided (http://algs4.cs.princeton.edu/code/). You have to follow the "Installing the textbook libraries." section to install this lib first.

Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld

I've been working on this for about an hour and thumbing through Q&As on stackoverflow but I haven't found a proposed solution to my problem. I'm sorry if this is a duplicate, but I couldn't find any duplicate question with an answer that solved my specific problem.
I am trying to write and compile a java program from terminal for the first time (up until this point I have been using Eclipse for java and VIM for everything else, but I feel its time to switch entirely to VIM). Here is my current HelloWorld code:
package main;
public class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello World!");
}
}
I compile and run using the following commands (specifying the classpath to ensure that isn't the problem):
javac -cp "./" HelloWorld.java
java -cp "./" HelloWorld
This gives me the following error message:
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong name: main/HelloWorld)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:480)
I know it is seeing the file HelloWorld.class and trying to access the class HelloWorld because if I change the run command to:
java -cp "./" Foo
I get an entirely different error message:
Error: Could not find or load main class Foo
I have tried several dozen pages worth of troubleshooting and come up short, including the following:
Exception in thread "main" java.lang.NoSuchMethodError: main
http://introcs.cs.princeton.edu/java/15inout/mac-cmd.html
java -version yields:
java version "1.7.0_07"
Java(TM) SE Runtime Environment (build 1.7.0_07-b10)
Java HotSpot(TM) Client VM (build 23.3-b01, mixed mode)
My operating system is LinuxMint and uname -a yields:
Linux will-Latitude-D620 2.6.38-8-generic #42-Ubuntu SMP Mon Apr 11 03:31:50 UTC 2011 i686 i686 i386 GNU/Linux
package main;
This means that your class resides in the main package, and its canonical name is main.HelloWorld.
Java requires that package names should also be mirrored in the directory structure. This means that:
Your HelloWorld.java file should be in a directory named main
You should execute javac and java from the directory containing main, not from main itself
The classpath should contain the directory where the main directory is, not main itself
java expects the canonical name of the class to execute, so main.HelloWorld
So, to recap:
You should have something like myproject/main/HelloWorld.java
From myproject, run javac main/HelloWorld.java
From myproject, run java -cp ./ main.HelloWorld
You've put your class in a package named "main", but you're trying to treat it like it isn't in a package. Since you put package main; at the top of your source file, you need to put HelloWorld.java in ./main, then run javac ./main/HelloWorld.java, followed by java -cp . main.HelloWorld.
These commands will get you the working example you're trying to build:
mkdir main
echo 'package main; public class HelloWorld { public static void main(String... args) { System.out.println("Hello World"); } }' > main/HelloWorld.java
javac main/HelloWorld.java
java -cp . main.HelloWorld
As a beginner you might encounter a very similar scenario where the error output is the same. You try to compile and run your simple program(without having any package set) and you do this:
javac HelloWorld.java
java HelloWorld.class
This will give you the same java.lang.NoClassDefFoundError since java thinks HelloWorld is your package and class your class name. To solve it just use
javac HelloWorld.java
java HelloWorld
See the Java page - Lesson: Common Problems (and Their Solutions)
Problem:
Basically, the Exception in thread "main" java.lang.NoClassDefFoundError:
means, that the class which you are trying to run was not found in the classpath.
Solution: you need to add the class or .jar file which contains this class into the java classpath. When you are running a java class from the command line, you need to add the dot (.)
java YourSingleClass -cp .
into the classpath which tells the JVM to search for classes in actual directory.
If you are running a class from a .jar file, you need to add this jar file into the classpath:
java org.somepackage.SomeClass -cp myJarWithSomeClass.jar

Categories