A Java method is a combination of some statements to perform an operation. For example, when you call the System.out.println method, the system will actually execute many statements to output information on the console.
Now you will learn how to create your own methods. They can have return values or no return values, can have parameters or no parameters. Overloading methods should use the same method name and use abstract methods in programming.
Creation method
Let's use the following example to explain the syntax of the method:
public static int funcName(int a, int b) { // body}Here
Methods also contain procedures or functions.
The definition of a method includes a method header and a method body. As shown below:
modifier returnType nameOfMethod (Parameter List) { // method body}The above syntax includes
Example
This is the method max() defined above, which accepts two parameters num1 and num2 to return the maximum value between the two.
/** the snippet returns the minimum between two numbers */public static int minFunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; } Method call
To use a method, the method must be called. There are two ways to call the method, one has a return value, and the other has no return value.
Calling a method is very simple. When a program needs to call a method, the control program transfers to the called method. The method will return two conditions to the caller:
Take the method that returns void as a call statement, let me see the following example:
System.out.println("wiki.jikexueyuan.com!");The return value of this method can be understood by the following example:
int result = sum(6, 9);
Example
The following example shows how to define a method and how to call it:
public class ExampleMinNumber{ public static void main(String[] args) { int a = 11; int b = 6; int c = minFunction(a, b); System.out.println("Minimum Value = " + c); } /** returns the minimum of two numbers */ public static int minFunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; }}The following results will be produced
Minimum value = 6
Keyword void
The keyword void allows us to create a method without a return value. Here we create a void method methodRankPoints in the next example. This method has no return value type. Calling the void method must declare methodRankPoints(255.7); the Java statement ends with a semicolon, as shown below:
public class ExampleVoid { public static void main(String[] args) { methodRankPoints(255.7); } public static void methodRankPoints(double points) { if (points >= 202.5) { System.out.println("Rank:A1"); } else if (points >= 122.4) { System.out.println("Rank:A2"); } else { System.out.println("Rank:A3"); } }}This will produce the following results:
Rank:A1
Pass parameters by values
Parameters must be passed when calling a function. And their order must be the same as the order of parameters when they were created. Parameters can be passed by values or references.
Passing parameters through values means calling the parameter of the method, passed to the parameter through the parameter value.
Example
The following program gives an example to show that parameters are passed by values. The parameter value will not change after calling the method.
public class swappingExample { public static void main(String[] args) { int a = 30; int b = 45; System.out.println("Before swapping, a = " + a + " and b = " + b); // Invoke the swap method swapFunction(a, b); System.out.println("/n**Now, Before and After swapping values will be same here**:"); System.out.println("After swapping, a = " + a + " and b is " + b); } public static void swapFunction(int a, int b) { System.out.println("Before swapping(Inside), a = " + a + " b = " + b); // Swap n1 with n2 int c = a; a = b; b = c; System.out.println("After swapping(Inside), a = " + a + " b = " + b); }}This will produce the following results:
Before swapping, a = 30 and b = 45Before swapping(Inside), a = 30 b = 45 After swapping(Inside), a = 45 b = 30**Now, Before and After swapping values will be same here**:After swapping, a = 30 and b is 45
Method overloading
When a method has two or more methods, their names are the same but the parameters are different, it is called method overloading. It is different from covering. Override refers to the number of methods with the same name, type and parameters.
Let's consider the previous example of finding the minimum integer number. If we ask to find the smallest number in a floating point type, we need to use the overload of the method to create two or more methods with the same function name but different parameters.
The following examples are explained:
public class ExampleOverloading{ public static void main(String[] args) { int a = 11; int b = 6; double c = 7.3; double d = 9.4; int result1 = minFunction(a, b); // same function name with different parameters double result2 = minFunction(c, d); System.out.println("Minimum Value = " + result1); System.out.println("Minimum Value = " + result2); } // for integer public static int minFunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; } // for double public static double minFunction(double n1, double n2) { double min; if (n1 > n2) min = n2; else min = n1; return min; }}This will produce the following results:
Minimum Value = 6 Minimum Value = 7.3
Overloading methods make the program easy to read. Here, the two methods have the same name but different parameters. Generates the minimum number of integer and floating point types as the result of the program running.
Use command line parameters
Sometimes you want to pass parameters before the program runs. This can be achieved by passing command line parameters to the main function.
On the command line, when you want to execute a program file, a command line parameter appears immediately after the file name. It is very easy to accept command line parameters in Java programs. They are passed into the main function character array.
Example
The following example shows a program that outputs all command line parameters:
public class CommandLine { public static void main(String args[]){ for(int i=0; i<args.length; i++){ System.out.println("args[" + i + "]: " + args[i]); } }}Execute the program by:
java CommandLine this is a command line 200 -100
This will produce the following results:
args[0]: thisargs[1]: isargs[2]: aargs[3]: commandargs[4]: lineargs[5]: 200args[6]: -100
Constructor
Here is a simple example of using constructors:
// A simple constructor.class MyClass { int x; // Following is the constructor MyClass() { x = 10; }}You can instantiate an object by calling the constructor:
public class ConsDemo { public static void main(String args[]) { MyClass t1 = new MyClass(); MyClass t2 = new MyClass(); System.out.println(t1.x + " " + t2.x); }}Typically, you will need to use a constructor to accept one or more parameters. The parameter passing is the same as the parameter passing of the ordinary method introduced above, which is to list the parameter list after the name of the constructor.
Example
Here is a simple example of using constructors:
// A simple constructor.class MyClass { int x; // Following is the constructor MyClass(int i ) { x = i; }}You can instantiate an object by calling the constructor:
public class ConsDemo { public static void main(String args[]) { MyClass t1 = new MyClass( 10 ); MyClass t2 = new MyClass( 20 ); System.out.println(t1.x + " " + t2.x); }}This will produce the following results:
10 20
Variable length parameters
JDK1.5 can allow you to pass variable length parameters of the same type. Declare it using the following method:
typeName... parameterName
When declaring a method, you need to specify the parameter type before the ellipsis, and there can only be one variable length parameter, and the variable length parameter must be the last of all parameters.
Example
public class VarargsDemo { public static void main(String args[]) { // Call method with variable args printMax(34, 3, 3, 2, 56.5); printMax(new double[]{1, 2, 3}); } public static void printMax( double... numbers) { if (numbers.length == 0) { System.out.println("No argument passed"); return; } double result = numbers[0]; for (int i = 1; i < numbers.length; i++) if (numbers[i] > result) result = numbers[i]; System.out.println("The max value is " + result); }}This will produce the following results:
The max value is 56.5The max value is 3.0
finalize() method
You can define a method that will only be called before being destroyed by the garbage collector. This method is called the finalize() method, which can also be used to ensure that an object is cleaned.
For example, you might use finalize() to ensure that the file opened by an object has been closed.
To add a finalizer to the class, you just need to define the finalize() method. When Java wants to recycle an object of this class, the method will be called.
In the finalize() method, you will specify some behavior that must be done before the object is destroyed.
The finalize() method is generally similar to the following:
protected void finalize( ){ // finalization code here}Here, the keyword protected is to ensure that code outside the class cannot access the finalize() method.
This means you can't know when finalize() is executed. For example, if your program ends before the garbage collector occurs, the finalize() method will not be executed.
Generic methods:
Java generic methods are widely used when the method returns a value that is a container-class object.
public static List<T> find(Class<T> clazz,String userId){ ....}Generally speaking, when writing a Java generic method, the return value type and at least one parameter type should be generic, and the type should be the same. If only one of the return value type or parameter type uses a generic, the use of this generic method will be greatly restricted, basically to the same level as if you don't use generics.
The following mainly introduces the use of two very similar java generic methods and the differences between them.
The first type:
public static <T extends CommonService> T getService(Class<T> clazz) { T service = (T) serviceMap.get(clazz.getName()); if (service == null) { service = (T) ServiceLocator.getService(clazz.getName()); serviceMap.put(clazz.getName(), service); } return service; } The second type:
public static <T> T getService(Class<? extends CommonService> clazz) { T service = (T) serviceMap.get(clazz.getName()); if (service == null) { service = (T) ServiceLocator.getService(clazz.getName()); serviceMap.put(clazz.getName(), service); } return service; } Here is the class where the generic method resides:
public abstract class CommonService { private static HashMap<String, CommonService> serviceMap = new HashMap<String, CommonService>(); //Here is the generic method definition. . } These two generic methods only have different methods' signatures and the method bodies are exactly the same. So what's the difference?
Let's use them and you'll know the difference.
Use the first generic method:
public class Main { public static void main(String[] args) { NoticeService noticeService=CommonService.getService(NoticeService.class);// Use the first generic method correctly without compiling errors. NoticeService noticeService=CommonService.getService(UserService.class);//If you use the first generic method incorrectly, a compilation error will occur. }} Use the second generic method:
public class Main { public static void main(String[] args) { NoticeService noticeService=CommonService.getService(NoticeService.class);// Use the second generic method correctly, there will be no compilation errors, the logic is correct, and there will be no exceptions during runtime. NoticeService noticeService=CommonService.getService(UserService.class);//If you use the second generic method incorrectly, there will be no compilation errors, but the logic is incorrect, and an exception will occur during runtime, which is dangerous! }}Now I know the difference between these two extremely similar generic methods?