Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running java class from terminal

Tags:

java

terminal

This question has been asked before but I still cannot figure whats wrong for some reason. I got a class named NewClass in package syntaxtest in file src. From src path I type :

javac src/syntaxtest/NewClass.java

and the class is compiled and I can see NewClass.class in syntaxtest folder. Now from that same path or even the same folder with NewClass.class, I can't figure out how to run the class from terminal. I have made many different attempts but ether I get

ClassDefNotFound or ClassDefNotFound (wrong name : syntaxtest/NewClass)

like image 973
Giannis Avatar asked Aug 09 '26 11:08

Giannis


2 Answers

Try "java -cp src syntaxtest.NewClass".

That is, if you have a folder "src" which contains the subfolder (package) "syntaxtest" and the class "NewClass" is in "package syntaxtest", then the above command will work.

$ ls src/syntaxtest
NewClass.java
$ cat src/syntaxtest/NewClass.java
package syntaxtest;
public class NewClass {
  public static void main(String args[]) {
    System.out.println("Hello, World!");
  }
}
$ javac src/syntaxtest/NewClass.java
$ java -cp src syntaxtest.NewClass
Hello, World!
like image 68
maerics Avatar answered Aug 11 '26 01:08

maerics


I've made the following test:

  • Created a java file in home/test/blah/TestClass.java

    package blah;

    public class TestClass { public static void main(String[] args) { System.out.println("Hello World!"); } }

  • Went to directory home/test/

  • Compiled the file by typing:
javac blah/TestClass.java
  • Got the file compiled ok.
  • Ran it by typing:
java blah.TestClass
  • Got the message "Hello World!" as expected: program runs ok.
  • Went to directory home/
  • Tried to run by typing:

java test/blah.TestClass

  • ... and many other combinations of slashes and dots..... nothing worked.... keep getting the same Exception as you:
java.lang.NoClassDefFoundError

So it seems to me that to run a Java class using the command 'java' you really must be in the application's root folder.

like image 31
Renato Avatar answered Aug 11 '26 00:08

Renato