Java method 02 -- method definition and calling, method overloading, command line parameter passing, variable parameters

Java method 02 -- method definition and calling, method overloading, command line parameter passing, variable parameters

Definition of method

  • Java methods are similar to functions in other languages. They are code fragments used to complete specific functions. Generally, defining a method includes the following syntax:

  • Method contains a method header and a method body. Here are all parts of a method:

    • Modifier: modifier, which is optional and tells the compiler how to call the method. Defines the access type of the method. public static

    • Return value type: a method may return a value. returnValueType is the data type of the return value of the method. Some methods perform the required operation but do not return a value. In this case, returnValueType is the keyword void.

    • Method name: is the actual name of the method. The method name and parameter table together constitute the method signature. (hump naming)

    • Parameter type: the parameter is like a placeholder. When a method is called, a value is passed to the parameter. This value is called an argument or variable. Parameter list refers to the parameter type, order and number of parameters of a method. Parameters are optional, and methods can contain no parameters.

      • Formal parameter: used to accept external input data when a method is called.
      • Argument: the data actually passed to the method when the method is called.

    • Method body: the method body contains specific statements that define the function of the method.

Modifier return value type method name (parameter type parameter name){
    Method body
    return Return value;
package com.studyhao1999.method;

public class Demo02 {
    public static void main(String[] args) {
        int max=max(10,10);

    //Specific size
    public static int max(int num1,int num2){
        int result=-1;//The result needs to be initialized here without any error
        if (num1==num2){
            return 0;//Termination method
            result=num1;//You cannot write return num1 directly. Use result to accept it;
        return result;

Method call

  • Calling method: object name. Method name (argument list)

  • Java supports two methods of calling methods, which are selected according to whether the method returns a value

  • When a method returns a value, the method call is usually treated as a value. For example:

    int larger =max(30,40);
  • If the return value of the method is void, the method call must be a statement.


Value passing (Java) and reference passing


  • Value Passing: passing real values
  • Reference passing: passing memory addresses
  1. Basic type
public class ValueTest{
    public static void main(String[] args){
        int a=10;
    public static void changVal(int a){

The demo above outputs 10 instead of 20. Why?

  • When the program is running, the main method first enters the stack, and then allocates memory to variable a.

  • When running to changeVal(a); The changeVal() method is pushed into the stack. When the method is stacked, memory is allocated to local variables and formal parameter variables (a)

That is, in the changeVal method stack, there is also a variable named a with a value of 10.

  • Because a+=10; It runs in the changeVal method stack, so only the a value in the changeVal method stack will be changed, not the a value in the main method stack. As shown below

  1. String test
public class ValueTest{
    public static void main(String[] args){
        StringBuilder builder = new StringBuilder("hello");
    public static void changVal(StringBuilder builder){
        builder.append(" world");
  • The output is hello world. It can be seen that the builder value has changed
  • Unlike basic types, StringBuilder is mainly a reference type. Therefore, the memory of new StringBuilder("hello") is allocated in the heap. The variable (builder) in the stack area only saves one address (assumed to be 0x345), as shown in the following figure:

Therefore, the builder variables of the main and changeVal method stacks point to the same block of memory. Therefore, when the value of builder is changed in the changeVal method, the builder in main will also change.

  1. Str test
public class ValueTest{
    public static void main(String[] args){
        String str = "hello";
    public static void changVal(String str){
       str+=" world";
  • The above demo output is: hello, not hello world. str records the address of the object, so the value of str should also be changed?

  • This is related to the "characteristics" of string. String will be stored in the string constant pool, and string cannot be changed (final)

① . set a breakpoint in line 10. When you reach this line, the above analysis shows that str in the main() and changeVal() methods point to the "hello" string in the constant pool.

② . when STR + = "world" is executed, because String is immutable, it is impossible to directly modify "hello". At this time, a String of "hello world" will be added to the constant pool, and the address will be passed to str

③ Therefore, str in changeVal() method points to the newly added "hello world" string, while str in main method still points to the original "hello". So output "hello"

Method overload

  • Overloading is a function with the same function name but different formal parameters in a class
  • Overload rule for method:
    • Method name must be the same;
    • The parameter list must be different (different number, different type, different parameter arrangement order, etc.);
    • The return types of methods can be the same or different;
    • Just different return types are not enough to overload methods.
  • Realization theory;
    • If the method names are the same, the compiler will match them one by one according to the number of parameters and parameter types of the calling method to select the corresponding method. If the matching fails, the compiler will report an error.

Command line parameters

  • Sometimes you want to pass messages to a program when you run it. This is achieved by passing command-line arguments to the main() function.
public class CommandLine{
    public ststic void main(String args[]){
        for(int i=0;i<arg.length;i++){
  • If you run the file directly after compiling in the directory folder, an error will be reported:

  • Solution: use cd.. / to fallback to the src directory, and then run through Package

Variable parameters

  • Starting with JDK 1.5, Java supports passing variable parameters of the same type to a method.

  • In the method declaration, add an ellipsis (...) after specifying the parameter type.

  • A method can only specify variable parameters to spoof. It must be the last parameter of the method, and any ordinary parameters must be declared before it.

package com.studyhao1999.method;

public class Demo04 {
    public static void main(String[] args) {
        //Calling methods with variable parameters
        Demo04 demo04 = new Demo04();
    public void test(int...i){

Example: sorting

package com.studyhao1999.method;

public class Demo04 {
    public static void main(String[] args) {
        //Calling methods with variable parameters
        printMax(new double[]{1,2,3});
    public static void printMax(double...numbles){
        if (numbles.length==0){
            System.out.println("No argument passed");
        double result = numbles[0];

        for (int i = 1; i <numbles.length ; i++) {
            if (numbles[i]>result){
                result =numbles[i];
        System.out.println("The max value is "+result);

Tags: Java

Posted on Fri, 03 Dec 2021 16:50:14 -0500 by gj6kings