Please tell me the simplest way to print out an array.

Asked 2 years ago, Updated 2 years ago, 114 views

You are trying to output the array without overriding the toString(). A strange value was printed.

    int[] intArray = new int[] {1, 2, 3, 4, 5};
    System.out.println(intArray); //'[I@3343c8b3' <- This is the value 

What I want is [1,2,3,4,5]. How can I print it out like the code below?

    // array of primitives:
    int[] intArray = new int[] {1, 2, 3, 4, 5};
    //output: [1, 2, 3, 4, 5]

    // // array of object references:
    String[] strArray = new String[] {"John", "Mary", "Bob"};
    //output: [John, Mary, Bob]

java array printings

2022-09-22 08:46

1 Answers

If you look at Java 5, there are methods such as Arrays.toString(arr) or Arrays.deepToString(arr). But I'm not going to override to StringSo if you use deepToString,

Don't forget to import first.

    package packageName;
    import java.util.Arrays;

Please do that.

 *// Initialize array
    int[] intArray = new int[] {1, 2, 3, 4, 5};
    *// Write the code below when you want to print out all the elements*
    System.out.print (*Arrays.deepToString*);
    *//output results for intArray: [1, 2, 3, 4, 5]*

    *// Initialize object array:*
    String[] strArray = new String[] {"John", "Mary", "Bob"};
    *// Write the code below when you want to print out each string*
    System.out.print(Arrays.toString (*array name to output*));
    *//trArray output: [John, Mary, Bob]*

You can do it.


2022-09-22 08:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.