Latest web development tutorials

Java 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 ().

So what is the way to do that?

Java method is set of statements which together perform a function.

  • The method is an ordered combination to solve a class of problems step
  • Methods included in the class or object
  • The method was created in the program, referenced elsewhere

Defined methods

In general, the definition of a method comprising the following syntax:

修饰符 返回值类型 方法名 (参数类型 参数名){
    ...
    方法体
    ...
    return 返回值;
}

The method includes a method header and a method body. Here are all part of a process:

  • Modifier: modifier, which is optional, to tell the compiler how to call the method. It defines the access type of the method.
  • Return Value Type: method might return value. returnValueType is a method returns the data type of the value. Some methods perform the desired action, but no return value. In this case, returnValueType keyword void.
  • Method name: the actual name of the method. Method name and parameter list together constitute the method signature.
  • Parameter Type: parameter like a placeholder. When the method is called, the value passed to the parameter. This value is called the argument or variable. Parameter list is the number of parameter type of the method, the order and parameters. Parameter is optional, the method may not contain any parameters.
  • Method Body: The method comprises a specific statement to define the function of the method.

Such as:

public static int age(int birthday){...}

You can have more than one parameter:

static float interest(float principal, int year){...}

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.

Examples

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; 
}

Method Invocation

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!");

Example

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.


Keyword void

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.

Example

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.


Passing parameters by value

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);
}

Example

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.


Overloaded methods

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.


Variable Scope

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.

Using the command line parameters

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.

Examples

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

Construction method

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.

Examples

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.

Examples

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

Variable parameter

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... parameterName

In the method statement, the specified parameter type after adding an ellipsis (...).

A method can specify only one variable parameter, it must be the last parameter method. Any common parameters must be declared before it.

Examples

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... 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

finalize () method

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.

Examples

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