-
Notifications
You must be signed in to change notification settings - Fork 1
Methods
Let's break down every part of that statement
This statement basically means that you have a method called main that:
- is accessible anywhere and by anyone (
public) - you can call
mainwithout having an object present (static) - has no return value (
void) - can contain String based arguments (
String[] args)
These are the basic parts of a method.
Methods can either be public, private, or in some cases protected. We'll go over protected when we begin talking about classes/objects later on.
- public - can be accessed directly inside or outside a class
- private - can only be accessed within the class
NEED TO ADD EXAMPLES
Static is an optional keyword that can be applied so that you could use a method without having to declare an object of the class containing the method.
NEED TO ADD EXAMPLES - Like a class that contains a static method to convert temperature from C to F that can be useful without needing to declare the class
A method must also have a return type listed. All the methods you've seen so far have been of the type void meaning that they don't return anything. If your method returns something though you must specify the type returned and also use the return keyword at the end of the method.
It should also be noted that a method can only have one return type.
> public class Example {
> public static int add(int a, int b) {
> int c = a + b;
> return c;
> }
>
> public static void main(String[] args) {
> System.out.println(Example.add(5, 6);
> }
11In the example above, we have a method takes two integer numbers and returns their integer sum.