有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是args[0],args[1]变量吗?

我有这样的代码:

public class Hi
{
  public static void main(String args[])
  {
    ...
  }
}

如果我输入下面的“java Hi String1 String2”,那么有多少个对象

正确答案是:

对象:3:“String1”对象,“String2”对象,args指定的数组点

变量:4:args,“String1”,“String2”,args的数组点

我的问题是:

如果我能将变量计数中的“String1”和“String2”视为args[0]和args[1]?(这意味着args[0]和args[1]是变量。)

如果代码是

int a[2]={0};

我知道有1个数组对象和2个变量(a,数组对象),但由于Java中的字符串是特殊的,我想知道我是否必须接受“String1”和“String2”,或者我可以接受args[0]和args[1]作为变量,如下所示

对象:3:“String1”对象,“String2”对象,args指定的数组点

变量:4:args,args[0],args[1],按args排列的数组点


共 (1) 个答案

  1. # 1 楼答案

    TL;DR简短回答:是的,args[0]args[1]是变量


    根据JLS4.12.3. Kinds of Variables,有8种变量。其中,您的代码使用了其中3个:

    1. An instance variable is a field declared within a class declaration without using the keyword static (§8.3.1.1).

      If a class T has a field a that is an instance variable, then a new instance variable a is created and initialized to a default value (§4.12.5) as part of each newly created object of class T or of any class that is a subclass of T (§8.1.4). The instance variable effectively ceases to exist when the object of which it is a field is no longer referenced, after any necessary finalization of the object (§12.6) has been completed.

    2. Array components are unnamed variables that are created and initialized to default values (§4.12.5) whenever a new object that is an array is created (§10 (Arrays), §15.10.2). The array components effectively cease to exist when the array is no longer referenced.

    3. Method parameters (§8.4.1) name argument values passed to a method.

      For every parameter declared in a method declaration, a new parameter variable is created each time that method is invoked (§15.12). The new variable is initialized with the corresponding argument value from the method invocation. The method parameter effectively ceases to exist when the execution of the body of the method is complete.


    当你运行java Hi String1 String2时,你会得到:

    • 3个目标:

      • String[2](数组)
      • "String1"(字符串)
      • "String2"(字符串)
    • 4个变量1

      • args(方法参数)
      • args.length(实例变量)
      • args[0](数组组件)
      • args[1](数组组件)

    请注意,如果您创建了一个String[2]并且没有为数组组件赋值(即,将其null),那么您只有一个对象,但仍然有4个变量

    1)不计算String对象内的私有字段(实例变量)


    int a[2]={0};是无效代码,将无法编译

    使用初始值设定项时,不能指定数组大小,因为这在初始值设定项中是隐式的

    此外,您应该始终将[]数组声明为类型的一部分,而不是名称的一部分。用名称指定[]是从C语言继承下来的,非常不推荐

    正确的声明是:

    int[] a = { 0 };
    

    也就是说:

    • 1.目标:

      • int[1](数组)
    • 3个变量:

      • a(局部变量,种类#8)
      • a.length(实例变量)
      • a[0](数组组件)