0

Suppose we have two .java files in the same directory.

Test.java:

public class Test {
    public void func() {
        System.out.println("Hello World");
    }
}

Main.java:

public class Main {
    public static void main(String args[]) {
        Test t = new Test();
        t.func();
    }
}

If I write in the command line: javac Main.java
it creates the Main.class and automatically creates Test.class and for running this program I use : java Main

but when I add package myPack statement in the first line of two files everything changes. and the structure of the files is as follows:

myPack
├── Main.java
└── Test.java

If I write javac Main.java the compiler says:

Main.java:5: error: cannot find symbol Test t = new Test();

and I should compile both of them at the same time. (javac Main.java Test.java)

Question 1) Why it happens?

Question 2) When I compiled both files I cant run program with java Main.

(Error: Could not find or load main class Main ).

What's the problem?

Question 3) I read somewhere you should compile and run this from the parent directory like this : javac myPack/Main.java (it automatically creates Test.class file) and then java myPack.Main . this way the program works properly. but why should we compile and run programs from the parent directory with this syntax?

1
  • Try cd .. and then javac myPack/Main.java. NB it is customary to use only lowercase in package names. Don't ask me why. Commented Apr 15, 2022 at 2:07

1 Answer 1

-1

Try this for compiling

# compile all files .java in folder ./myPack and outputing in ./folder-compiled
javac -d folder-compiled $(find ./myPack -name '*.java')

So you can run all compiled class with this

# run all Main.class already compiled in ./folder-compiled
java -cp folder-compiled Main

this example above will work because I'm considering your classpath is in myPack/* and you are not working with modular classpath jdk9+ in other way may be diferent

the other simple and easy way is working with building tools such as gradle or maven

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.