public static void methodName() { System. out. println(“This is a method”); }
Public: By placing the access modifier “public” before the method name allows the method to be called from anywhere. Protected: The “protected” access modifier, only allows the method to be called within it’s class and subclasses. Private: If a method is declared private, then the method can only be called inside the class. This is called the default, or package-private. This means that only the classes in the same package can call the method.
If the keyword “static” was not used, then the method can be invoked only through an object. For instance, if the class was called “ExampleObject” and it had a constructor (for making objects), then we could make a new object by typing “ExampleObject obj = new ExampleObject();”, and call the method with using the following: “obj. methodExample();”.
If you do want a method to return something, then simply replace the word “void<” with a data type (primitive or reference type) of the object (or primitive type) that you wish to return. Primitive types include int, float, double, and more. Then just add “return” plus an object of that type somewhere toward the end of the method’s code. When calling a method that returns something, you can use what it returns. For example, if a method called “someMethod()” returns an integer (a number), then you can set an integer to what it returns using the code: “int a = someMethod();”
public class className { public static void methodName(){ System. out. println(“This is a method”); } public static void main(String[] args) { methodName(); } }
public class myClass { public static void sum(int a, int b){ int c = a + b; System. out. println(“The sum of A and B is “+ c); } public static void main(String[] args) { sum(20, 30); } }