Michael DeMarco
Michael DeMarco

Reputation: 19

Getting weird result when returning an array of boolean values

How do I write a method with a void return value that inverts all the elements of a two-dimensional array of booleans (true becomes false and false becomes true) that includes code to test your method. The output should show all the values of the array prior to inverting them and afterwards.

Now I have the code complete but when I go to use System.out.println to display the array, I'm getting some strange values popping up in the answer. Can anybody help me out. Here is the code:

public class TF
{
   public static void main(String[] args)
{
   boolean [][] bArray = {{false,false,true},{true,false,true}};

   System.out.println("This is before: " + bArray);

   for(int i = 0; i > bArray.length; i++)
   {
     for(int j = 0; j < bArray[i].length; i++)
     {
        bArray[i][j] = !(bArray[i][j]);
     }//endfor(j)
    }//endfor(i)

    System.out.println("This is after: " + bArray);
}//endmain
}//end TF

And this is the returntype I'm getting:

This is before: [[Z@69ed56e2
This is after: [[Z@69ed56e2

Anyone have any idea why I'm getting this?

Upvotes: 0

Views: 1485

Answers (2)

Shashank
Shashank

Reputation: 13869

In Java, when you try to convert an array to a String, you will get the array's zero-indexed address so that's why you are seeing mumbo-jumbo printed to the console.

To print out the values within in array, use a for loop that is capped on the array's .length property (this is built into all Java arrays so you don't need to worry about it):

for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}

To print out the contents of a 2-dimensional array in a visually pleasing format, you can use this code I wrote or do something similar:

// "Pretty print" 2D array
System.out.print("[");
for (int i = 0; i < bArray.length; i++) {
    System.out.print("[");
    for (int j = 0; j < bArray[i].length; j++) {
        System.out.print(bArray[i][j] + ((j < bArray[i].length - 1) ? ", " : ""));
    }
    System.out.print("]" + ((i < bArray.length - 1) ? ", " : ""));
}
System.out.println("]");

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201437

Yes. Arrays are Object(s) and inherit (but do not Override) Object.toString() and the javadoc says (in part)

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())

Instead you might use Arrays.deepToString(Object[]) like

System.out.println("This is before: " + Arrays.deepToString(bArray));

Also,

for(int j = 0; j < bArray[i].length; i++)

should be

for(int j = 0; j < bArray[i].length; j++)

Upvotes: 0

Related Questions