views:

590

answers:

4

what does public static void mean in java? I'm in in the process of learning. In all the examples in the book i'm working from public.static.void comes before any method that is being used or created. What does this mean?

+19  A: 

It's three completely different things:

public means that the method is visible and can be called from other objects of other types. Other alternatives are private, protected, package and package-private. See here for more details.

static means that the method is associated with the class, not a specific instance of that class.

void means that the method has no return value. If the method returned an int you would write int instead of void.

The combination of all three of these is most commonly seen on the main method which most tutorials will include.

Mark Byers
Since the questioner is still learning: the order of these keywords is also important. All modifiers first (`public`, `static`, `private`, etc.) then the return type (`void` in this case).
Pindatjuh
+6  A: 

The three words have orthogonal meanings.

public means that the method will be visible from classes in other packages.

static means that the method is not attached to a specific instance, and it has no "this". It is more or less a function.

void is the return type. It means "this method returns nothing".

Thomas Pornin
+4  A: 

It means that:

  • "public" - it can be called from anywhere
  • "static" - it doesn't have any object state, so you can call it without instantiating an object
  • "void" - it doesn't return anything

You'd think that the lack of a return means it isn't doing much, but it might be saving things in the database, for example.

Paul Tomblin
+1  A: 

It means three things.

First public means that any other object can access it.

static means that the class in which it resides doesn't have to be instantiated first before the function can be called.

void means that the function does not return a value.

Since you are just learning, don't worry about the first two too much until you learn about classes, and the third won't matter much until you start writing functions (other than main that is).

Best piece of advice I got when learning to program, and which I pass along to you, is don't worry about the little details you don't understand right away. Get a broad overview of the fundamentals, then go back and worry about the details. The reason is that you have to use some things (like public static void) in your first programs which can't really be explained well without teaching you about a bunch of other stuff first. So, for the moment, just accept that that's the way it's done, and move on. You will understand them shortly.

Aaron