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

                      Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                      Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                      How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page