A Java method is a combination of some statements that perform an operation. For example, when you call the System.out.println method, the system actually executes a lot of statements to output the information on the console.
Now you'll learn how to create your own methods, they can have return values, no return values, parameters, or no parameters, overloaded methods use the same method name, and use abstract methods in programming.
Create method
We use the following example to explain the syntax of the method:
public static int FuncName (int a, int b) {
//body
}
Over here
- public static: Modifier
- int: return value type
- FuncName: Function name
- A,b: Formal parameters
- int a,int B: Parameter columns
Methods also contain procedures or functions.
- Procedure: They do not return a value
- Functions: They return a value
The definition of a method contains the method header and the method body. As shown below:
Modifier returntype nameofmethod (Parameter List) {
//method body
}
The above syntax includes
- Modifier: He defines the access type of the method, which is optional.
- ReturnType: Method is possible to return a value.
- Nameofmethod: This is the name of the method. The method signature includes a method name and a list of parameters.
- Parameter list: The sequence of parameters, the type, and the number of parameters. These are optional, and of course the method can have no parameters.
- Method Body: The method body defines what the method is used for.
Example
This is the method max () defined above that 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 calls
to use a method, the method must be invoked. There are two ways to call a method, one with a return value and one that has no return value.
Calling a method is simple, when a program needs to call a method, the control program moves to the called method, and the method returns two conditions to the caller:
- Returns an execution statement
- Execution to method end
To take the method of returning void as a call statement, let me look at the following example:
System.out.println ("wiki.jikexueyuan.com!");
The return value of the method can be understood through the following example:
Example
The following example shows how to define a method and how to invoke it:
public class exampleminnumber{public
static void Main (string[] args) {
int a = one;
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;
}
will produce the following results
key word void
the keyword void allows us to create a method that does not have a return value. Here we create a void method methodrankpoints in the next example. This method is not a return value type. Call void method must declare methodrankpoints (255.7); The Java statement ends with a semicolon, as follows:
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"); c7/>}
else if (points >= 122.4) {
System.out.println ("rank:a2");
}
else {
System.out.println ("Rank:a3");}}}
This will produce the following results:
Passing parameters by value
parameters must be passed when the function is invoked. And their order must be the same as the order of the parameters they created. Parameters can be passed by value or by reference.
Passing a parameter by value means calling the parameter of the method, which is passed to the parameter by a parameter value.
Example
The following program gives an example to show passing parameters by value. The parameter value does not change after the method is invoked.
public class Swappingexample {public
static void Main (string[] args) {
int a =;
int b =;
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 would be same here**:");
System.out.println ("After swapping, a =" +
A + "and B" + 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 = and B =
before swapping (Inside), a = b =-after
swapping (Inside), a = b = 30
**now, before and after swapping values would be same here**: After
swapping, a = and B are 45
Overload of the method
when a method has two or more methods, their name is the same but the parameter is not the same, it is called the overload of the method. It is different from the overlay. Overlay means that the method has the same name, type, and number of parameters.
Let's consider the previous example of finding the smallest integer number. If we ask for the smallest number of floating-point types, we need to use the overload of the method to create two or more methods with the same function name, but with different parameters.
The following example gives an explanation:
public class exampleoverloading{public
static void Main (string[] args) {
int a = one;
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 the 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
Overloaded methods make programs easy to read. Here, the two methods have the same name but different parameters. Produces the smallest number of integral and floating-point types as the result of a program run.
Using Command line arguments
Sometimes you want to pass parameters before the program runs. This can be done by passing command-line arguments to the main function.
On the command line, when you want to execute a program file, a command-line argument appears immediately after the file name. It is very easy to accept command-line arguments in Java programs. They are passed into the array of main function numbers.
Example
The following example shows a program that outputs all command-line arguments:
public class CommandLine {public
static void Main (String args[]) {for
(int i=0; i<args.length; i++) {
System.out.println ("args[" + i + "]:" +
args[i]);}}
Use the following methods to execute the program:
Java CommandLine This be a command line 200-100
This will produce the following results:
Args[0]: This
args[1]: are
args[2]: a
args[3]: command
args[4]: line
args[5]:
args[ 6]:-100
Constructors
This is a simple example of using a constructor:
A Simple constructor.
Class MyClass {
int x;
Following is the constructor
MyClass () {
x = ten;
}
}
You can instantiate an object by invoking the constructor in the following ways:
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. Parameter passing is the same as the parameter pass of the normal method described above, that is, the list of parameters is listed after the constructor's name.
Example
This is a simple example of using a constructor:
A Simple constructor.
Class MyClass {
int x;
Following is the constructor
MyClass (int i) {
x = i;
}
}
You can instantiate an object by invoking the constructor in the following ways:
public class Consdemo {public
static void Main (String args[]) {
MyClass t1 = new MyClass (a);
MyClass t2 = new MyClass (m);
System.out.println (t1.x + "" + t2.x);
}
This will produce the following results:
Variable Long parameters
JDK1.5 allows you to pass variable-length parameters of the same type. Declare it in the following ways:
TypeName ... parametername
method declaration, you have to specify the parameter type before omitting the number, and you can have only 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 (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 passe D ");
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.5 the
max value is 3.0
Finalize () method
You can define a method that will only be invoked before it is destroyed by the garbage collector. This method, called the Finalize () method, can also be used to ensure that an object is cleaned cleanly.
For example, you might use Finalize () to make sure that a file opened by an object has been closed.
To add a finalizer to a class, you only need to define the Finalize () method. This method is invoked when Java wants to reclaim an object of the class.
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 don't know when Finalize () will be executed. For example, if your program ends before the garbage collector occurs, the Finalize () method will not be executed.
Generic method:
Java generic methods are widely used when the method return value is a container class object.
public static list<t> Find (class<t> clazz,string userId) {
...
}
In general, when writing Java generic methods, the return value type and at least one parameter type should be generic, and the type should be consistent, and if only one of the return value types or parameter types uses generics, the use of this generic method is greatly limited and is basically limited to the same extent as the generic type.
The following are mainly about the use of two very similar Java generic methods and the differences between them.
First type:
public static <t extends commonservice> t GetService (class<t> clazz) {
T service = (t) servicemap.get (Claz Z.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 (CLA Zz.getname ());
if (service = = null) {
service = (T) servicelocator.getservice (Clazz.getname ());
Servicemap.put (Clazz.getname (), service);
}
return service;
The following is the class in which 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 the signature of the method is different, the method body is exactly the same, then what are they different?
Let's use them to know the difference.
Use of the first generic method:
public class Main {public
static void Main (string[] args) {
Noticeservice noticeservice= Commonservice.getservice (Noticeservice.class);//correct use of the first generic method, no compilation error occurs.
noticeservice Noticeservice=commonservice.getservice (userservice.class)//incorrect use of the first generic method will cause a compilation error.
}
}
Use of the second generic method:
public class Main {public
static void Main (string[] args) {
Noticeservice noticeservice= Commonservice.getservice (noticeservice.class); the correct use of the second generic method does not present a compilation error, the logic is correct, and the runtime does not have an exception.
noticeservice Noticeservice=commonservice.getservice (userservice.class)//incorrect use of the second generic method, no compilation error, but incorrect logic, There will be an exception at run time, dangerous!
}
}
Now you know the difference between these two very similar generic methods?
- The first generic method: The return value and the parameter value of the type are consistent, recommended;
- The second generic method: The return value and the parameter value are not the same type, please be cautious or avoid using them.