Solyridz3
Solyridz3

Reputation: 43

Run with console class import error(java)

The question is: if I run my Test.java file with run button in IntelliJ it works just fine, but if I run it manually with console by writing java Test.java it breaks with an error. (Files are in the same folder.):

Error

.\src\Test.java:4: error: cannot find symbol
        Car car1 = new Car();
        ^
  symbol:   class Car
  location: class Test
.\src\Test.java:4: error: cannot find symbol
        Car car1 = new Car();

Test.java

public class Test {
    public static void main(String[] args) {
        Car car1 = new Car();
        System.out.println(car1.model);
    }
}

Car.java

public class Car {
    String model = "Corvette";
}   

Upvotes: 0

Views: 99

Answers (1)

Abra
Abra

Reputation: 20913

Look at the java command that appears in the Run window of IntelliJ when you run class Test. You will notice it is very different to that which you are trying, i.e. java Test.java.

According to the documentation, you can only run a single source code file, however class Test references class Car so you need to first compile class Car and then add the appropriate path option, i.e. either --class-path or --module-path, e.g.

java --class-path whatever Test.java

where whatever is the appropriate path to file Car.class.

Alternatively, when running a single Java source code file, the file name does not have to be identical to the name of the public class that it defines and it can also contain more than one public class – contrary to the rules required when compiling Java source code. (Refer to the documentation for javac as well as Oracle's Java tutorials.) Hence you can write the code for both class Car and class Test in a single file and run that code using the java command.

I wrote file TestCar.java as follows:

public class Test {
    public static void main(String[] args) {
        Car car1 = new Car();
        System.out.println(car1.model);
    }
}

public class Car {
    String model = "Corvette";
}

And issued the following command, from the folder containing file TestCar.java:

java TestCar.java

And got the following output:

Corvette

I used [Oracle] JDK 19 on Windows 10.

Upvotes: 1

Related Questions