The best Java method Tutorial In 2024, In this tutorial you can learn Defined methods,Method Invocation,Keyword void,Passing parameters by value,Overloaded methods,Variable Scope,Using the command line parameters,Construction method,Variable parameter,finalize () method,
In the first few chapters, we often use to System.out.println (), then what is it?
println () is a method (Method), and the System is the system class (Class), out is the standard output object (Object). Usage of this statement is to call the system class System standard output object out method println ().
Java method is set of statements which together perform a function.
In general, the definition of a method comprising the following syntax:
修饰符 返回值类型 方法名 (参数类型 参数名){ /en. 方法体 /en. return 返回值; }
The method includes a method header and a method body. Here are all part of a process:
Such as:
public static int age(int birthday){/en.}
You can have more than one parameter:
static float interest(float principal, int year){/en.}
Note: In some other languages method refers to the process and functions. A non-void return type of the return value of the called function method; method returns a return value of void type called process.
The following method contains two parameters num1 and num2, it returns the maximum value of these two parameters.
/** 返回两个整型变量数据的较大值 */ public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
Java supports two ways to invoke a method, according to whether the method return value to select.
When the program calls a method, a program to control the method is called. When the called method's return statement is executed or until the body of the method when the closing parenthesis return control to the program.
When the method returns a value, the method invocation is generally treated as a value. E.g:
int larger = max(30, 40);
If the method return value is void, the method call must be a statement. For example, the method println returns void. The following call is a statement:
System.out.println("Welcome to Java!");
The following example shows how to define a method, and how to call it:
public class TestMax { /** 主方法 */ public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println("The maximum between " + i + " and " + j + " is " + k); } /** 返回两个整数变量较大的值 */ public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } }
The above examples compiled results are as follows:
The maximum between 5 and 2 is 5
This program contains a main method and the method of max. Main JVM method is invoked, in addition, main and other methods no difference.
Head main method is the same as the example shown, with modifiers public and static, the value of void return type, method name is main, in addition with a a String [] type parameters. String [] that the argument is an array of strings.
This section explains how to declare and call a void method.
The following example declares a method named printGrade, and call it to print a given score.
public class TestVoidMethod { public static void main(String[] args) { printGrade(78.5); } public static void printGrade(double score) { if (score >= 90.0) { System.out.println('A'); } else if (score >= 80.0) { System.out.println('B'); } else if (score >= 70.0) { System.out.println('C'); } else if (score >= 60.0) { System.out.println('D'); } else { System.out.println('F'); } } }
The above examples compiled results are as follows:
C
Here printGrade method is a method of type void, it does not return a value.
A void method call must be a statement. Therefore, it is the main method of the third line calls in the form of the statement. Like any statement ends with a semicolon like.
Call a method when you need to provide the parameters, you must provide the parameter list according to the order specified.
For example, the following method of continuous n Times prints a message:
public static void nPrintln(String message, int n) { for (int i = 0; i < n; i++) System.out.println(message); }
The following example illustrates the effect passed by value.
The program creates a method that is used to exchange two variables.
public class TestPassByValue { public static void main(String[] args) { int num1 = 1; int num2 = 2; System.out.println("Before swap method, num1 is " + num1 + " and num2 is " + num2); // 调用swap方法 swap(num1, num2); System.out.println("After swap method, num1 is " + num1 + " and num2 is " + num2); } /** 交换两个变量的方法 */ public static void swap(int n1, int n2) { System.out.println("\tInside the swap method"); System.out.println("\t\tBefore swapping n1 is " + n1 + " n2 is " + n2); // 交换 n1 与 n2的值 int temp = n1; n1 = n2; n2 = temp; System.out.println("\t\tAfter swapping n1 is " + n1 + " n2 is " + n2); } }
The above examples compiled results are as follows:
Before swap method, num1 is 1 and num2 is 2 Inside the swap method Before swapping n1 is 1 n2 is 2 After swapping n1 is 2 n2 is 1 After swap method, num1 is 1 and num2 is 2
Pass two parameters to call swap method. Interestingly, after the method is called, the value of the argument has not changed.
max method uses the above only applies to data type int. But if you want to get the maximum value of two floating-point data type it?
The solution is to create another parameter with the same name but a different method, as shown in the following code:
public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; }
If you call max method is passed an int parameter, max method of the int argument is invoked;
If passed double type parameter, the type of double experience max method is called, this is called method overloading;
That two methods of a class have the same name, but with different parameter list.
Java compiler according to the method signature to determine which method should be called.
Method overloading can make the program more legible. The method of execution is closely related tasks should use the same name.
Overloaded methods must have different parameter list. You can not just based on different types of modifiers or return to overloaded methods.
Range variable is part of the program where the variable can be referenced.
Variables within method definition are called local variables.
Scope of a local variable declarations from the start until the end of the block containing it.
Local variables must be declared before they can be used.
The method of covering the entire range of parameters method. Parameter is actually a local variable.
Variable initialization part of the for loop statement, the scope of its role in the cycle.
But variable loop body statement is a statement of its scope from it to the end of the loop. It contains a variable declared as follows:
You can in a way, the different non-nested blocks repeatedly declare a local variable with the same name, but you can not be nested within the block twice to declare local variables.
Sometimes you want to run a program when it then passed the message. This depends on passing command-line arguments to the main () function to achieve.
Command line argument is followed by information on execution time after the program name.
The following program prints 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]); } } }
As shown below, run the program:
java CommandLine this is a command line 200 -100
Results are as follows:
args[0]: this args[1]: is args[2]: a args[3]: command args[4]: line args[5]: 200 args[6]: -100
When an object is created when the constructor is used to initialize the object. And it is in the class constructor of the same name, but the constructor has no return value.
Often use the constructor to a class instance variable initial values, or perform other necessary steps to create a complete object.
Whether or not you are a custom constructor, all classes have constructor because Java automatically provides a default constructor, which all members are initialized to zero.
Once you have defined your own constructor, the default constructor will fail.
Here is an example of using the constructor:
// 一个简单的构造函数 class MyClass { int x; // 以下是构造函数 MyClass() { x = 10; } }
You can call like this constructor to initialize an object:
public class ConsDemo { public static void main(String args[]) { MyClass t1 = new MyClass(); MyClass t2 = new MyClass(); System.out.println(t1.x + " " + t2.x); } }
Most of the time need a constructor parameter.
Here is an example of using the constructor:
// 一个简单的构造函数 class MyClass { int x; // 以下是构造函数 MyClass(int i ) { x = i; } }
You can call like this constructor to initialize an object:
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); } }
Results are as follows:
10 20
As of JDK 1.5, Java support passing the same type of variable parameters to a method.
Declare the variable parameters of the method are as follows:
typeName/en. parameterName
In the method statement, the specified parameter type after adding an ellipsis (/en.).
A method can specify only one variable parameter, it must be the last parameter method. Any common parameters must be declared before it.
public class VarargsDemo { public static void main(String args[]) { // 调用可变参数的方法 printMax(34, 3, 3, 2, 56.5); printMax(new double[]{1, 2, 3}); } public static void printMax( double/en. 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); } }
The above examples compiled results are as follows:
The max value is 56.5 The max value is 3.0
Java allows you to define a method in which an object is invoked before the garbage collector destructor (recycling), this method is called finalize (), which is used to clear the recovered objects.
For example, you can use the finalize () to ensure that an object open file is closed.
In finalize () method, you must specify the operation to be performed when the object is destroyed.
finalize () is the general format:
protected void finalize() { // 在这里终结代码 }
Keyword protected is a qualifier, it ensures that finalize () method is never called the code outside the class.
Of course, Java's garbage collection can be done automatically by the JVM. If you use the manual, you can use the above method.
public class FinalizationDemo { public static void main(String[] args) { Cake c1 = new Cake(1); Cake c2 = new Cake(2); Cake c3 = new Cake(3); c2 = c3 = null; System.gc(); //调用Java垃圾收集器 } } class Cake extends Object { private int id; public Cake(int id) { this.id = id; System.out.println("Cake Object " + id + "is created"); } protected void finalize() throws java.lang.Throwable { super.finalize(); System.out.println("Cake Object " + id + "is disposed"); } }
Run the above code, the output results are as follows:
C:\1>java FinalizationDemo Cake Object 1is created Cake Object 2is created Cake Object 3is created Cake Object 3is disposed Cake Object 2is disposed