+91 81900 98289

Java Methods

A method is a named block you can call. Parameters are the inputs. The return type is what it gives back. void means it gives nothing back and is used for actions such as printing.

A static method belongs to the class, so main can call it without creating an object. Pass the values main already has. Do not reach for variables that live only inside another method.

Example

2.0 forces a double division. (70 + 90) / 2 with two ints would be 80 as well, but an odd total would drop the fraction.

public class Average { static double mean(int a, int b) { return (a + b) / 2.0; } public static void main(String[] args) { System.out.println(mean(70, 90)); } }
Return ends the method immediately. Code after a plain return in the same block does not compile. Name the method for the result, such as mean, not doStuff.