Java error: Exception in thread "main" java.lang.Arrayindexoutofboundsexception: 0

Asked

Viewed 313 times

0

I am starting to learn java and in my simple code input arguments in the program is giving the error:

Exception in thread "main" java.lang.Arrayindexoutofboundsexception: 0

This is my code:

public class Saudacao {

  public static void main(String[] args) {
      System.out.println("Saudacao, " + args[0]);       
  }
}

1 answer

1


This type of exercise is usually performed via the command line (cmd, powershell, bash, etc).

In the command line, after compiling the class you would do as an example:

java Saudacao Gianluca

And the result on the command line would be:

Saudacao, Gianluca

At runtime the virtual machine searches for content in the first index of the args array.
Since you have not passed any argument the virtual machine creates an Array of size 0.
Since there are no elements, there is no index 0 and when trying to access launches an Exception.

  • Right, I went to the terminal in my virtual machine and gave everything right, thank you. But... how do I do in Vscode? right in windows, you can tell me?

  • Top: Terminal ~> New Terminal. At the bottom will open the terminal. (:

  • Show, helped a lot, abs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.