• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

When to convert field to local variable?

 
Ranch Hand
Posts: 284
MySQL Database PHP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I read some articles, they said that converting fields into local variables will help improve performance because local variables have speed to access / gets faster than fields.
So I wrote a simple code (and notary what I understand):

The most obvious, although converting field into local variable then if there is any change in local variables, such as adding, changing, removing (whether they are removed directly as in the example code or use Iterator.remove()) will not affect the current value of the field (unless you have re-assign the local variable for field).
However, do really should re-assign local variable for field? Does it affect performance?
Which cases should convert field into local variable?
Although I'm not sure whether to convert or not? And does it really improve performance? But I think it can be divided into 2 cases.
  • Case 1: If only access / get the values of the field WITHOUT making any changes (add, change, remove,...), I WILL convert field into local variables.
  • Case 2: In contrast, if NOT only access / get the values of the field but also make any changes (add, change, remove,...), I WILL NOT convert the field into local variable.

  • In case of whether to re-assign local variable to field? I need your answer.  
     
    Marshal
    Posts: 28193
    95
    Eclipse IDE Firefox Browser MySQL Database
    • Likes 3
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    From the design point of view: you should generally declare a variable as a local variable inside a method if it's only used within that one method. Some people would say "always" in this case but it's still only a "should".

    If it's needed in more than one method, then it must be declared as a field, a class-level variable. There's no "maybe" here, your design won't work if Method A and Method B both need access to Variable X but Variable X is local to a single method.

    So, generally you can't convert a field to a local variable unless it's only used in one method, and if that's the case you should probably do that anyway.

    But your code doesn't seem to do that. I was under the impression that those mysterious articles were talking about where the variables where declared -- was that the case or not? Your code copies data from a field to a local variable. It isn't obvious to me how getting a copy of a reference to Object Z and then using that reference to access Object Z improves upon accessing Object Z via a field which you already have access to.

    Anyway to me this is the sort of performance optimization which, if it even exists, is similar to scraping the paint off my bicycle to reduce its weight and therefore improve its performance.
     
    Tan Quang
    Ranch Hand
    Posts: 284
    MySQL Database PHP Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    I don't understand one thing: Sometimes I just need to write line 5 and do not need to do things in line 12, when I make changes in local variables, field will also be changed.
    Why is that?
    And the "copying of field data to local variables" really helps improve performance? Especially in the case of access / get value (because any change in local variables willn't affect field if we do not perform line 12)?
     
    Paul Clapham
    Marshal
    Posts: 28193
    95
    Eclipse IDE Firefox Browser MySQL Database
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Your one question: your field contains a reference to an object. When you copy that to a local variable, you now have another reference to the same object. So copying the reference from the local variable back to the field has no effect. This assumes you're talking about reference variables, by the way. Variables which contain primitive values like int and long, that's different.

    As for your other question, you should be asking the person who gave you this advice. It's totally wrong to ask somebody who hasn't even read the actual articles, but has only seen a possibly flawed interpretation of them. Anyway if there is any performance improvement to be had by doing that, it's not the sort of thing that I would spend any time considering. The best performance-improving change I could do to the code I'm working with now would be to buy a faster disk to speed up the database access. (Which I do plan to do.) We're talking about seconds of time reduction there, not nanoseconds.
     
    Marshal
    Posts: 79179
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Sorry for not noticing this thread earlier. I think I am going to agree with Paul.

    Tan Quang wrote:I read some articles . . .

    Please tell us where you read that, in case we want to assess the sources ourselves.

    converting fields into local variables will help improve performance . . .

    Did they say how much performance improvement you can expect? I would expect at most a few nanoseconds for each field access, which falls into my definition of imperceptible and negligible. Did they say that performance should be your lowest priority? Did they say that correct design is much more important?

    . . . // convert field to local variable

    Your comment is incorrect. You are not converting anything, but creating an “alias”, which is a second reference to an object already referenced elsewhere. That is usually at best dubious design because changes in one place are reflected in the other place.

    . . . // why if re-assign local variable to field here, we will receive 3 "null" of 3 println below?

    Because of incorrect design of that class. I think correct design for fields includes initialising them before use,

    . . .
           /**
            * Now, if you change anything in local variable will also cause the field to change
            **/
    . . .

    Please don't use /** documentation comments */ in that sort of context. Please remind yourself of the different between an object and a reference to is.

    . . . However, do really should re-assign local variable for field? Does it affect performance?

    Performance should be your last consideration; behaviour of the program is what matters. Also remember that the JVM can monitor code for performance problems and can optimise many of those problems, but attempts to be too clever can prevent such optimisations.

    Which cases should convert field into local variable? . . .

    None. Follow Paul's rule of thumb. Decide whether a variable will be needed by several methods. Decide whether it will be needed outwith the object. If so, it will have to be a field. If you aren't sure, make it a local variable. If you get access problems, change it to a field. You usually use Eclipse and Eclipse has an option to correct compiler errors by converting a local variable to a field.

    The more fields you have, the larger the object will be. The larger an object you have, the more scope there is for changing the state of the object. The more scope there is for changing the state of an object there is, the more scope there is for errors to occur. Local variables have restricted scope and the scope for errors to occur is therefore smaller.

    Make all your fields private, unless you have a special agreement with colleagues for package‑private fields in a package. Only use static fields for constants. Remember the different behaviour of uninitialised fields and local variables.
     
    Tan Quang
    Ranch Hand
    Posts: 284
    MySQL Database PHP Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:Please don't use /** documentation comments */ in that sort of context. Please remind yourself of the different between an object and a reference to is.


    Yes, I actually intended to write:
    But maybe I pressed it so quickly, so it came from commenting into a document comment.
    Well, this question makes me feel confused. So I wrote a test code. This is my code:
    File Main.java:
    File Second.java:
    After the test, I drawed a number of things:
  • (1) If a getter or field in another class I assigned (by the = sign) into a local variable, this action of mine is assigned. Any change on the local variable will lead to changes on getter / field.
  • (2) Conversely, if a getter / field is in the same class that I assigned (by the = sign) into a local variable, this action is that I'm copying the data of that field into the local variable. Therefore, any change in local variable willn't change on getter / field. Right?

  • It reminds me of this question, Carey Brown said:

    Carey Brown wrote:

    Tan Quang wrote: will return the original of the mall, i.e. if I add, delete, or modify its data (KEY, VALUE) it will replace the data and cannot be restored initial data until I restart the server. That's why I have to clone that data before making any modifications.

    The original data is never modified, added to, or deleted. The only purpose it serves is to have its values copied (if applicable) to newMall.


    But that question in my case (1), that is, if any changes in local variable will also make the value of getter (a.k.a getMallTable()) change. Why did he say it won't change?  
     
    Tan Quang
    Ranch Hand
    Posts: 284
    MySQL Database PHP Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Paul Clapham wrote:Variables which contain primitive values like int and long, that's different.


    Can you explain it?

    Paul Clapham wrote:As for your other question, you should be asking the person who gave you this advice. It's totally wrong to ask somebody who hasn't even read the actual articles, but has only seen a possibly flawed interpretation of them. Anyway if there is any performance improvement to be had by doing that, it's not the sort of thing that I would spend any time considering. The best performance-improving change I could do to the code I'm working with now would be to buy a faster disk to speed up the database access. (Which I do plan to do.) We're talking about seconds of time reduction there, not nanoseconds.


    I didn't really find those articles, but I found quite similar questions on StackOverflow: Java local vs instance variable access speed and Local variables or class fields? (It's C# but also worth reference)
     
    Campbell Ritchie
    Marshal
    Posts: 79179
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Tan Quang wrote:. . . Local variables or class fields? . . .

    Somebody is using poor nomenclature; “class fields” usually means static fields. That link seems to be as much about performance as anything else, and as I said earlier, the likely difference will be too small to notice.

    Any change on the local variable will lead to changes on getter / field.

    That sounds very confused, and I think you have misunderstood something. A getXXX() method should never change anything.
     
    Saloon Keeper
    Posts: 15510
    363
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    In theory accessing a local variable is faster than accessing an instance field, because for an instance field the JVM must first dereference the object reference before it can access the field.

    In practice, any difference in performance will be negligible, and there might not even be a difference because it's possible that the the JVM optimizes access to the current object.

    Note that the benchmark in the StackOverflow topic that you linked to is poorly written. You may draw absolutely NO conclusions from it. Micro benchmarks must always be written using a micro benchmarking framework, such as JMH.
     
    Campbell Ritchie
    Marshal
    Posts: 79179
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Stephan van Hulst wrote:. . . the benchmark in the StackOverflow topic that you linked to is poorly written. . . .

    In the same SO thread, Steve Kuo wrote:So much bad advice in that article I don't know where to start



    [edit]Addition: This would appear to be the article he criticised.
     
    Paul Clapham
    Marshal
    Posts: 28193
    95
    Eclipse IDE Firefox Browser MySQL Database
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Addition: This would appear to be the article he criticised.

    I noticed it mentioned applets, which helps to explain why it is seriously outdated.
     
    Tan Quang
    Ranch Hand
    Posts: 284
    MySQL Database PHP Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:Somebody is using poor nomenclature; “class fields” usually means static fields. That link seems to be as much about performance as anything else, and as I said earlier, the likely difference will be too small to notice.


    I'm quoting the original title of the question, not that I say so.

    Campbell Ritchie wrote:That sounds very confused, and I think you have misunderstood something. A getXXX() method should never change anything.


    I mean that I don't tell it to change the thing it has to return, it changes the value of what is returned.
     
    Campbell Ritchie
    Marshal
    Posts: 79179
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    I didn't say it was you using poor nomenclature. Sorry for that confusion.
     
    Tan Quang
    Ranch Hand
    Posts: 284
    MySQL Database PHP Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:I didn't say it was you using poor nomenclature. Sorry for that confusion.


    So I wonder if anyone can read my example code?
    Maybe I should explain my questions:

    Case 1: According to Paul Clapham's call, "copies data from a field to a local variable":

  • I created a field is mainArrList on the Main.java file.
  • After that, I proceeded to "copy" the data of the mainArrList field data into the local variable _mainArrList (line 13).
  • After that, I proceeded to remove the element at the index = 2 of the field mainArrList (line 14) and then check the remaining element list of that field (line 15). It can be seen that the element at the index = 2 has been removed.

  • Next, I removed the index = 5 on the local variable _mainArrList that I used to "copy" the data of the field mainArrList (line 16) and proceed to print the value of the mainArrList field value. It can be seen that it didn't remove the index = 5 on the mainArrList field (line 17) but it removed the index = 5 on the local variable _mainArrList (line 18).


    In the case (1), after "copying" field data into local variables, any changes on local variables will not change the value on the field.

    Case 2: Unknown name, temporarily called "assign":

  • At the Second.java file, I have the field secArrs and the method getSecArrs() return to the field secArrs above.
  • At the Main.java file, I performed "assign" method getSecArrs() and field secArrs for 2 variables, respectively, mainArrs (line 20) and _mainArrs respectively (line 21).
  • After that, I made changes on both variables, namely deleted the element at the index = 2 on the mainArrs variable (line 22) and index = 5 on the _mainArrs variable (line 23).
  • As a result, the element in those two positions was deleted from the secArrs field at the Second.java file, whether above I "assigned" the method or field. It can be said that the two local variables (mainArrs and _mainArrs) are like the "representative" of the field secArrs at Second.java on the Main.java file, so when I change the local variable value will also lead to change of value at the secArrs field.

  • In the case (2), although I do quite similar to the case (1) above, the field and method are all in another file (Second.java). However, when I made changes in local variables, field data on Second.java file will also be changed.
    Therefore, I just asked the two questions above:
  • (1) If a getter or field in another class I assigned (by the = sign) into a local variable, this action of mine is assigned. Any change on the local variable will lead to changes on getter / field.
  • (2) Conversely, if a getter / field is in the same class that I assigned (by the = sign) into a local variable, this action is that I'm copying the data of that field into the local variable. Therefore, any change in local variable willn't change on getter / field. Right?

  • That's what makes me confused here.  
     
    Saloon Keeper
    Posts: 10705
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Tan Quang wrote:(2) Conversely, if a getter / field is in the same class that I assigned (by the = sign) into a local variable, this action is that I'm copying the data of that field into the local variable. Therefore, any change in local variable willn't change on getter / field. Right?

    What does the running of your program tell you?
    These two assignments are exactly the same. They copy the reference to the ArrayList. They do NOT copy the contents of the ArrayList. This is confirmed by your program.
     
    Carey Brown
    Saloon Keeper
    Posts: 10705
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    You can verify this with:
    Note that '==' compares  the REFERENCES themselves not the values that the references refer to.
     
    Carey Brown
    Saloon Keeper
    Posts: 10705
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    I think you are concentrating on the wrong thing. You are worried about a couple of nano-seconds of performance (maybe) when you don't have a clear mental image of  how Java passes around references and under what circumstances the data being referred to is also being copied.
     
    Tan Quang
    Ranch Hand
    Posts: 284
    MySQL Database PHP Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Carey Brown wrote:I think you are concentrating on the wrong thing. You are worried about a couple of nano-seconds of performance (maybe) when you don't have a clear mental image of  how Java passes around references and under what circumstances the data being referred to is also being copied.


    Oh, so bad. I'm wondering:
    1. Why when "assigning" a field or a method to local variables, if the field / method is in the same class as the local variable, this action will only copy the data of the field / method, any change on the local variable will not change to the value of the field / method that I "assigned" before?
    2. And vice versa, if I "assign" a field or a method in another class with the class of local variables, then make changes on that local variable, the value of the field / method will also be changed like local variables?  
    Moreover, temporarily didn't mention performance, writing code:

    It is obvious that it will be "easier to see" than writing:
     
    Carey Brown
    Saloon Keeper
    Posts: 10705
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Here is my work-over of your code. Note that I did away with your "singleton" code in Second because it's not thread safe. My version is the correct way to do it. Also note the helper methods remove() and print() that output what is being done along with the address of the data in memory. You'll see that for all your copying of references you're ending up dealing with only two memory addresses no matter which variable or method you choose.
    Output:
     
    Tan Quang
    Ranch Hand
    Posts: 284
    MySQL Database PHP Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Carey Brown wrote:Here is my work-over of your code. Note that I did away with your "singleton" code in Second because it's not thread safe. My version is the correct way to do it. Also note the helper methods remove() and print() that output what is being done along with the address of the data in memory. You'll see that for all your copying of references you're ending up dealing with only two memory addresses no matter which variable or method you choose.


    That is the problem, my code and you are the same at the point that both have "copied" the data of field mainArrList into local variable _mainArrList on the same class and then remove a element on that local variable.
    But my code after removing the element on local variable, that element is only removed on local variable, not removed on field. You can see that the element has been removed on local variable but on field is still not removed (line 17, 18).
    But in your code,  the element is removed on both local variable and field, even though you just need to remove on local variable, no need to remove on field (line 28).
    I'm wondering why is that?  
    P/s: I need to go slowly, so temporarily not mentioned the code section of the Second.  
     
    Carey Brown
    Saloon Keeper
    Posts: 10705
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Tan Quang wrote:But my code after removing the element on local variable, that element is only removed on local variable, not removed on field.

    Not true.
     
    Carey Brown
    Saloon Keeper
    Posts: 10705
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Your comment on line 17 is incorrect.
     
    Carey Brown
    Saloon Keeper
    Posts: 10705
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Likes 2
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Please don't say you are "copying the data" when you are actually copying the reference. Once you "copy" or assign one reference to another then both references now point to the same object in memory, which in your case, is an ArrayList. You still only have one ArrayList with elements that contain values. You haven't made a new ArrayList whose elements contain copies of values in the original ArrayList.
     
    Tan Quang
    Ranch Hand
    Posts: 284
    MySQL Database PHP Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Carey Brown wrote:Please don't say you are "copying the data" when you are actually copying the reference. Once you "copy" or assign one reference to another then both references now point to the same object in memory, which in your case, is an ArrayList. You still only have one ArrayList with elements that contain values. You haven't made a new ArrayList whose elements contain copies of values in the original ArrayList.


    I checked again, yes, I was wrong.
    Can you explain it to me, why in the case below, field mainArrList is still null while _mainArrList is not?

    P/s: I borrowed your print method.
     
    Carey Brown
    Saloon Keeper
    Posts: 10705
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    A = null
    B = null
    B = A
    IF B == null
    THEN B = new something

    Now, what's in A? well A is still null. putting something into B does not put it into A.
     
    Carey Brown
    Saloon Keeper
    Posts: 10705
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    This tweak handles a null objejct

     
    Master Rancher
    Posts: 4806
    72
    • Likes 2
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Or:
     
    Tan Quang
    Ranch Hand
    Posts: 284
    MySQL Database PHP Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Mike Simmons wrote:Or:


    Yes, I remembered this method that would give string "null" when meeting an null object instead of throwing a NPE as the toString() method.
     
    Campbell Ritchie
    Marshal
    Posts: 79179
    377
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    I am sure there is no such thing as a null object; it would be better to say, “reference to null”.
     
    Tan Quang
    Ranch Hand
    Posts: 284
    MySQL Database PHP Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Carey Brown wrote:A = null
    B = null
    B = A
    IF B == null
    THEN B = new something

    Now, what's in A? well A is still null. putting something into B does not put it into A.


    Campbell Ritchie wrote:I am sure there is no such thing as a null object; it would be better to say, “reference to null”.


    Then I found an answer on SO, the address of "reference to null" is 0. So, want "assign one reference to another then both references now point to the same object in memory" mean object reference must be different null (aka A != null), right?
     
    Campbell Ritchie
    Marshal
    Posts: 79179
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Tan Quang wrote:. . . an answer on SO, the address of "reference to null" is 0.

    Please give us a link to that SO thread.
    How do they know the address of null is 0? The Java Virtual Machine Specification (=JVMS) doesn't specify that. It is also unlikely that there is such a thing as memory location 0. That might be used by the OS for some sort of important code. It is however likely that the JVMS uses a notional reference of 0 to represent zero, false, or null depending on context.

    . . . object reference must be different null (aka A != null), right?

    I am afraid you have misunderstood that. The fact that it is always possible to test for xyz == null and xyz == null and get the correct answer shows that null always uses the same (notional) reference and there is only one such memory reference. There is no such thing as a different null.
     
    Tan Quang
    Ranch Hand
    Posts: 284
    MySQL Database PHP Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:Please give us a link to that SO thread.
    How do they know the address of null is 0? The Java Virtual Machine Specification (=JVMS) doesn't specify that. It is also unlikely that there is such a thing as memory location 0. That might be used by the OS for some sort of important code. It is however likely that the JVMS uses a notional reference of 0 to represent zero, false, or null depending on context.


    I think it is here: Does null variable require space in memory
    You can use System.identityHashCode with null object, it will return 0.

    Identity hashcode is certainly not generated based on the address of the object in memory. Unfortunately, there is no documentation about the identity hashcode generation algorithm, the secret lies in the source code of the JVM written in C++ language.


    I am afraid you have misunderstood that. The fact that it is always possible to test for xyz == null and xyz == null and get the correct answer shows that null always uses the same (notional) reference and there is only one such memory reference. There is no such thing as a different null.


    I mean:

    In this case, the situation will always appear like the example you give. That is, B may change the value but A does not (sounds like assigning A to B is redundant).
    Whereas:

    At this point, like you say: "Both A and B will point to to the same object in memory..." (omit N words). At this time, B changes the value, A will also change the value.
     
    Campbell Ritchie
    Marshal
    Posts: 79179
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Tan Quang wrote:. . . Does null variable require space in memory

    There are a  few errors in that thread. One of them is that no memory is used for the class, which is probably incorrect. A Class<T> object is probably loaded when the class name is used. I can't remember whether that is specified by the language or not.

    You can use System.identityHashCode with null object, it will return 0.

    Not a null object, but a reference to null, please. If there is no object behind the pointer, it is impossible to calculate its hash code, but it is very easy to implement identityHashCode() like this:-Taht does not mean the 0 is anything other than a notional address.

    . . . Unfortunately, there is no documentation about the identity hashcode generation algorithm . . .

    There is nothing unfortunate about that. Specifying an algorithm, as earlier versions of hashCode() did, fixes the implementation and restricts the language developes when updating it.

    . . .  assigning A to B is redundant).

    Yes, it is redundant.

    Whereas:
    . . . like you say:

    That code is different from what I said anything about. I haven't looked really carefully, but I think nobody else said that either.

    "Both A and B will point to to the same object in memory..." (omit N words). At this time, B changes the value, A will also change the value.

    If you actually get the above code to compile (I couldn't compile it) then a and b (not A and B, please) will point to the same reference. If that isn't null, then a and b are aliases of each other; both point to the same object.
     
    Tan Quang
    Ranch Hand
    Posts: 284
    MySQL Database PHP Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:There are a  few errors in that thread. One of them is that no memory is used for the class, which is probably incorrect. A Class<T> object is probably loaded when the class name is used. I can't remember whether that is specified by the language or not.


    Yes, you're right, I won't ask you to prove what you say is right!

    Campbell Ritchie wrote:Not a null object, but a reference to null, please. If there is no object behind the pointer, it is impossible to calculate its hash code, but it is very easy to implement identityHashCode() like this:-Taht does not mean the 0 is anything other than a notional address.


    Oh bad, "null object" in my opinion is like Carey Brown said in this answer: This tweak handles a null objejct (he also encountered a typing error...)
    But the truth is that there is no document about identity hashcode generation algorithm, therefore, it is not possible to confirm that the argument you give is right.

    Campbell Ritchie wrote:There is nothing unfortunate about that. Specifying an algorithm, as earlier versions of hashCode() did, fixes the implementation and restricts the language developes when updating it.


    That is I quoted the sentence in this article (Worse, I received the notice of Sorry, your post appears to be spam. If it is a legitimate post, then we apologize for the inconvenience; please bring it to the attention of one of the moderators. so it is impossible to assign the article link if it does not shorten it.). In fact, I don't feel anything.

    Campbell Ritchie wrote:That code is different from what I said anything about. I haven't looked really carefully, but I think nobody else said that either.


    I mean it's the same as this case: Carey Brown code. In it, A != null, A here is the mainArrList field and B is a local variable _mainArrList.
    But anyway, you're right, not you say. I once again confused your name and Carey Brown's name.

    Campbell Ritchie wrote:If you actually get the above code to compile (I couldn't compile it) then a and b (not A and B, please) will point to the same reference. If that isn't null, then a and b are aliases of each other; both point to the same object.


    Yes, like the test code that Carey Brown wrote above, both field and local variables will point to an object in memory.
    P/s: Why do I feel you are "catching" me and "counter" Carey Brown? Um... It is difficult to describe this feeling...  
     
    Campbell Ritchie
    Marshal
    Posts: 79179
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    We are suspicious about bit.ly because people post all sorts of weird and wonderful things there, some of them hiding malware. Please quote only the part of the bit.ly link after the last / if you think it is legitimate.
     
    Tan Quang
    Ranch Hand
    Posts: 284
    MySQL Database PHP Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:We are suspicious about bit.ly because people post all sorts of weird and wonderful things there, some of them hiding malware. Please quote only the part of the bit.ly link after the last / if you think it is legitimate.


    Oh, it has been quite popular in Vietnam since Google stopped providing a shortened service of goo(dot)gl.
    This is a link to the original article: o7\planning(dot)org/13693/java-system-identityhashcode-object-hashcode-object-equals#a64443851
    I don't know why it can't be inserted directly, so this time, I'll use the way to "bypass" quite popular when posting links on Facebook, replace (dot) with "." and remove "\".
    P/s: In fact, you can blacken up the above quote, then right-click, select "Search on Google for ...", maybe it will take you to the website.
     
    Campbell Ritchie
    Marshal
    Posts: 79179
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Thank you for the O7 link. Unfortunately, Firefox (=Mozilla) gave a severe security warning about that link and wouldn't open it.

    The implementation of methods can vary from version to version. This is what it says about hashCode() in Java6:-

    As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)

    Note that does not say definitely that hashCode() returns the memory address, so the most recent version of the same method tells us:-

    As far as is reasonably practical, the hashCode method defined by class Object returns distinct integers for distinct objects.

    It says nothing about how hash codes are calculated.
    Since both ObjecthashCode() and System#identityHashCode() are native methods, it is only possible to see their implementation by opening the JVM code; you can do that with OpenJDK. It is likely, but not certain, that the implementation is similar on Windows®, Unix, and Linux. It is likely but not certain that there is a notional value of 0 because that is the easiest way to implement default values for (non‑final) fields.
    It is certain that the real‑life programmer doesn't need to know that sort of implementation details.

    I am sorry if I have not been polite.
     
    Tan Quang
    Ranch Hand
    Posts: 284
    MySQL Database PHP Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:Thank you for the O7 link. Unfortunately, Firefox (=Mozilla) gave a severe security warning about that link and wouldn't open it.



    Yes, the safety score of that site is really low!

    Campbell Ritchie wrote:The implementation of methods can vary from version to version. This is what it says about hashCode() in Java6:-

    As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)

    Note that does not say definitely that hashCode() returns the memory address, so the most recent version of the same method tells us:-

    As far as is reasonably practical, the hashCode method defined by class Object returns distinct integers for distinct objects.

    It says nothing about how hash codes are calculated.
    Since both ObjecthashCode() and System#identityHashCode() are native methods, it is only possible to see their implementation by opening the JVM code; you can do that with OpenJDK. It is likely, but not certain, that the implementation is similar on Windows®, Unix, and Linux. It is likely but not certain that there is a notional value of 0 because that is the easiest way to implement default values for (non‑final) fields.
    It is certain that the real‑life programmer doesn't need to know that sort of implementation details.


    Yes, so assigning A for B in case both A and B is null really doesn't bring anything, it just pointed to the same object in memory if A != null.

    Campbell Ritchie wrote:I am sorry if I have not been polite.


    I don't say you aren't polite, it's hard to explain that feeling in English, it's like: If I use a word it is not clear, you will say "No, you said wrong! It must be...   ".
    But anyway, I feel very interesting, whenever you "reject" something of Carey Brown, I once again confused the names of both of you.  

    Mike Simmons wrote:Just remember, he's named after the soup:


    Well, I mistook the person who wrote the topic above for Carey Brown when exactly it had to be Mike Simmons.  
     
    Don't get me started about those stupid light bulbs.
    reply
      Bookmark Topic Watch Topic
    • New Topic