When I started learning Java I too started with the ubiqutous Hello world app. Which is more or less like :
public class MyClass {
public static void main(String args[]){
//some code here....
}
}
Its been many years since my tryst with Java but recently I was confronted by a beginner with a problem : Her class file wouldn’t run even though she was able to compile correctly.
After looking at her code the first thing I noticed was that is didn’t have the public access specifier on the class with the main method. I immediately mocked her on that slip up and went about “fixing” it by adding the public access modifier. The joke was on me offcourse as that didn’t make any difference either. I then realized that she was trying to execute the compiled class from a different directory from the one where the class file was. I changed to that dir and issued the java command and it ran immediately.
This brings me to my question… Most hello world examples have the class setup with public access when its just as ok to not have that at all. So what difference does it make if at all for a class that contains the main method ?
To help make it clearer as to what we were doing exactly here are the steps :
We had the class in
c:\users\[usersname]\[my documents folder]\myprog.class
and we tried to run it from c:\ (as our working dir) . We did specify the full relative path expecting it to work. like so :
java users\[usersname]\[my documents folder]\myprog
Offcourse this just failed untill I changed into the documents folder making it the current working dir and issuing the command again like so
java myprog
So basically such a call makes sense when you have the class in a package resembling the folder structure prepended to its name. In this case the class is not in any package.
The “public” vs. “package” specifier has to do with whether classes in other packages are allowed to “see” the class.
Most hello world programs ignore packages, so they go with the more common public option. Most people never have to learn about other package specifiers (and their limitations) until they actually learn to organize their project into packages. Of course, if you have only one class, it doesn’t matter either.
Also, I’m not sure why you mock novice programmers. I’ve been coding in Java for 10 years and still learn new things all the time.