Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Beginning Java and the fly likes why public keyword is necessory here? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "why public keyword is necessory here?" Watch "why public keyword is necessory here?" New topic

why public keyword is necessory here?

vianyrajnish rajnish
Ranch Hand

Joined: Apr 22, 2007
Posts: 70
hi all,

This is a simple java program -----

public class HelloWorldApp
public static void main(String arg[])
System.out.println("Hello World!");

here why do i declare -- public class HelloWorldApp -- for the class .?
if i remove (public) this i do get error..why is this?

can anyone please answer?

-- vinay rajnish
Maurizio Nagni
Ranch Hand

Joined: May 29, 2004
Posts: 75
Generaly it is not an error to set "default" the class, but the error appears if you try to run it throught the "java HelloWorldApp" command; in this case the JVM cannot access the main method (because the class is not public).

To test that it just try to modify your HelloWorldApp file as

Note that in this case the code will give you an error if you define public the Test class because as defined in the Java syntax one file can contain one public class with a public static void main(String[] args) method.

asha ganapathy
Ranch Hand

Joined: Nov 03, 2006
Posts: 54
I think the keyword "public" is used so that other classes in the same package or in the different package can use this class.
If you dont declare HelloWorldApp class as public it means its using a default access(you can use this class only in the current package, hence even if you dont use public keyword for HelloWorldApp there should not be any compiler error.
vianyrajnish rajnish
Ranch Hand

Joined: Apr 22, 2007
Posts: 70
hi all,

thanks for helping .... all of you are correct

thanks for helping with clearing the concepts..

vinay rajnish
wood burning stoves
subject: why public keyword is necessory here?
Similar Threads
Why Blackberry Simulator run so slow for HelloWorld App.
Fresh SDK Install Won't Compile?
Exception in thread "main" java.lang. NoClassDefFoundError: HelloWorldApp
Error by compiling textfile Could not find the main class: HelloWorldapp. Program will exit
Classpath problem when trying to access packages