Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First of all: I know it's hypocritical but I think the best place to get this idea solid in your head is to grab a Java textbook (or possibly an online tutorial). I don't think you'll be able to get a solid understanding of these concepts through our answers.</p> <p>Maybe try (I haven't read these, only skimmed):</p> <ul> <li><a href="http://www.yoda.arachsys.com/java/passing.html" rel="nofollow noreferrer">http://www.yoda.arachsys.com/java/passing.html</a></li> <li><a href="http://www.developertutorials.com/tutorials/java/pass-by-value-semantic-050524/page3.html" rel="nofollow noreferrer">http://www.developertutorials.com/tutorials/java/pass-by-value-semantic-050524/page3.html</a></li> <li><a href="http://javadude.com/articles/passbyvalue.htm" rel="nofollow noreferrer">http://javadude.com/articles/passbyvalue.htm</a></li> </ul> <hr> <p>I'm going to try and answer this a different way. The correct answer is out there already but this sort of thing is notoriously hard IMO to explain if you're not face-to-face with the person.</p> <p>This is your first piece of code:</p> <pre><code>public class Main { public static void foo(String a){ a="2"; } public static void main(String[] args) { String x="1"; foo(x); System.out.println("x="+x); } } </code></pre> <p>The problem is the line <code>a = "2"</code>. In simple terms it means: "make the variable 'a' point to a String instance with the value '2'". What this implies is: "forget whatever String 'a' is currently pointing to so it can point to this new value". So you are telling it to forget that it points to the String that you passed (as an argument to the method), so it can point to the new one.</p> <p>The String you passed as an argument still exists, and the variable 'x' still points to it. You didn't change the String which the variable 'x' points to, you only changed the String which the variable 'a' points to.</p> <p>As mentioned above this is because Java uses pass-by-value and not pass-by-reference.</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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