shantz
shantz

Reputation: 25

Calculate length of first argument in java

I want to print the length of the first argument(args[0]) but getting ArrayOutOfBountException :

public class Main {
    public static void main(String[] args){
        args[0] = "Hello";
        System.out.println(args[0].length());

    }
}

Exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at Main.main(Main.java:3)

Upvotes: 2

Views: 730

Answers (4)

Sumit Desai
Sumit Desai

Reputation: 1770

You need to check first if an argument is even present.If there is no argument passed and you try to access any element, it will throw ArrayIndexOutOfBoundsException. Also, you should avoid assign any hardcoded value to the elements in array. The code to access 1st element can be something like below:-

if(args.length>0){
 System.out.println(args[0].length());
 }

Upvotes: 0

Dushyant Tankariya
Dushyant Tankariya

Reputation: 1454

When you write the code,

public class Main {
    public static void main(String[] args){
        args[0] = "Hello";
        System.out.println(args[0].length());

    }
}

At this point args[0]="Hello";, If your args a String array is not initialized then, while execute I'm supposed to think that you may have used the command in such a way java Main to execute your basic program.

Which cause the error, You have not passed any argument through command line so your String[] args is not initialized yet and it is not able to store your String "Hello" inside array args[0] and you are trying to print an empty array and throw the Exception

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at Main.main(Main.java:3)

Update Answer:
Now Yes, You can use that to verify the String args length before print.

public class Main {
    public static void main(String[] args){
        if(args.length !=0){
           System.out.println(args[0].length());
        }else{
          args = new String[1]; //Initilize first
          args[0] = "Hello";    //Store value in array element 
          System.out.println(args[0].length()); //Print it.
        }  
    }
}

Upvotes: 2

Bam
Bam

Reputation: 151

Here array of String does not have any initialized objects and args has 0 element. That's why it is recommended to check whether does args have any element or not. Then, proceed further accordingly. This is how code looks like.

 public class Main {
public static void main(String[] args){
    if(args.length !=0){
       // do something
    }else{
      // args doesn't have element.
      return ;
  }  
}
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201477

First, check if there is an argument. Then print the length. It's not a good idea to change the values in the argument array either. Something like

if (args.length > 0) {
    System.out.println(args[0].length);
} else {
    System.out.println(0);
}

should do it.

Upvotes: 1

Related Questions