• Java基础


    调用方法时可以给该方法传递一个或多个值,传给方法的值叫实参,在方法内部,接收实参的变量叫做形参,形参的声明语法与变量的声明语法一样。形参只在方法内部有效。

    Java中方法的参数主要有3种,分别为值参数、引用参数和不定长参数

    值参数

    值参数表明实参与形参之间按值传递,当使用值参数的方法被调用时,编译器为形参分别存储单元,然后将对应的实参的值复制到形参中,由于是值类型的传递方式,所以在方法中对值类型的形参的修改并不会影响实参

     1 package mingri.chapter_6;
     2 
     3 public class Book {
     4 
     5     public static void main(String[] args) {
     6         Book book = new Book();
     7         int shelf = 30;
     8         int box = 40;
     9 
    10         System.out.println("把书架上的书全部放进箱子后,箱子里一共有"
    11                 + book.add(shelf, box) + "本书。
    明细如下:书架上"
    12                 + shelf + "本书,箱子里原有" + box + "本书"
    13         );
    14     }
    15 
    16     private int add(int shelf, int box) {
    17         box += shelf;
    18         return box;
    19     }
    20 }

    引用参数

    如果在给方法传递参数时,参数的类型是数组或者其他引用类型,在方法中对参数的修改会反应到原有的数组或者其他引用类型上,这种类型的方法参数被称之为引用参数

     1 package mingri.chapter_6;
     2 
     3 public class ExchangeRate {
     4 
     5     public static void main(String[] args) {
     6         ExchangeRate rate = new ExchangeRate();
     7         double[] denomination = {1, 10, 100};   // 定义一个一维数组,用来存储纸币面额
     8 
     9         // 输出三种面值的美元金额
    10         System.out.println("美元:");
    11         for (int i = 0; i < denomination.length; i++) {
    12             System.out.println(denomination[i] + "美元 ");
    13         }
    14 
    15         // 传入一个引用参数
    16         rate.chage(denomination);
    17         // 输出与三种面值的美元等值的人民币
    18         System.out.println("
    人民币:");
    19         for (int i = 0; i < denomination.length; i++) {
    20             System.out.println(denomination[i] + "元");
    21         }
    22 
    23     }
    24 
    25     public void chage(double[] i) {
    26         // 接收的引用参数,修改引用参数中的值后,会改变传入进来的引用参数
    27         for (int i1 = 0; i1 < i.length; i1++) {
    28             i[i1] = i[i1] * 6.903;
    29         }
    30     }
    31 }

    不定长参数

    声明方法时,如果有若干个相同类型的参数,可以定义为不定长参数

     1 package mingri.chapter_6;
     2 
     3 public class demo {
     4 
     5     public static void main(String[] args) {
     6         demo dm = new demo();
     7         int result = dm.add(20, 30, 40, 50);
     8         System.out.println("result -->" + result);
     9     }
    10 
    11 
    12     int add(int... x) {
    13         int result = 0;
    14         for (int i = 0; i < x.length; i++) {
    15             result += x[i];
    16         }
    17 
    18         return result;
    19     }
    20 }
  • 相关阅读:
    动画差值
    高达模型
    TCP/IP负载均衡
    FreeImage使用
    Game Programming Pattern
    Apple Instruments
    GLEW OpenGL Access violation when using glGenVertexArrays
    微服务了解
    summary
    事务传播行为
  • 原文地址:https://www.cnblogs.com/CongZhang/p/9942238.html
Copyright © 2020-2023  润新知