public class Main { static void myMethod() { System.out.println("I just got executed!"); } public static void main(String[] args) { myMethod(); } } // Outputs "I just got executed!"
Parameters and Arguments
When a parameter is passed to the method, it is called an argument. So, from the example above: fname
is a parameter, while Liam
, Jenny
and Anja
are arguments.
public class Main { static void myMethod(String fname) { System.out.println(fname + " Refsnes"); } public static void main(String[] args) { myMethod("Liam"); myMethod("Jenny"); myMethod("Anja"); } } // Liam Refsnes // Jenny Refsnes // Anja Refsnes
Method Overloading
With method overloading, multiple methods can have the same name with different parameters:
int myMethod(int x) float myMethod(float x) double myMethod(double x, double y)
Variables declared directly inside a method
public class Main { public static void main(String[] args) { // Code here CANNOT use x int x = 100; // Code here can use x System.out.println(x); } }
Recursion
public class Main { public static void main(String[] args) { int result = sum(10); System.out.println(result); } public static int sum(int k) { if (k > 0) { return k + sum(k - 1); } else { return 0; } } }
标签:Java,Methods,int,void,static,myMethod,public,String From: https://www.cnblogs.com/ShengLiu/p/16924022.html