zoukankan      html  css  js  c++  java
  • java语言中的varargs

    java语言中的varargs允许调用者传递数量不定的参数,并传入的数量不定的实参转化为数组形式的形参。

    那么不传递任何参数,或者传入null时,形参的值是什么呢?下面是测试代码和运行结果:

     1     private void test1(int... args) {
     2         if (args != null) {
     3             System.out.println("[test1] args.length = " + args.length);
     4         } else {
     5             System.out.println("[test1] args is null");
     6         }
     7     }
     8 
     9     private void test2(String... args) {
    10         if (args != null) {
    11             System.out.println("[test2] args.length = " + args.length);
    12         } else {
    13             System.out.println("[test2] args is null");
    14         }
    15     }
    16 
    17     public void static main(String[] args) {
    18         test1();
    19         test1(null);
    20         test1(1);
    21         test1(1,2);
    22 
    23         test2();
    24         test2(null);
    25         test2("1");
    26         test2("a", "b");
    27     }

    [test1] args.length = 0
    [test1] args is null
    [test1] args.length = 1
    [test1] args.length = 2
    [test2] args.length = 0
    [test2] args is null
    [test2] args.length = 1
    [test2] args.length = 2

    结论:

    1. 如果不传参数,那么形参的值是长度为0的数组。
    2. 如果传入null,那么形参的值是null,但是编译时会有警告提示。
  • 相关阅读:
    作业07-Java GUI编程
    作业06-接口、内部类
    作业05-继承、多态、抽象类与接口
    作业14-数据库
    作业13-网络
    作业12-流与文件
    作业11-多线程
    作业10-异常
    作业09-集合与泛型
    作业08-集合
  • 原文地址:https://www.cnblogs.com/mopno1/p/7505666.html
Copyright © 2011-2022 走看看