2 Replies - 307 Views - Last Post: 19 December 2013 - 11:26 PM Rate Topic: -----

#1 burakaltr  Icon User is offline

  • D.I.C Regular

Reputation: 92
  • View blog
  • Posts: 276
  • Joined: 07-November 10

args re-defined

Posted 19 December 2013 - 07:51 PM

public class Test {

	public Test() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
    args[0]="main";
    System.out.println(args[0]);
    String a[]=new String[]{"ss"};
		Main(a);
	}
    public static void Main(String[] args){
        args[0]="Main";
        System.out.println(args[0]);

    	}
}



Hello.

Why Cannot I set in the main args[] values and request to print them to get

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Test.main(Test.java:10)

But in the Similar Main, I can do it?

Thanks in Advance for your Input.

Is This A Good Question/Topic? 0
  • +

Replies To: args re-defined

#2 floppyspace  Icon User is offline

  • D.I.C Regular

Reputation: 48
  • View blog
  • Posts: 254
  • Joined: 04-February 10

Re: args re-defined

Posted 19 December 2013 - 08:45 PM

someone else will probably explain this better, but the args array contains nothing, if you were to give it a value then it would have something to print, eg

public class printMainFromArgs
{
   public static void main(String args[]) {

      System.out.print("main");

      for (int i = 0 ; i < args.length ; i++)
         System.out.print(" " + args[i]);

      System.out.println();
   }
}


interested to see what the pros have to say : )
Was This Post Helpful? 0
  • +
  • -

#3 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 8029
  • View blog
  • Posts: 13,741
  • Joined: 19-March 11

Re: args re-defined

Posted 19 December 2013 - 11:26 PM

If you ran this as

$ java Test foo


it should work fine. If you run it as

$ java Test

it'll fail as you say because the args array is empty. Specifically it's an array of length zero, so element 0 does not exist, so it cannot be assigned a value.

You'll notice that you can do

Quote

args = {"foo", "bar", "baz"};


and if you do this, your

args[0]="main";



should work fine after it. (since now there's an element args[0] to work on)
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1