Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem on executing a java class file

Tags:

java

javac

I am new to java. I write a simple code like this:

import java.io.*;


public class a
{
    public static void main(String []argc)
    {
        System.out.println("S");
    }
}

I compile it with below bash command:

javac a.java

then this:

java a

But it said:

Could not find or load main class a

My java version is 1.6.0. What should I do?

like image 661
Babak Mehrabi Avatar asked Apr 27 '26 10:04

Babak Mehrabi


2 Answers

A common reason for this is that you've set the environment variable CLASSPATH.

This is usually not a good idea, because that setting always influences your whole system.

You can easily define a per-instance classpath, by specifying the -cp parameter.

In your case you can do

java -cp . a

This tells Java to look for classes in the current directory (.).

like image 141
Joachim Sauer Avatar answered Apr 30 '26 20:04

Joachim Sauer


Use this to run :

java -cp . a

Basically, you need to add the directory where your compiled .class file is to your classpath (which is the current directory, ., in your case).

Also, your code at this time uses no other APIs from external libraries, but most likely you would going forward. In that case, ensure that you add those JARs to you classpath (using java -cp .;<jar1 path>;<jar2 path> a) when running your code.

like image 30
Saket Avatar answered Apr 30 '26 20:04

Saket



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!