0

I am coding a server-client java program. The code was supposed to be running on command prompt after server run of java server as:

Client user

Where client is the name of the user which will be passed to args[0]. In order to take care of the situation where user did not pass the username, I want to initiate a name as anonymous. But the following code did not work and keeps giving ArrayIndexOutOfBoundException error.

    if(args == null || args.length == 0)
    {
        args[0] = "anonymous";
    }

Any suggestion?

Philippe Boissonneault
  • 3,949
  • 3
  • 26
  • 33
user893970
  • 889
  • 6
  • 17
  • 28

3 Answers3

3

You are trying to change an element of an array that's guaranteed to either be null or empty.

One way to sidestep this is by using a separate variable:

String name = "anonymous";
if (args != null && args.length > 0) {
    name = args[0];
}
// use name
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

You can not assign a value to null, nor can you assign a value to an array that has length 0. Thus, args[0] = "anonymous" will throw an ArrayOutOfBounds exception if the args.length == 0

Marv
  • 3,517
  • 2
  • 22
  • 47
0

You need to re-initialize it.

if(args != null && args.length > 0) {
    args = new String[]{"anonymous"};
}

Note: Although it solves the issue, I would use @NPE's solution.

BackSlash
  • 21,927
  • 22
  • 96
  • 136