0

I tried to run my java class generated using netbeans 10.0 in terminal as below:

 ~/Desktop/JavaLesson5/build/classes/javalesson5$ java javalesson5.JavaLesson5

but I keep getting the error below:

Error: Could not find or load main class javalesson5.JavaLesson5
Caused by: java.lang.ClassNotFoundException: javalesson5.JavaLesson5

My java code is as below:

package javalesson5;
import java.util.*;
import java.io.*;

public class JavaLesson5{

    public static double myPI = 3.14159; //Class variable

    public static int addThem(int a, int b){
      double smallPI = 3.140;//Local variable
      System.out.println("Local "+myPI);

      int c = a + b;
      return c;
    }


    public static void main(String[] args) {
      System.out.println(addThem(1,2));
    }

}

1 Answers1

0

Try:

java -cp ~/Desktop/JavaLesson5/build/classes javalesson5.JavaLesson5

You use classes as the classpath because you've specified javalesson5 as part of the classname. For each directory in the classpath (just one in this example) Java will look for a directory called javalesson5 and then look for the JavaLesson5 class in that directory.

Willis Blackburn
  • 8,068
  • 19
  • 36
  • I had earlier tried it in its folder but it had still failed. Does that mean that the approach of java javalesson5.JavaLesson5 is totally wrong and should not be used? –  Feb 23 '19 at 04:09
  • 1
    You always have to set the classpath either by specifying `-cp` or setting the environment variable `CLASSPATH`. If you set `CLASSPATH` to `~/Desktop/JavaLesson5/build/classes` then you can run `java javalesson5.JavaLesson5` without specifying `-cp`. – Willis Blackburn Feb 23 '19 at 04:15
  • I now understand the whole concept. Thank you –  Feb 23 '19 at 04:24