21xrx.com
2025-04-09 14:29:37 Wednesday
文章检索 我的文章 写文章
Java中的return语句:如何使用返回值
2023-06-18 14:58:52 深夜i     18     0
Java return 返回值

在Java编程中,使用return语句是很常见的。它的作用是将程序执行的控制权返回给调用它的方法,并可携带一个返回值。

在下面的代码示例中,我们演示了如何使用return语句来返回不同类型的值,包括int、String和boolean类型。

public class ReturnExample {
  public static void main(String[] args) {
    int a = 10;
    int b = 20;
    int result = sum(a, b);
    System.out.println("The sum of " + a + " and " + b + " is " + result);
    String str = concatenate("Hello", "World");
    System.out.println("The concatenated string is: " + str);
    boolean flag = check(a, b);
    if (flag) {
      System.out.println("a is greater than b");
    } else {
      System.out.println("b is greater than a");
    }
  }
  public static int sum(int x, int y) {
    int z = x + y;
    return z;
  }
  public static String concatenate(String s1, String s2) {
    String s3 = s1 + " " + s2;
    return s3;
  }
  public static boolean check(int x, int y) {
    if (x > y)
      return true;
     else
      return false;
    
  }
}

  
  

评论区

请求出错了