Edit: I am aware that there are plenty of questions abut pass-by-reference/value and so on, and I've checked a ton of them. I still don't 'get' it. If someone could just explain THIS piece of code like I'm three years old, I think it would finally click.  Edit 2: I'm an idiot. There WAS a main method, I just read over it somehow. Adjusted the example code.  Original post:  I would never play 'reference hide-and-seek' in real life, but I am stumped by the following exam question. I know the answer, but I cannot figure out WHY it is the answer, if that makes any sense. If someone can help me make this 'click', I would greatly appreciate it.  Here is the code:  class Person {     public String name;     public int height; }  class EJavaGuruPassObjects1 {     public static void main(String args[]) {         Person p = new Person();         p.name = "EJava";          anotherMethod(p);         System.out.println(p.name);          someMethod(p);         System.out.println(p.name);     }      static void anotherMethod(Person p) {         p = new Person();         p.name = "anotherMethod";         System.out.println(p.name);     }      static void someMethod(Person p) {         p.name = "someMethod";         System.out.println(p.name);     } }   According to the book I'm using, the code should output:   anotherMethod EJava someMethod someMethod   I can't, for the life of me, figure out why it does this?  The third and fourth line of the answer, someMethod has set the name of 'p' to "someMethod" and then it printed p.name. Okay, no problem there. But anotherMethod does something curious: it seems to assign either a new Person object to 'p', or create a new reference variable that is also called 'p' and assigns the new Person object to that one. I suspect it does the latter.  Now it gets interesting: the method has worked its magic and the remaining code wants to print p.name now. If the existing variable was reassigned (I don't think so, but... maybe?), it should print "anotherMethod" again. If a second 'p' variable was indeed created, we have a problem. Why does it print EJava? How does it know which 'p' reference is adressed?
121
I always thought Java uses pass-by-reference. However, I've seen a couple of blog posts (for example, ) that claim that it isn't (the blog post says that Java uses pass-by-value). I don't think I understand the distinction they're making. What is the explanation?
48229
what about using "this" with methods in Java? Is it optional or there are situations when one needs to use it obligatory?  The only situation I have encountered is when in the class you invoke a method within a method. But it is optional. Here is a silly example just to show what I mean:  public class Test {      String s;      private String hey() {         return s;     }      public String getS(){         String sm = this.hey();         // here I could just write hey(); without this         return sm;     } }
46209
Using instance methods as callbacks for event handlers changes the scope of this from "My instance" to "Whatever just called the callback". So my code looks like this  function MyObject() {   this.doSomething = function() {     ...   }    var self = this   $('#foobar').bind('click', function(){     self.doSomethng()     // this.doSomething() would not work here   }) }   It works, but is that the best way to do it? It looks strange to me.
38779
I'm new to Apex and development in general... So, I'm playing around coding and doing some badges in Trailhead. I created a small piece of code, as below, and have no actual use: public class GenderIdentifier {     public void DetermineGender(String Gender){                 if (Gender == 'Man'){             Gender = 'Male';             } else {             Gender = 'Female';         }            } }  If I make the method 'non-static' it works, and I can see it working fine executing as a anonymous block. If I make it static, I can't execute the anonymous block, as I get an Error like:  Non static method cannot be referenced from a static context: void GenderIdentifier.DetermineGender(String)  What am I doing wrong? It would make sense to have a method like this as Static. I think I misunderstood the concept of static methods.
16290
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, navigate to the  tag. This question and answer is owned by the community! If you can improve it and make it more useful, you're welcome to edit it. I am building a trigger, a unit test, or other Apex code. I'm working with sObject records, and trying to access related record information. For example, I might have a structure like this: Account a = new Account(Name = 'Test'); insert a;  Opportunity o = new Opportunity(Name = 'Donation', AccountId = a.Id); insert o;  System.assertEquals(o.Account.Name, 'Test', 'Correct Account associated'); // Assertion fails!  Or, in a trigger, I might be aiming for something like this: trigger ContactTrigger on Contact (after insert) {     for (Contact c : Trigger.new) {         if (c.Account.Name == 'Test') {             // Take some action here         }      } }  Why doesn't this work? Why am I getting null values, or NullPointerExceptions?
34071
Consider this:  public class TestClass {      private String a;     private String b;      public TestClass()     {     a = "initialized";     }      public void doSomething()     {     String c;          a.notify(); // This is fine     b.notify(); // This is fine - but will end in an exception     c.notify(); // "Local variable c may not have been initialised"     }  }   I don't get it. "b" is never initialized but will give the same run-time error as "c", which is a compile-time error. Why the difference between local variables and members?  Edit: making the members private was my initial intention, and the question still stands...
1905
I ran into an interesting (and very frustrating) issue with the equals() method today which caused what I thought to be a well tested class to crash and cause a bug that took me a very long time to track down.   Just for completeness, I wasn't using an IDE or debugger - just good old fashioned text editor and System.out's. Time was very limited and it was a school project.  Anyhow -   I was developing a basic shopping cart which could contain an ArrayList of Book objects. In order to implement the addBook(), removeBook(), and hasBook() methods of the Cart, I wanted to check if the Book already existed in the Cart. So off I go -  public boolean equals(Book b) {     ... // More code here - null checks     if (b.getID() == this.getID()) return true;     else return false; }   All works fine in testing. I create 6 objects and fill them with data. Do many adds, removes, has() operations on the Cart and everything works fine. I read that you can either have equals(TYPE var) or equals(Object o) { (CAST) var } but assumed that since it was working, it didn't matter too much.  Then I ran into a problem - I needed to create a Book object with only the ID in it from within the Book class. No other data would be entered into it. Basically the following:  public boolean hasBook(int i) {     Book b = new Book(i);     return hasBook(b); }  public boolean hasBook(Book b) {     // .. more code here     return this.books.contains(b); }   All of a sudden, the equals(Book b) method no longer works. This took a VERY long time to track down without a good debugger and assuming the Cart class was properly tested and correct. After swaapping the equals() method to the following:  public boolean equals(Object o) {     Book b = (Book) o;     ... // The rest goes here    }   Everything began to work again. Is there a reason the method decided not to take the Book parameter even though it clearly  was  a Book object? The only difference seemed to be it was instantiated from within the same class, and only filled with one data member. I'm very very confused. Please, shed some light?
4013
If I have two variables:  Object obj; String methodName = "getName";   Without knowing the class of obj, how can I call the method identified by methodName on it?  The method being called has no parameters, and a String return value. It's a getter for a Java bean.
111110
I'm a bit confused as to how to get two method to call each other (i.e., have A() call B() and B() call A()). It seems that F# only 'sees' the method after it's been encountered in code, so if it hasn't, it just says value or constructor has not been defined.  Am I missing something very basic here?
96218
I came across this code and wanted others to provide their point of view... is it good or bad ? ;)  Class ReportClass {  public string ReportName {get; set;} }   Then it was used as follows in code:  displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString())   That is about the simplest form example I can give you. Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?  EDIT: I'm referring to the inplace assignment. Which I wasn't aware of until today
20628
I would like to clarify the differences between by value and by reference.  I drew a picture     So, for passing by value,  a copy of an identical object is created with a different reference, and the local variable is assigned the new reference, so to point to the new copy  How to understand the words: " If the function modifies that value, the modifications appear also within the scope of the calling function for both passing by value and by reference "  Thanks!
14488
I saw this in , in reference to shortcomings of the Java spec:  There are more shortcomings and this is a subtle topic. Check  out: public class methodOverloading{      public static void hello(Integer x){           System.out.println(&quot;Integer&quot;);      }       public static void hello(long x){           System.out.println(&quot;long&quot;);      }       public static void main(String[] args){          int i = 5;          hello(i);      } }  Here &quot;long&quot; would be printed (haven't checked it myself), because the compiler chooses widening over auto-boxing. Be careful when using auto-boxing or don't use it at all!  Are we sure that this is actually an example of widening instead of autoboxing, or is it something else entirely? On my initial scanning, I would agree with the statement that the output would be &quot;long&quot; on the basis of i being declared as a primitive and not an object.  However, if you changed hello(long x)  to hello(Long x)  the output would print &quot;Integer&quot; What's really going on here?  I know nothing about the compilers/bytecode interpreters for java...
16486
It appears that in PHP objects are passed by reference. Even assignment operators do not appear to be creating a copy of the Object.  Here's a simple, contrived proof:  &lt;?php  class A {     public $b; }   function set_b($obj) { $obj-&gt;b = "after"; }  $a = new A(); $a-&gt;b = "before"; $c = $a; //i would especially expect this to create a copy.  set_b($a);  print $a-&gt;b; //i would expect this to show 'before' print $c-&gt;b; //i would ESPECIALLY expect this to show 'before'  ?&gt;   In both print cases I am getting 'after'  So, how do I pass $a to set_b() by value, not by reference?
19919
I ran into an interesting behavior recently.  It seems that if I override .equals() to take a parameter other than Object, it doesn't get called.  Can anyone explain to me why this is happening?  It seems to violate my understanding of polymorphism in OOP, but maybe I'm missing something.  Here's much simpler code that shows what I'm seeing:  public class MyClass {   private int x;   public MyClass(int n) { x = n; }   public boolean equals(Object o) { return false; }   public boolean equals(MyClass mc) { return x == mc.x; }   public static void main(String[] args) {     List&lt;MyClass&gt; list = new ArrayList&lt;MyClass&gt;();     list.add(new MyClass(3));     System.out.println("Contains 3? " + list.contains(new MyClass(3)));   } }   When this is run, it prints "Contains 3? false".  It looks like the equals(Object) function is called, even though there is another that would work.  By contrast, if I write equals like this the code works as expected:  public boolean equals(Object o) {   if(!(o instanceof MyClass))     return false;   MyClass mc = (MyClass)o;   return x == mc.x; }   Why isn't it figuring out which version of the function to call based on the type of the parameter?
5893
What is the difference between    a parameter passed by reference a parameter passed by value?   Could you give me some examples, please?
1624
The very common beginner mistake is when you try to use a class property "statically" without making an instance of that class. It leaves you with the mentioned error message:     You can either make the non static method static or make an instance of that class to use its properties.   Why? I am not asking for solutions. I would be grateful to know what is the reason behind it. The very core reason!  private java.util.List&lt;String&gt; someMethod(){     /* Some Code */     return someList;             }  public static void main(String[] strArgs){                // The following statement causes the error. You know why..     java.util.List&lt;String&gt; someList = someMethod();          }
14396
For years, I've been using named blocks to limit the scope of temporary variables.  I've never seen this done anywhere else, which makes me wonder if this is a bad idea.  Especially since the Eclipse IDE flags these as warnings by default.  I've used this to good effect, I think, in my own code.  But since it is un-idiomatic to the point where good programmers will distrust it when they see it, I really have two ways to go from here:     avoid doing it, or  promote it, with the hope that it will become an idiom.   Example (within a larger method):  final Date nextTuesday; initNextTuesday: {     GregorianCalendar cal = new GregorianCalendar();     ... // About 5-10 lines of setting the calendar fields     nextTuesday = cal.getTime(); }   Here I'm using a GregorianCalendar just to initialize a date, and I want to make sure that I don't accidentally reuse it.  Some people have commented that you don't actually need to name the block.  While that's true, a raw block looks even more like a bug, as the intent is unclear.  Furthermore, naming something encourages you to think about the intention of the block.  The goal here is to identify distinct sections of code, not to give every temporary variable its own scope.  Many people have commented that it's best to go straight to small methods.  I agree that this should be your first instinct.  However, there may be several mitigating factors:   To even consider a named block, the code should be short, one-off code that will never be called elsewhere. A named block is a quick way to organize an oversized method without creating a one-off method with a dozen parameters.  This is especially true when a class is in flux, and the inputs are likely to change from version to version. Creating a new method encourages its reuse, which may be ill-advised if the use cases aren't well-established.  A named block is easier (psychologically, at least) to throw away. Especially for unit tests, you may need to define a dozen different objects for one-off assertions, and they are just different enough that you can't (yet) find a way to consolidate them into a small number of methods, nor can you think of a way to distinguish them with names that aren't a mile long.   Advantages of using the named scope:   Can't accidentally reuse temporary variables Limited scope gives garbage collector and JIT compiler more information about programmer intent Block name provides a comment on a block of code, which I find more readable than open-ended comments Makes it easier to refactor code out of a big method into little methods, or vice versa, since the named block is easier to separate than unstructured code.   Disadvantages:  Not idiomatic: programmers who haven't seen this use of named blocks (i.e. everyone but me) assume it's buggy, since they can't find references to the block name.  (Just like Eclipse does.)  And getting something to become idiomatic is an uphill battle.  It can be used as an excuse for bad programming habits, such as:   Making huge, monolithic methods where several small methods would be more legible. Layers of indentation too deep to read easily.   Note:  I've edited this question extensively, based on some thoughtful responses.  Thanks!