fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10.  
  11. public static void main (String[] args) throws java.lang.Exception
  12. {
  13. Demo demo1 = new Demo();
  14. demo1.changeReference();
  15.  
  16. Demo demo2 = new Demo();
  17. demo2.changeInsideObject();
  18. }
  19. }
  20.  
  21. class Demo {
  22. private int[][] table = {{1,2,3}, {4,5,6}};
  23.  
  24. public void changeReference() {
  25. int[][] tab = table;
  26.  
  27. // this will change table to [[4,4,4]]. But since the original reference is copied into tab, tab will keep the original values.
  28. doChange();
  29. System.out.println("tab after reassigning:");
  30. System.out.println(Arrays.deepToString(tab));
  31. }
  32.  
  33.  
  34. public void changeInsideObject() {
  35. int[][] tab = table;
  36.  
  37. // This directly modifies table contents, and they get reflected into tab because the reference points to the same object
  38. doChange2();
  39. System.out.println("tab after changing inside element:");
  40. System.out.println(Arrays.deepToString(tab));
  41. }
  42.  
  43. private void doChange() {
  44. table = new int[][] {{4,4,4}};
  45. }
  46.  
  47. private void doChange2() {
  48. table[0][0] = 12;
  49. }
  50. }
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
tab after reassigning:
[[1, 2, 3], [4, 5, 6]]
tab after changing inside element:
[[12, 2, 3], [4, 5, 6]]