r/CodingHelp • • 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

7 comments sorted by

View all comments

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 be public void meow(), since specific instances of Cat (actual cats) can meow. It can be called using this way:

Cat mitzi = new Cat();
mitzi.meow();

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:

Cat.isValidBreed("Maine Coon"); // returns true
Cat.isValidBreed("Dachshund"); // returns false

"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 has int as its return. That means that you can do something like this with it:

int z = add(3, 5); // z now has value 8

Hope this all makes sense! Please excuse any typos, since I'm on my phone.

3

u/TA_Radiant Mar 05 '21

Please excuse me because this is my first time doing Java. Still do not clearly understand the static keyword. Does it mean what happens in the method block is only applied in that specific instance of the class?

4

u/Rrrrry123 Mar 05 '21

I think you have it backwards. Static means that you don't have to have an instance of a class to use the method. One instance it can be helpful is if you want to make a class full of related helper functions. Let's say I wanted to make a class full of math formulae. If the methods were non-static, I would have to initialize the class before I can use those methods.Formulae formulae = new Formulae()

However, if all the methods were static, I could just do Formulae.areaOfSquare(x,y); without ever having to initialize the class.

I'm just guessing here, because I haven't actually tried this for a long time, but I'm pretty sure static member functions can only access static member variables (which makes sense if you think about it). However, non-static methods can access static methods and variables.