Java Methods

We often used System.out.println() in previous chapters. What is it?
  • Println() is a method.
  • System is a system class.
  • Out is the standard output object.
The use of this sentence is to call the method println() in the standard output object out of the system class System.

So what is a method?

Java methods are collections of statements that perform a function together.
  • Method is an ordered combination of steps to solve a class of problems
  • Methods are included in a class or object
  • Methods are created in the program and referenced elsewhere

The advantages of the method

  • 1. Make the program shorter and clearer.
  • 2. It is good for program maintenance.
  • 3. It can improve the efficiency of program development.
  • 4. Improve code reusability.

Method naming rules

  • 1. The first word of the method's name should begin with a lowercase letter. The following words should be written with a capital letter, without the use of connectors. For example: addPerson .
  • 2. Underscores may appear in JUnit test method names to separate logical components of names. A typical pattern is: test<MethodUnderTest>_<state> , for example testPop_emptyStack .

Method definition

In general, defining a method contains the following syntax:
Modifier return value type method name ( parameter type parameter name ) { ... method body ... return return value; }
The method contains a method header and a method body. Here are all parts of a method:
  • Modifier: Modifier, which is optional, tells the compiler how to call this method. Defines the method's access type.
  • Return Type: The method may return a value. returnValueType is the data type of the method return value. Some methods perform the desired operation but no return value. In this case, returnValueType is the keyword void .
  • Method name: is the actual name of the method. The method name and the parameter table together constitute the method signature.
  • Parameter type: The parameter is like a placeholder. When the method is called, pass the value to the parameter. This value is called an argument or variable. The parameter list refers to the method's parameter type, sequence, and number of parameters. The parameter is optional and the method can contain no parameters.
  • Method body: The method body contains concrete statements defining the function of the method.
Java Methods

Such as:
public static int age ( int birthday ) { ... }
Parameters can have more than one:
static float interest ( float principal , int year ) { ... }
Note: In some other languages, methods refer to procedures and functions. A method that returns a non-void return value is called a function; a method that returns a void return value is called a procedure.

Examples

The following method contains two parameters, num1 and num2, which return the maximum of these two parameters.
/* * Returns the larger value of two integer variable data */
public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

Method call

Java supports two ways to invoke methods, depending on whether the method returns a value.
When a program calls a method, the program's control is passed to the called method. The control is returned to the program when the returned statement of the called method is executed or when the method body closes the parenthesis.
When a method returns a value, the method call is usually treated as a value. E.g:
int larger = max ( 30 , 40 ) ;
If the method returns a value of 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 rookie tutorial! " ) ;

Example

The following example shows how to define a method and how to call it:

TestMax.java file code:

public class TestMax {
/** Main method */ public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( i + " and " + j + " For comparison, the maximum value is:" + k); } /** Returns the larger value of two integer variables */ public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }
}
The above example compiled and run results are as follows:
5 and 2 , the maximum value is: 5   
This program contains the main method and the max method. The main method is called by the JVM, except that the main method is no different from other methods.
The head of the main method is unchanged, as shown in the example, with the modifiers public and static, returning a void type value, the method name being main, and taking a String[] type parameter. String[] indicates that the argument is an array of strings.

Void keyword

This section shows how to declare and call a void method.
The following example declares a method named printGrade and calls it to print the given score.

Example

TestVoidMethod.java file code:

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 example compiled and run results are as follows:
C
Here the printGrade method is a void type method, it does not return a value.
A call to a void method must be a statement. Therefore, it is called as a statement in the third line of the main method. Just like any statement that ends with a semicolon.

Passing parameters by value

You need to provide parameters when calling a method. You must provide them in the order specified by the parameter list.
For example, the following method prints a message n times in succession:

TestVoidMethod.java file code:

public static void nPrintln(String message, int n) { for (int i = 0; i < n; i++) { System.out.println(message); } }

Example

The following example shows the effect of passing by value.
The program creates a method that is used to exchange two variables.

The TestPassByValue.java file code:

public class TestPassByValue { public static void main(String[] args) { int num1 = 1; int num2 = 2; System . out . println ( " The value of num1 before the exchange: " + num1 + " , the value of num2 is: " + num2 ) ; // call the swap method swap ( num1 , num2 ) ; System . out . println ( " The value of num1 after the exchange is: " + num1 + " , and the value of num2 is: " + num2 ) ; }


/* * The method of exchanging two variables */
public static void swap ( int n1 , int n2 ) {
System . out . println ( " \t Method entering swap " ) ; System . out . println ( " \t \t exchanged before n1 values: " + n1 + " , the value of n2: " + n2 ) ;
// value exchange n1 and n2, int temp = n1 ; n1 = n2 ; n2 = temp ; System . out . println ( " \t \t The value of n1 after the exchange " + n1 + " , the value of n2: " + n2 ) ; }
}
The above example compiled and run results are as follows:
The value of num1 before the exchange: 1 , the value of num2 is: 2
 	 Method entering swap 
 	 	 exchanged before n1 values: 1 , the value of n2: 2
 	 	 The value of n1 after the exchange 2 , the value of n2: 1
 The value of num1 after the exchange is: 1 , and the value of num2 is: 2
Pass two arguments to call the swap method. Interestingly, after the method was called, the value of the argument did not change.

Overload of methods

The max method used above applies only to int data. But what if you want to get the maximum value of two floating-point type data?
The solution is to create another method with the same name but different parameters, 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 the max method with int arguments, the max method of int arguments will be called;
If you pass a double argument, the max method's body of type double is called. This is called method overloading.
This means that two methods of a class have the same name, but have different parameter lists.
The Java compiler determines which method should be called based on the method signature.
Method overload can make the program more legible. Methods that perform closely related tasks should use the same name.
The overloaded method must have a different list of parameters. You can't just override the method depending on the modifier or return type.

Variable scope

The scope of a variable is the portion of the program that the variable can be referenced by.
Variables defined within a method are called local variables.
The scope of a local variable begins with the declaration and ends with the block that contains it.
Local variables must be declared before they can be used.
The method's parameter range covers the entire method. The parameter is actually a local variable.
The variable declared in the initialization section of the for loop has its scope of action throughout the loop.
But the variable declared in the body of the loop applies from its declaration to the end of the loop body. It contains the variable declarations shown below:

Variable scope in java

You can declare a local variable with the same name multiple times in different non-nested blocks in a method, but you cannot declare a local variable twice within the nested block.

Use of command line parameters

Sometimes you want to run a program and pass it a message. This depends on passing the command line arguments to the main() function.
The command line arguments are the information that follows the program name when executing the program.

Examples

The following program prints all the command line parameters:

CommandLine.java file code:

public class CommandLine { public static void main(String args[]){ for(int i=0; i<args.length; i++){ System.out.println("args[" + i + "]: " + args[i]); } }
}
Run this program as follows:
$ javac CommandLine.java 
$ java CommandLine this is a command line 200 -100
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100  

Construction method

When an object is created, the constructor is used to initialize the object. The constructor has the same name as the class it is in, but the constructor has no return value.
You usually use constructors to assign initial values to an instance variable of a class, or to perform other necessary steps to create a complete object.
Regardless of whether or not you customize the constructor, all classes have constructors because Java automatically provides a default constructor that initializes all members to 0.
Once you define your own constructor, the default constructor will fail.

Examples

Here is an example of using a constructor:
// A simple constructor Class MyClass {
int x ; // The following is the constructor MyClass ( ) {
x = 10 ; }
}
You can call an constructor like this to initialize an object:

ConsDemo.java file code:

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 requires a parameterized constructor.

Examples

Here is an example of using a constructor:
// A simple constructor Class MyClass {
int x ; // The following is the constructor MyClass ( int i ) {
x = i ; }
}
You can call an constructor like this to initialize an object:

ConsDemo.java file code:

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); } }
The operating results are as follows:
10 20 

variable parameter

Beginning with JDK 1.5, Java supports passing a variable parameter of the same type to a method.
The declaration of a variable parameter of a method is as follows:
typeName ... parameterName
In the method declaration, add an ellipsis (...) after the specified parameter type.
Only one variable parameter can be specified in a method. It must be the last parameter of the method. Any ordinary parameters must be declared before it.

Examples

VarargsDemo.java file code:

public class VarargsDemo { public static void main(String args[]) { // Method for calling varargs 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); } }
The above example compiled and run results are as follows:
The max value is 56.5                                                                The max value is 3.0  

Finalize() method

Java allows you to define a method that is called before the object is destroyed (recycled) by the garbage collector. This method is called finalize() and it is used to clear the recycled object.
For example, you can use finalize() to ensure that an object's open file is closed.
In the finalize() method, you must specify the operation to be performed when the object is destroyed.
The finalize() general format is:
protected void finalize ( ) { // End the code here }
The keyword protected is a qualifier that ensures that the finalize() method will not be called by code outside of this class.
Of course, Java's memory reclaim can be done automatically by the JVM. If you use it manually, you can use the above method.

Examples

FinalizationDemo.java file code:

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(); //Call the Java garbage collector } } 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 and the output is as follows:
$ javac FinalizationDemo . java
$ java FinalizationDemo Cake Object 1is created
 Cake Object 2is created
 Cake Object 3is created
 Cake Object 3is shipped
 Cake Object 2is disposed
          

Comments