How to invoke a function in Java?

To call a function in Java, you need to follow these steps:

  1. Create an object to invoke a function. If the function is static, you can directly use the class name to call the function, for example: ClassName.functionName()
  2. To call a function using the object name. If the function is non-static, you need to create the object first and then use the object name to call the function, for example: objectName.functionName().

When calling a function, be sure to pay attention to the following points:

  1. The parameters of the function must match the types and order of the parameters defined in the function.
  2. If a function returns a value, you can store the result of the function call in a variable or use the function call expression directly where the return value is needed.

Here is a simple example:

public class Example {
  
  // 定义一个静态函数
  public static void staticFunction() {
    System.out.println("This is a static function");
  }
  
  // 定义一个非静态函数
  public void nonStaticFunction() {
    System.out.println("This is a non-static function");
  }
  
  // 定义一个带参数的函数
  public void functionWithParameter(String name) {
    System.out.println("Hello, " + name);
  }
  
  // 定义一个带返回值的函数
  public int functionWithReturnValue(int a, int b) {
    return a + b;
  }
  
  public static void main(String[] args) {
    // 调用静态函数
    Example.staticFunction();
    
    // 创建对象
    Example example = new Example();
    
    // 调用非静态函数
    example.nonStaticFunction();
    
    // 调用带参数的函数
    example.functionWithParameter("Alice");
    
    // 调用带返回值的函数
    int result = example.functionWithReturnValue(2, 3);
    System.out.println("Result: " + result);
  }
}

The output is:

This is a static function
This is a non-static function
Hello, Alice
Result: 5
bannerAds