Search code examples
javamethodsreturn

JAVA how to print out array in main using a method?


So I need to create a method which would take ints and return an array of length 3 with those three ints as they have been input.

This is what I have created, but it returns this [I@7852e922

public class IntsToArray {
  public static int[] fill(int a, int b, int c){
      int[] array = new int[3];
      array[0] = a;
      array[1] = b;
      array[2] = c;
      return (array);
  }
    public static void main(String[] args){
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int c = Integer.parseInt(args[2]);
        int[] array = fill(a, b, c);
        System.out.println(array);
    }
}

What am I doing wrong?


Solution

  • If you want to print an array you should iterate over all of it's members and print each one. What you are doing at this moment is trying to print the array object which prints it's memory address uses the default toString() method of the object base class, as pointed out by bhspencer, to print the array.

    Try this:

    public class IntsToArray {
      public static int[] fill(int a, int b, int c){
          int[] array = new int[3];
          array[0] = a;
          array[1] = b;
          array[2] = c;
          return (array);
      }
        public static void main(String[] args){
            int a = Integer.parseInt(args[0]);
            int b = Integer.parseInt(args[1]);
            int c = Integer.parseInt(args[2]);
            int[] array = fill(a, b, c);
    
            for(int i = 0; i < array.length; i++)
            {
                System.out.println(array[i]);
            }
        }
    }