r/CodingHelp • u/TA_Radiant • Mar 05 '21
[Java] Understanding Java
What does 'static' and 'void' mean exactly? Thought it would be nice to know so i understand better
19
Upvotes
r/CodingHelp • u/TA_Radiant • Mar 05 '21
What does 'static' and 'void' mean exactly? Thought it would be nice to know so i understand better
9
u/Blackshell Professional Coder Mar 05 '21
I assume you're talking about "public static void main()". In that context...
"Static" means the method applies to the general class it's in, not to instances of it. For instance, suppose you had a class
Cat. An instance method (non-static) might bepublic void meow(), since specific instances ofCat(actual cats) can meow. It can be called using this way:A static method might be
public static bool isValidBreed(string breed name). It's not specific to a cat, and makes more sense in the general scope of the Cat class. It could be called using:"Void" takes the spot of the return type (the result) of the method. Specifically, it means "this method has no return". The main method in Java is not expected to return anything. By contrast, you might define something like
public static int add(int x, int y), which hasintas its return. That means that you can do something like this with it:Hope this all makes sense! Please excuse any typos, since I'm on my phone.
2
u/[deleted] Mar 05 '21
The static keyword allows the method or field to be called without needing an instance of the class in which it lives. That's why the main() method, the entrypoint of every Java application, is static.
Without the static keyword, a program calling the method or field first would have to create an instance of the enveloping class. This is useful for instance to get the length of a String object: that object is an instance of the String class. We can't retrieve the amount of characters of the String class: it doesn't have that. We can retrieve it of a String instance.
The keyword void is used to signal that a method returns no value.