1

I had some java classes a couple years ago, due to lack of use it all faded away. now ive been getting back into it. i was following a very simple tutorial building something using sublime (it was so simple i didn't bother on getting a proper IDE) the two files are:

package hello;

public class HelloWorld {
    public static void main(String[] args) {
        Greeter greeter = new Greeter();
        System.out.println(greeter.sayHello());
        System.out.println("random alt shift");
    }
}

and

package hello;

public class Greeter {
    public String sayHello() {
        return "Hello world!";
    }
}

Greeter compiles dine but HelloWorld gives me the following error: javac HelloWorld.java

HelloWorld.java:6: error: cannot find symbol
        Greeter greeter = new Greeter();
        ^
  symbol:   class Greeter
  location: class HelloWorld
HelloWorld.java:6: error: cannot find symbol
        Greeter greeter = new Greeter();
                              ^
  symbol:   class Greeter
  location: class HelloWorld
2 errors

and if i add "import hello.Greeter;" i get:

HelloWorld.java:2: error: cannot find symbol
import hello.Greeter;
            ^
  symbol:   class Greeter
  location: package hello
HelloWorld.java:6: error: cannot find symbol
        Greeter greeter = new Greeter();
        ^
  symbol:   class Greeter
  location: class HelloWorld
HelloWorld.java:6: error: cannot find symbol
        Greeter greeter = new Greeter();
                              ^
  symbol:   class Greeter
  location: class HelloWorld
3 errors

On the IDE it runs fine, can anyone be so kind as to explain whats happening

1
  • 1
    @SureshAtta No he doesn't. There is no need to explicitly import classes from the same package. Commented Jul 4, 2017 at 11:36

1 Answer 1

9
javac HelloWorld.java

The problem is here. You're in the wrong directory. You should be up one level, where the package hierarchy starts, and you should be issuing

javac hello/HelloWorld.java
Sign up to request clarification or add additional context in comments.

4 Comments

Worked marvelously, could you explain me why i need to be one level higher?
Because compilation needs to respect the package structure, and the package is rooted one level higher than you had been telling javac, and you didn't use command-line options to make it clear.
@LewBloch Sorry to revive an old question, but I'm still confused on why we must compile outside of the package hierarchy. What is the point of this?
You aren't outside the package hierarchy. You're at the top of the hierarchy. The top level is the unnamed package. It's a bad idea to use the unnamed package. Outside the hierarchy would be one more level up.

Your Answer

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