为什么Java中需要String [] args? [英] Why is String[] args required in Java?

查看:115
本文介绍了为什么Java中需要String [] args?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解String [] args是一个传递给main作为参数的字符串数组。

I understand that String[] args is an array of strings passed into main as parameters.

java Print "Hello, World!"

 

class Print {
  public static void main(String[] args) {
    System.out.println(args[0]);
  }
}

但是,当你不把它包括在内时参数(即使你不使用),它会抛出异常。那为什么需要呢?另外,为什么它不能是int []或boolean []?

However, when you don't include it as a parameter (even if you don't use), it throws an exception. So why is it required? Also, why can't it be an int[] or boolean[]?

推荐答案

这是一个String,因为命令行是用文字表达。如果要将该文本转换为整数或布尔值,则必须自己执行此操作 - 操作系统或Java引导程序将如何确切地知道您希望如何解析所有内容?我想Java 可以查找与命令行参数具有相同数量参数的main方法,然后尝试使用 Integer.parseInt 解析它们等...但这会非常复杂,在许多情况下仍然不够。

It's a String because the command line is expressed in text. If you want to convert that text into integers or booleans, you have to do that yourself - how would the operating system or Java bootstrapper know exactly how you wanted everything to be parsed? I suppose Java could look for a main method with the same number of parameters as command line arguments, and then try to parse them using Integer.parseInt etc... but this would be pretty complicated, and would still be inadequate in many situations.

至于它是强制性的 - 基本上Java设计师决定坚持单一方法签名,坦率地说比允许它是可选的更简单。但是有可能 - 在C#中,你可以拥有任何

As for it being mandatory - basically the Java designers decided to stick to a single method signature, which is frankly simpler than allowing for it to be optional. It would be possible though - in C#, you can have any of

static void Main()
static void Main(string[] args)
static int Main()
static int Main(string[] args)

说实话,最终并没有太大的区别。必须包含参数没有明显的缺点。

Ultimately it doesn't make a lot of difference, to be honest. There's no significant downside in having to include the parameter.

这篇关于为什么Java中需要String [] args?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆