Java variables updating after void method [duplicate]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

Arrow those variables!

Add text to same line using sed

Rock identification in KY

Perform and show arithmetic with LuaLaTeX

Could an aircraft fly or hover using only jets of compressed air?

Is it possible to do 50 km distance without any previous training?

What would happen to a modern skyscraper if it rains micro blackholes?

Modeling an IP Address

I'm flying to France today and my passport expires in less than 2 months

Revoked SSL certificate

Do I have a twin with permutated remainders?

NMaximize is not converging to a solution

How can I make my BBEG immortal short of making them a Lich or Vampire?

Why can't I see bouncing of a switch on an oscilloscope?

"You are your self first supporter", a more proper way to say it

Why doesn't H₄O²⁺ exist?

dbcc cleantable batch size explanation

Can I ask the recruiters in my resume to put the reason why I am rejected?

Why do I get two different answers for this counting problem?

What are these boxed doors outside store fronts in New York?

Is it possible to run Internet Explorer on OS X El Capitan?

Today is the Center

How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?

Can I make popcorn with any corn?



Java variables updating after void method [duplicate]


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

82431534




82431534




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

          197k79423576




          197k79423576























              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

                      Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                      Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                      2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived