-2

I am new to java. My code is:

public class Hi {
        public static void main(String[] args) {
        System.out.print("Hi, ");
        System.out.print(args[2]);
        System.out.print(",");
        System.out.print(args[1]);
        System.out.print(", and");
        System.out.print(args[0]);
        System.out.println(".");
    }
}

I get the following exception upon running this program:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Hi.main(Hi.java:5)

I would be glad to know why I had got this exception and how to resolve it.

6
  • 1
    You forgot to ask a question. And what command-line args have you passed in? Commented Jun 27, 2014 at 10:27
  • what are you passing while executing your program Commented Jun 27, 2014 at 10:27
  • Like, java hi any_arguments? Commented Jun 27, 2014 at 10:28
  • java Hi Mango Orange Banana Commented Jun 27, 2014 at 10:30
  • 4
    if (args.length < 3) chastiseUser(); Commented Jun 27, 2014 at 10:31

3 Answers 3

0

You are passing parameters which is less than 3, thats why you are getting this error.

try like below command,

java hi test test test

Sign up to request clarification or add additional context in comments.

Comments

0

Either you dint passed command line arguments while executing the program or args.length < 3

Comments

0

You would have got this exception if you had tried to run this program providing 2 or fewer arguments.

  • args[0] will be the first index of the array.
  • args[1] will be the second index.
  • args[2] will be the third index of the array.

This is because array index starts with 0 and ends with n-1 for arrays in Java. (n is the size of the array).

Command line way

This program will run fine, if you run the program as java Hi Demo Test Argument

Here Demo is at args[0], Test is at args[1] and Argument is at args[2].

Using Eclipse IDE

  • Right click on the class file.
  • Select Run As and select Run Configurations
  • Double Click on Java Application
  • Go to the Arguments tab and provide three arguments in the Program Arguments textarea separated by spaces as shown in the image below. enter image description here
  • Now click on Apply and then on Run

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.