21xrx.com
2024-09-20 00:03:43 Friday
登录
文章检索 我的文章 写文章
Java中的return语句:如何使用返回值
2023-06-18 14:58:52 深夜i     --     --
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;

    

  }

}

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复