0
Some questions I have about the Java language.
Hello, Basically I am learning Java for programming and developing games and apps and I have some questions and I am confused in some parts, please explain the simplest way possible! 1. In the main method what does "(String [] args)" mean and what does it do? When will I actually do something with this? 2. What does void do? I see that it means; it does not have a return value, but can someone explain this more to me? 3. What does static do? I understand it a bit, but Im still confused. Thanks for helping me out!
1 Resposta
+ 3
EDIT: I just realised you may have not gotten to the part about static in the Java course in Sololearn, that should help you understand. If you don't understand this right now, try after learning about methods and classes. :)
==========
1. (String[] args) is an array of strings named args, so it can be anything you want (args can be anything you want). Why? Because in the command line, you can run Java programs by typing:
java nameoffile
Because of this, you can add extra arguments to the running command. For example, you could make a server program and run:
java server.idk hostnamehere portnumberhere
Here, the (String[] args) part would be {"hostnamehere", "portnumberhere"}, and you could access those from the main() method.
==========
2. Every method needs a return type, because otherwise, the Java compiler will be confused (exceptions include constructors, etc.). Void kinda just fills in that part, saying 'nope, I don't return anything.'
==========
3. Static means that the thing is not specific to each instance of a class, but can be accessed by itself, without making a new instance. Suppose we have a Math class, and in that class we have a method called add(). If the method wasn't static, you would have to make an instance of Math, like:
Math mathclassthing = new Math();
After that, you'd be able to use the add() method. If the method is static, you can simply go:
Math.add();
Without making an instance of the class. With variables of a class, it means the variable belongs to the class, and there is only one of it. This can be used to count how many instances of a class there are:
class Example {
static int counter = 0;
Example() {
counter++
}
}
With classes, it just means everything in the class is static. There is an actual class called 'Math,' and it is a static class (correct me if I'm wrong), so you don't have to make an instance of it to use its methods.
==========
Hopefully that helped. Happy coding! 🙃