Java variables updating after void method [duplicate] Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Is Java “pass-by-reference” or “pass-by-value”?Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Fastest way to determine if an integer's square root is an integerHow do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I pass a variable by reference?Does Java support default parameter values?How do I convert a String to an int in Java?Creating a memory leak with Java

Is the time—manner—place ordering of adverbials an oversimplification?

Inverse square law not accurate for non-point masses?

Marquee sign letters

How can I prevent/balance waiting and turtling as a response to cooldown mechanics

Does a random sequence of vectors span a Hilbert space?

Where did Ptolemy compare the Earth to the distance of fixed stars?

Is this Half-dragon Quaggoth boss monster balanced?

What is the music which plays over the closing credits of Fleabag series 2 episode 2?

Why do C and C++ allow the expression (int) + 4*5;

An isoperimetric-type inequality inside a cube

malloc in main() or malloc in another function: allocating memory for a struct and its members

New Order #6: Easter Egg

French equivalents of おしゃれは足元から (Every good outfit starts with the shoes)

One-one communication

Any stored/leased 737s that could substitute for grounded MAXs?

Should man-made satellites feature an intelligent inverted "cow catcher"?

Calculation of line of sight system gain

How does the body cool itself in a stillsuit?

.bashrc alias for a command with fixed second parameter

NIntegrate on a solution of a matrix ODE

Where and when has Thucydides been studied?

Is there a spell that can create a permanent fire?

Short story about astronauts fertilizing soil with their own bodies

How to achieve cat-like agility?



Java variables updating after void method [duplicate]



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Is Java “pass-by-reference” or “pass-by-value”?Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Fastest way to determine if an integer's square root is an integerHow do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I pass a variable by reference?Does Java support default parameter values?How do I convert a String to an int in Java?Creating a memory leak with Java



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0
















This question already has an answer here:



  • Is Java “pass-by-reference” or “pass-by-value”?

    79 answers



I'm slightly confused how Java works, I know the following to be true:



public static void main(String[] args) 
int c=0;
changeC(c);
System.out.println(c); // 0


public static void changeC(int c)
c++;



We know c outputs 0 because the changeC method does not change the original c



Now I'm looking at a solution on Leetcode, and it seems to following a similar concept.



Here is the code:



public int numIslands(char[][] grid) 
int count=0;
for(int i=0;i<grid.length;i++)
for(int j=0;j<grid[0].length;j++)
if(grid[i][j]=='1')
dfsFill(grid,i,j);
count++;


return count;

private void dfsFill(char[][] grid,int i, int j)
if(i>=0 && j>=0 && i<grid.length && j<grid[0].length&&grid[i][j]=='1')
grid[i][j]='0';
dfsFill(grid, i + 1, j);
dfsFill(grid, i - 1, j);
dfsFill(grid, i, j + 1);
dfsFill(grid, i, j - 1);




In this case, the grid is passed to the void function dfsFills(). Yet, whatever dfsFill() does to grid, the grid in the numIslands() function is also updated.



Why does this act differently than my first example? Is one pass by reference and the other pass by value?










share|improve this question













marked as duplicate by Thilo java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 9 at 4:00


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • 2





    Yes, you answered yourself correctly. The JVM passes along the call stack a reference to the memory area where the array elements are stored, while the primitive integer is copied. Mutable arrays (but I'd say objects in general) are dangerous to pass around, as at times you can't be sure about the side-effects produced by the called methods. That's why defensive-copy is used javapractices.com/topic/TopicAction.do?Id=15

    – LppEdd
    Mar 9 at 0:59


















0
















This question already has an answer here:



  • Is Java “pass-by-reference” or “pass-by-value”?

    79 answers



I'm slightly confused how Java works, I know the following to be true:



public static void main(String[] args) 
int c=0;
changeC(c);
System.out.println(c); // 0


public static void changeC(int c)
c++;



We know c outputs 0 because the changeC method does not change the original c



Now I'm looking at a solution on Leetcode, and it seems to following a similar concept.



Here is the code:



public int numIslands(char[][] grid) 
int count=0;
for(int i=0;i<grid.length;i++)
for(int j=0;j<grid[0].length;j++)
if(grid[i][j]=='1')
dfsFill(grid,i,j);
count++;


return count;

private void dfsFill(char[][] grid,int i, int j)
if(i>=0 && j>=0 && i<grid.length && j<grid[0].length&&grid[i][j]=='1')
grid[i][j]='0';
dfsFill(grid, i + 1, j);
dfsFill(grid, i - 1, j);
dfsFill(grid, i, j + 1);
dfsFill(grid, i, j - 1);




In this case, the grid is passed to the void function dfsFills(). Yet, whatever dfsFill() does to grid, the grid in the numIslands() function is also updated.



Why does this act differently than my first example? Is one pass by reference and the other pass by value?










share|improve this question













marked as duplicate by Thilo java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 9 at 4:00


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.













  • 2





    Yes, you answered yourself correctly. The JVM passes along the call stack a reference to the memory area where the array elements are stored, while the primitive integer is copied. Mutable arrays (but I'd say objects in general) are dangerous to pass around, as at times you can't be sure about the side-effects produced by the called methods. That's why defensive-copy is used javapractices.com/topic/TopicAction.do?Id=15

    – LppEdd
    Mar 9 at 0:59














0












0








0









This question already has an answer here:



  • Is Java “pass-by-reference” or “pass-by-value”?

    79 answers



I'm slightly confused how Java works, I know the following to be true:



public static void main(String[] args) 
int c=0;
changeC(c);
System.out.println(c); // 0


public static void changeC(int c)
c++;



We know c outputs 0 because the changeC method does not change the original c



Now I'm looking at a solution on Leetcode, and it seems to following a similar concept.



Here is the code:



public int numIslands(char[][] grid) 
int count=0;
for(int i=0;i<grid.length;i++)
for(int j=0;j<grid[0].length;j++)
if(grid[i][j]=='1')
dfsFill(grid,i,j);
count++;


return count;

private void dfsFill(char[][] grid,int i, int j)
if(i>=0 && j>=0 && i<grid.length && j<grid[0].length&&grid[i][j]=='1')
grid[i][j]='0';
dfsFill(grid, i + 1, j);
dfsFill(grid, i - 1, j);
dfsFill(grid, i, j + 1);
dfsFill(grid, i, j - 1);




In this case, the grid is passed to the void function dfsFills(). Yet, whatever dfsFill() does to grid, the grid in the numIslands() function is also updated.



Why does this act differently than my first example? Is one pass by reference and the other pass by value?










share|improve this question















This question already has an answer here:



  • Is Java “pass-by-reference” or “pass-by-value”?

    79 answers



I'm slightly confused how Java works, I know the following to be true:



public static void main(String[] args) 
int c=0;
changeC(c);
System.out.println(c); // 0


public static void changeC(int c)
c++;



We know c outputs 0 because the changeC method does not change the original c



Now I'm looking at a solution on Leetcode, and it seems to following a similar concept.



Here is the code:



public int numIslands(char[][] grid) 
int count=0;
for(int i=0;i<grid.length;i++)
for(int j=0;j<grid[0].length;j++)
if(grid[i][j]=='1')
dfsFill(grid,i,j);
count++;


return count;

private void dfsFill(char[][] grid,int i, int j)
if(i>=0 && j>=0 && i<grid.length && j<grid[0].length&&grid[i][j]=='1')
grid[i][j]='0';
dfsFill(grid, i + 1, j);
dfsFill(grid, i - 1, j);
dfsFill(grid, i, j + 1);
dfsFill(grid, i, j - 1);




In this case, the grid is passed to the void function dfsFills(). Yet, whatever dfsFill() does to grid, the grid in the numIslands() function is also updated.



Why does this act differently than my first example? Is one pass by reference and the other pass by value?





This question already has an answer here:



  • Is Java “pass-by-reference” or “pass-by-value”?

    79 answers







java methods parameter-passing pass-by-reference pass-by-value






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 9 at 0:52









James MitchellJames Mitchell

82431635




82431635




marked as duplicate by Thilo java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 9 at 4:00


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by Thilo java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 9 at 4:00


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









  • 2





    Yes, you answered yourself correctly. The JVM passes along the call stack a reference to the memory area where the array elements are stored, while the primitive integer is copied. Mutable arrays (but I'd say objects in general) are dangerous to pass around, as at times you can't be sure about the side-effects produced by the called methods. That's why defensive-copy is used javapractices.com/topic/TopicAction.do?Id=15

    – LppEdd
    Mar 9 at 0:59













  • 2





    Yes, you answered yourself correctly. The JVM passes along the call stack a reference to the memory area where the array elements are stored, while the primitive integer is copied. Mutable arrays (but I'd say objects in general) are dangerous to pass around, as at times you can't be sure about the side-effects produced by the called methods. That's why defensive-copy is used javapractices.com/topic/TopicAction.do?Id=15

    – LppEdd
    Mar 9 at 0:59








2




2





Yes, you answered yourself correctly. The JVM passes along the call stack a reference to the memory area where the array elements are stored, while the primitive integer is copied. Mutable arrays (but I'd say objects in general) are dangerous to pass around, as at times you can't be sure about the side-effects produced by the called methods. That's why defensive-copy is used javapractices.com/topic/TopicAction.do?Id=15

– LppEdd
Mar 9 at 0:59






Yes, you answered yourself correctly. The JVM passes along the call stack a reference to the memory area where the array elements are stored, while the primitive integer is copied. Mutable arrays (but I'd say objects in general) are dangerous to pass around, as at times you can't be sure about the side-effects produced by the called methods. That's why defensive-copy is used javapractices.com/topic/TopicAction.do?Id=15

– LppEdd
Mar 9 at 0:59













2 Answers
2






active

oldest

votes


















1














It is not pass-by-reference, because no matter what happens inside the method, the variable grid of the caller still points to the same object it did before the call.



The difference is that grid is a mutable object (an array), so the method can cause the state inside of grid to change. Since both places (caller and callee) look at the same object, they will both see the changes made there.



Everything in Java is passed by value. But except for primitive types that "value" being passed is a pointer to an object. So if the state of that object is mutable, you need to be careful.



"Pass-by-reference" would mean that the method could change the variable of the caller to point at a different object. That is not possible. In your example you can be sure that e.g. grid is not suddenly null or that its length has changed.






share|improve this answer






























    0














    Yes and no.



    Yes because that's how JVM internally works. Primitive parameters like int are passed by copying their value, while all other parameters like String or int[] are passed by copying a reference (points to the actual object in heap).



    No because you will see exactly the same behavior even when you are using an java.lang.Integer, which is the boxed type of int and is passed by copying a reference. In fact, terms like "pass by value" and "pass by ref" are not used in java at all.



    void foo() 
    Integer i = 0;
    bar(i);
    assert i == 0;


    void bar(Integer i)
    i++;




    The key fact is i++ means i = i + 1, which use i and 1 to produce a new int, bind name i with that new int, and discard the previous int value, instead of mutating the previous int directly.



    Things like array[0]++ or people.age++ work in the same way. It bind the property age of people with a new int. It changes the property age, but not affects the int itself






    share|improve this answer





























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      It is not pass-by-reference, because no matter what happens inside the method, the variable grid of the caller still points to the same object it did before the call.



      The difference is that grid is a mutable object (an array), so the method can cause the state inside of grid to change. Since both places (caller and callee) look at the same object, they will both see the changes made there.



      Everything in Java is passed by value. But except for primitive types that "value" being passed is a pointer to an object. So if the state of that object is mutable, you need to be careful.



      "Pass-by-reference" would mean that the method could change the variable of the caller to point at a different object. That is not possible. In your example you can be sure that e.g. grid is not suddenly null or that its length has changed.






      share|improve this answer



























        1














        It is not pass-by-reference, because no matter what happens inside the method, the variable grid of the caller still points to the same object it did before the call.



        The difference is that grid is a mutable object (an array), so the method can cause the state inside of grid to change. Since both places (caller and callee) look at the same object, they will both see the changes made there.



        Everything in Java is passed by value. But except for primitive types that "value" being passed is a pointer to an object. So if the state of that object is mutable, you need to be careful.



        "Pass-by-reference" would mean that the method could change the variable of the caller to point at a different object. That is not possible. In your example you can be sure that e.g. grid is not suddenly null or that its length has changed.






        share|improve this answer

























          1












          1








          1







          It is not pass-by-reference, because no matter what happens inside the method, the variable grid of the caller still points to the same object it did before the call.



          The difference is that grid is a mutable object (an array), so the method can cause the state inside of grid to change. Since both places (caller and callee) look at the same object, they will both see the changes made there.



          Everything in Java is passed by value. But except for primitive types that "value" being passed is a pointer to an object. So if the state of that object is mutable, you need to be careful.



          "Pass-by-reference" would mean that the method could change the variable of the caller to point at a different object. That is not possible. In your example you can be sure that e.g. grid is not suddenly null or that its length has changed.






          share|improve this answer













          It is not pass-by-reference, because no matter what happens inside the method, the variable grid of the caller still points to the same object it did before the call.



          The difference is that grid is a mutable object (an array), so the method can cause the state inside of grid to change. Since both places (caller and callee) look at the same object, they will both see the changes made there.



          Everything in Java is passed by value. But except for primitive types that "value" being passed is a pointer to an object. So if the state of that object is mutable, you need to be careful.



          "Pass-by-reference" would mean that the method could change the variable of the caller to point at a different object. That is not possible. In your example you can be sure that e.g. grid is not suddenly null or that its length has changed.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 9 at 3:55









          ThiloThilo

          198k79425579




          198k79425579























              0














              Yes and no.



              Yes because that's how JVM internally works. Primitive parameters like int are passed by copying their value, while all other parameters like String or int[] are passed by copying a reference (points to the actual object in heap).



              No because you will see exactly the same behavior even when you are using an java.lang.Integer, which is the boxed type of int and is passed by copying a reference. In fact, terms like "pass by value" and "pass by ref" are not used in java at all.



              void foo() 
              Integer i = 0;
              bar(i);
              assert i == 0;


              void bar(Integer i)
              i++;




              The key fact is i++ means i = i + 1, which use i and 1 to produce a new int, bind name i with that new int, and discard the previous int value, instead of mutating the previous int directly.



              Things like array[0]++ or people.age++ work in the same way. It bind the property age of people with a new int. It changes the property age, but not affects the int itself






              share|improve this answer



























                0














                Yes and no.



                Yes because that's how JVM internally works. Primitive parameters like int are passed by copying their value, while all other parameters like String or int[] are passed by copying a reference (points to the actual object in heap).



                No because you will see exactly the same behavior even when you are using an java.lang.Integer, which is the boxed type of int and is passed by copying a reference. In fact, terms like "pass by value" and "pass by ref" are not used in java at all.



                void foo() 
                Integer i = 0;
                bar(i);
                assert i == 0;


                void bar(Integer i)
                i++;




                The key fact is i++ means i = i + 1, which use i and 1 to produce a new int, bind name i with that new int, and discard the previous int value, instead of mutating the previous int directly.



                Things like array[0]++ or people.age++ work in the same way. It bind the property age of people with a new int. It changes the property age, but not affects the int itself






                share|improve this answer

























                  0












                  0








                  0







                  Yes and no.



                  Yes because that's how JVM internally works. Primitive parameters like int are passed by copying their value, while all other parameters like String or int[] are passed by copying a reference (points to the actual object in heap).



                  No because you will see exactly the same behavior even when you are using an java.lang.Integer, which is the boxed type of int and is passed by copying a reference. In fact, terms like "pass by value" and "pass by ref" are not used in java at all.



                  void foo() 
                  Integer i = 0;
                  bar(i);
                  assert i == 0;


                  void bar(Integer i)
                  i++;




                  The key fact is i++ means i = i + 1, which use i and 1 to produce a new int, bind name i with that new int, and discard the previous int value, instead of mutating the previous int directly.



                  Things like array[0]++ or people.age++ work in the same way. It bind the property age of people with a new int. It changes the property age, but not affects the int itself






                  share|improve this answer













                  Yes and no.



                  Yes because that's how JVM internally works. Primitive parameters like int are passed by copying their value, while all other parameters like String or int[] are passed by copying a reference (points to the actual object in heap).



                  No because you will see exactly the same behavior even when you are using an java.lang.Integer, which is the boxed type of int and is passed by copying a reference. In fact, terms like "pass by value" and "pass by ref" are not used in java at all.



                  void foo() 
                  Integer i = 0;
                  bar(i);
                  assert i == 0;


                  void bar(Integer i)
                  i++;




                  The key fact is i++ means i = i + 1, which use i and 1 to produce a new int, bind name i with that new int, and discard the previous int value, instead of mutating the previous int directly.



                  Things like array[0]++ or people.age++ work in the same way. It bind the property age of people with a new int. It changes the property age, but not affects the int itself







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 9 at 3:50









                  yyyyyyyy

                  885




                  885













                      Popular posts from this blog

                      1928 у кіно

                      Захаров Федір Захарович

                      Ель Греко