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;
    }
}
2
  • 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(). 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) Commented Mar 2, 2021 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) Commented Mar 2, 2021 at 16:57

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.