Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is Java reference is not working like expected in this Program
    primarykey
    data
    text
    <p>I was working in a problem and I found that Java references are not working as I expect it to. Ofcourse, I am the culprit :), can someone please me why the following happens. Let me first post the code here.</p> <pre><code>package misc.matrix; public class ReferenceTester { public static void main(String args[]){ Boolean[][] input = { {true ,false ,true ,true ,false }, {false ,true ,true ,true ,true }, {true ,true ,true ,true ,true }, {true ,true ,true ,true ,true }, {true ,false ,true ,true ,true } }; print(input); for(Boolean[] eachRow:input){ for(Boolean eachVal:eachRow){ eachVal = Boolean.TRUE; } } print(input); /*Expected output true true true true true true true true true true true true true true true true true true true true true true true true true */ } /** * Simply prints the array */ private static void print(Boolean[][] input) { for(Boolean[] outArray:input){ for(Boolean iVal:outArray){ System.out.print(iVal?iVal+" ":iVal+" "); } System.out.println(); } } } </code></pre> <p>If you take a look at the above program, all I am trying to do is to change all the values in the Array to true and print it. But its simply prints the input again. Can someone please tell me why is this. Initially I had used the primitive boolean in the program, but since I dont want to create copies, I used the wrapper Boolean Class which is a Java OBJECT as opposed to primitives. (Isnt eachVal a JAVA OBJECT!?!?!?!?) Why is this happening in Java. Why did it not print all the values to be true?</p> <p>Please advise.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload