Demo07.java 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package j1_java_basic.J20250525;
  2. /**
  3. * @author WanJl
  4. * @version 1.0
  5. * @title Demo07
  6. * @description
  7. * @create 2025/5/25
  8. */
  9. public class Demo07 {
  10. /*
  11. 没有参数、没有返回值的方法
  12. 输出hello world
  13. 没有参数 方法名后面的括号()里面是空的。调用方法的时候不需要传参数
  14. 没有返回值 方法前面的是void,表示没有返回值,也就不需要设置返回值类型。
  15. */
  16. public static void printHelloWorld(){
  17. System.out.println("hello world");
  18. }
  19. /*
  20. 有参数 需要在创建方法的时候,设置【形式参数】,在调用方法的时候需要传【实际参数】
  21. 没有返回值
  22. 输出n个hello world
  23. */
  24. public static void printHelloWorld2(int n){
  25. for (int i = 0; i < n; i++) {
  26. System.out.println("hello world");
  27. }
  28. }
  29. /*
  30. 没有参数
  31. 有返回值
  32. 定义一个方法,调用该方法会【返回】一个hello world
  33. 如果方法是带有返回值的,那么在调用该方法的时候,需要按照方法的返回值类型定义变量进行接收。
  34. */
  35. public static String getHelloWorld(){
  36. return "hello World";
  37. }
  38. /*
  39. 有参数
  40. 有返回值
  41. 定义一个加法运算的方法,传入两个整数,返回这两个整数的和
  42. */
  43. public static int add(int a,int b){
  44. int sum=a+b;
  45. return sum;
  46. }
  47. public static void main(String[] args) {
  48. printHelloWorld2(5);
  49. //调用了方法,需要接收方法运行后的返回值结果
  50. String h=getHelloWorld();
  51. System.out.println(h);
  52. int s = add(15, 7);
  53. System.out.println(s);
  54. }
  55. }