搜索

Java: Methods


发布时间: 2022-11-25 03:07:00    浏览次数:70 次
public class Main {
  static void myMethod() {
    System.out.println("I just got executed!");
  }

  public static void main(String[] args) {
    myMethod();
  }
}

// Outputs "I just got executed!"

Parameters and Arguments

When a parameter is passed to the method, it is called an argument. So, from the example above: fname is a parameter, while LiamJenny and Anja are arguments.

public class Main {
  static void myMethod(String fname) {
    System.out.println(fname + " Refsnes");
  }

  public static void main(String[] args) {
    myMethod("Liam");
    myMethod("Jenny");
    myMethod("Anja");
  }
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes

 

Method Overloading

With method overloading, multiple methods can have the same name with different parameters:

int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)

 

Variables declared directly inside a method

public class Main {
  public static void main(String[] args) {

    // Code here CANNOT use x

    int x = 100;

    // Code here can use x
    System.out.println(x);
  }
}

 

Recursion

public class Main {
  public static void main(String[] args) {
    int result = sum(10);
    System.out.println(result);
  }
  public static int sum(int k) {
    if (k > 0) {
      return k + sum(k - 1);
    } else {
      return 0;
    }
  }
}

 

免责声明 Java: Methods,资源类别:文本, 浏览次数:70 次, 文件大小:-- , 由本站蜘蛛搜索收录2022-11-25 03:07:00。此页面由程序自动采集,只作交流和学习使用,本站不储存任何资源文件,如有侵权内容请联系我们举报删除, 感谢您对本站的支持。 原文链接:https://www.cnblogs.com/ShengLiu/p/16924022.html