0

All I'm trying to do is print the elements in a boolean array. But instead of getting the values of the elements which are either true or false, I get a weird output like this [Z@4517d9a3. I have read about the toString but this applies to string arrays. Here is my code :

public class Class{


    public static void main(String[] args) {
        
        boolean a[] =  {true, false, true, false};
        boolean[] x = show(a);
        System.out.println(x);

    }
    
    public static boolean[] show(boolean a[]) {
        
        return a;
    }
}
Filzzo
  • 19
  • 4
  • 1) Your `show()` method does nothing. `System.out.println(x);` is the same as `System.out.println(a);`. 2) To print the array, you first need to turn it into a string. See [`Arrays#toString()`](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/Arrays.html#toString(boolean%5B%5D)). What you're getting right now is the default implementation of the `toString()` method, which includes the type of the object (`[` means it's an array and `Z` indicates primitive booleans), followed by an `@` symbol, followed by the hash code for that particular object (`4517d9a3` in your case) – Charlie Armstrong Mar 02 '21 at 16:45
  • `public static String show(boolean a[]) { return Arrays.toString(a); }` but calling `Arrays.toString()` directly is more adequate IMO (and the name `show` is a bit confusing here) –  Mar 02 '21 at 16:57

1 Answers1

1

You can use the Arrays.toString method according to its documentation:

Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by String.valueOf(boolean). Returns "null" if a is null.

You can print your boolean array like this:

boolean a[] =  {true, false, true, false};
System.out.println(Arrays.toString(a)); //<-- [true, false, true, false]
dariosicily
  • 4,239
  • 2
  • 11
  • 17