• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why prefer char[] over String for password?  RSS feed

 
Ganesh Patekar
Bartender
Posts: 726
23
Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I’m trying to understand why we are recommended to use char[] rather than String to store password for security reasons.
If we see public String getText() of JPasswordField which is deprecated and replaced by getPassword. Ref: getText() method link
Java SE 8, @Deprecated public String getText() wrote:For security reasons, this method is deprecated. Use the * getPassword method instead.

If you check public char[] getPassword() which returns char[] for security reason. Ref: getPassword() method link
Java SE 8, getPassword() wrote:For stronger security, it is recommended that the returned character array be cleared after use by setting each character to zero.

What I understood, Why not to use String to store password?
  • Because Strings are immutable means once we create an object of it to store password then it will not be changed and will last until GC collects it when no more reference to it.
  • If we create String using String literal then although there is no more reference to it in code, it will be referred by String pool constant which has reference to that String and will last till program is running.
  • If we access memory dump then we can see the content of String having password but that is not case with char[] so these are few reasons we should use char[] over String.

  • I searched on google and found some information about it here link
    This is what I tried to know it practically why not to use String.
  • I created a class having instance variables String and char[] and stored values in it i.e. our password.
  • Used the jmap (Java Memory Map) tool to generate Java heap dump and analyzed by Java Heap Analysis Tool (jhat).
  • Output:
    PID: 4888@Ganesh-PC  // PID is 4888 which varies each time we run this program.
    End Java Language

  • While program was in running state, I executed jmap command like below
  • c:\> jmap -dump:format=b,file=c:\mydump.bin 4888

  • Then used jhat to read generated heap dump like below
  • c:\> jhat mydump.bin

  • Output on command prompt I got:
  • On localhost:7000 under Instance data members: we can see value of String str which had password and visible to all

  • And If you see values of char [] charArray not visible.
    Please correct me If I'm wrong.
    jmpjhatcommand.png
    [Thumbnail for jmpjhatcommand.png]
    Output on command prompt I got:
    readheapdump.png
    [Thumbnail for readheapdump.png]
    Read generated heap dump
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    What I'm trying is
    Suppose if my friend stores his password in a String variable in his program like this
    Now I he used it and assigned str = null; because he doesn't want to use it anymore but he doesn't know just dereferencing that String object will not make that String eligible for GC as It will be referred by String literal pool.
    Now I want to access that Strings to know the password as I know his program is still running on system and that String will be referrenced by String literal pool till program is running.
    Is there anyway to access that String reside in heap and referred only by String literal pool?
    I think IMO this possibility of accessing String object residing on heap for long time is the reason of not using String for password. 
     
    Fred Kleinschmidt
    Bartender
    Posts: 571
    9
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    you should never store a password in your code. Not in a String, not in a char[].
    What you should store is the encrypted value of the password. Then when the user types in the password, encrypt it and compare to the stored encryption
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    If first time user is creating user name and password. For password I used JPasswordField then getPassword() returns array of chars so do you mean I should directly encrypt that array of char and store in database? and next time when user enters user name and password while log in, encrypt that password which is in char[] and  check that encrypted password with encrypted password fetched from database?
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Actually I just want to know Is there anyway to access that String which is in heap and referred only by String literal pool?
    I tried in above shown example but when you assign null to that String str, then generated dump heap shows null value. There are so many threads about encrption and decryption so to learn that first I need to search already existed thread on that issue so I think I should not discuss about encryption.
     
    Fred Kleinschmidt
    Bartender
    Posts: 571
    9
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Exactly. Then overwrite the char[] array with junk. That way the password text no longer exists in the running java program or in core. If you were to uses a String, and you set the string to null,  the text of the password would still exist in memory until garbage collection happens. And even then, the text may still hang around in core until that core happens to be reused.
     
    Campbell Ritchie
    Marshal
    Posts: 56576
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ganesh Patekar wrote:. . . Is there anyway to access that String which is in heap and referred only by String literal pool?  . . .
    If anybody gains access to your computer directly or indirectly they can probably do a memory dump and find the password.
     
    Dave Tolls
    Ranch Foreman
    Posts: 3067
    37
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Fred Kleinschmidt wrote:
    What you should store is the encrypted value of the password. Then when the user types in the password, encrypt it and compare to the stored encryption


    They should be hashed (using appropriate techniques), not encrypted.
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:
    Ganesh Patekar wrote:. . . Is there anyway to access that String which is in heap and referred only by String literal pool?  . . .
    If anybody gains access to your computer directly or indirectly they can probably do a memory dump and find the password.
    That's what I was actually looking for, I know It may not be that necessary but I adore to verify it If possible, so Is there any way I can verify that practly by writing code or using some tools?

    Dave Tolls wrote:They should be hashed (using appropriate techniques), not encrypted.
    I think hashing is used to store particular group of values into same place which are having same hashcode so while searching a value it will be easier to find that value into a particular group having same hashcode as value which we are searching for, so rather comparing that value with each value. IMO hashing is one way process means once you calculate hash code of a value then by using that hascode you can't get original value because two different values may also have same hash code.

    In encryption and decrption, If you have key you can decrypt encrypted data so It is reversible means you can get original value by decrypting encrypted value using key, which is not in possible in the case of hashcode. Here is nice explanation Equals and Hash Code
    public int hashCode() method returns the hash code value as an integer. This integer need not remain consistent from one execution of an application to another execution of the same application.
    Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.
     
    Paul Clapham
    Sheriff
    Posts: 22835
    43
    Eclipse IDE Firefox Browser MySQL Database
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Dave Tolls wrote:They should be hashed (using appropriate techniques), not encrypted.
    I think hashing is used to store particular group of values into same place which are having same hashcode so while searching a value it will be easier to find that value into a particular group having same hashcode as value which we are searching for, so rather comparing that value with each value. IMO hashing is one way process means once you calculate hash code of a value then by using that hascode you can't get original value because two different values may also have same hash code.

    In encryption and decrption, If you have key you can decrypt encrypted data so It is reversible means you can get original value by decrypting encrypted value using key, which is not in possible in the case of hashcode. Here is nice explanation Equals and Hash Code
    public int hashCode() method returns the hash code value as an integer. This integer need not remain consistent from one execution of an application to another execution of the same application.
    Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.


    In other words, encryption is reversible (via decryption) but hashing is not. This is why you should store a hashed version of the password in your database and not an encrypted version.
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 7992
    143
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    When storing passwords, they should always be hashed, NOT encrypted. Retrieving passwords should be impossible, so we want an irreversible process. Fortunately, good password hashing algorithms such as bcrypt and PBKDF2 exist.

    To authenticate a user, you hash their password using a key derivation algorithm, and then compare the hash to the hash that you stored.
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ohh I see, Suppose I have a password "abcd" and assume calculated hascode of it is 1234. But here it says
    This integer need not remain consistent from one execution of an application to another execution of the same application.
    This line confusing me. It means If I get hash code "1234" for password "abcd" then next time when user try to login and provides password "abcd" then it is not guarantee that has code produced this time will be same as previous one i.e. 1234 which was stored in database during user's registeration.
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 7992
    143
    • Likes 2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    The hash that you get from the hashCode() method is not the same as a cryptographic hash. It's only intended to be used to implement hash tables.

    Common cryptographic hashes are MD5 or SHA1. These are NOT appropriate to use for passwords though, you need to use a key derivation function like bcrypt or PBKDF2.
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 7992
    143
    • Likes 3
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    To illustrate the issue with moving passwords around using the String class, write an application that accepts a String from a user, then null that reference out, and generate a dump of the execution.

    First run "jps" to find the PID of your application, then run "jmap -dump:file=password.dump <application pid>" and finally "jhat password.dump". You can then view the dump by browsing to localhost:7000.

    Using this method, I can easily find three instances of the password I entered into the following program while it was running:
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Opps I was trying jsp,  Yes now I got browser with localhost:7000 but under which menu you see those three instances of the password you entered?
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 7992
    143
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    There's a link to a page that will show you instance counts of classes (including platform classes). Then you click the link to String instances. Then the password you entered will be among the instances listed, if it hasn't been garbage collected yet.
     
    fred rosenberger
    lowercase baba
    Bartender
    Posts: 12565
    49
    Chrome Java Linux
    • Likes 2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I found this very interesting to watch. It explains a lot of the issues talked about in this thread.

     
    Campbell Ritchie
    Marshal
    Posts: 56576
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Stephan van Hulst wrote:The hash that you get from the hashCode() method is not the same as a cryptographic hash. It's only intended to be used to implement hash tables. . . .
    That means that whenever somebody finds that using 2047 as a prime number multiplicand instead of 31 in the Objects#hash() method, and they change the algorithm in Java13, it will still fulfil the requirements of its general contract. Serialised old hash maps might not work, but that is a different problem.

    What was that, Lassie? 2047 isn't a prime number? It damn‑well ought to be! 8191 instead?
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    So salted hash is better one. Lets see If I undertood it well or not.
  • User 1:
  • User 1 password:  "ABC"
    Assume we get random data = "XML"
    random data + User 1 password is given to hashesh and we get salted hash.

  • User 2:
  • User 2 password:  "ABC"
    Assume we get random data = "XYZ"
    random data + User 2 password is given to hashesh and we get salted hash.

  • Although both user enter same password just because of salt random data both becomes new different password.
  • But when user 1 try to login and enters password "ABC" how does this check whether entered password matches to password which is in database?

  • Yes I got about using algorithm first we get hash of password provided by user but in the salted hash case it adds random data to the password entered by user 1 during registeration and then generated salted hash on that both.
     
    Campbell Ritchie
    Marshal
    Posts: 56576
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    fred rosenberger wrote:I found this very interesting to watch. . . .
    The video talks about recent tutorials, so I went to look for dates. It said, Published on 20 Nov 2013.
     
    Rob Spoor
    Sheriff
    Posts: 21135
    87
    Chrome Eclipse IDE Java Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ganesh Patekar wrote:But when user 1 try to login and enters password "ABC" how does this check whether entered password matches to password which is in database?

    Well, you can't let the database perform the check. What you need to is retrieve the hashed password from the database, and then use the hashing algorithm itself to verify the password against the hash. For instance, using BCrypt:

    Similarly, in PHP:
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Yes I know that we have to retrieve hashed password from database.
    During registration User 1 entered password was "ABC" then random data is generated assumed "XML" now both are concatenated so becomes "ABCXML" now this data goes to algorithm which generated salt hash. Assume algorithm just adds @ symbol at last. So salted hash password of User 1 is "ABCXML@" stored in database.

    Now User 1 tries to login and enters "ABC" and salted hash password retrieved from database which is "ABCXML@". Now how does algorith matches salted hash password with User 1 entered password for log in i.e. "ABC". Why I'm asking this becaue algorithm got data which is combination of random data + User 1 entered password during registeration so algorithm is not aware of random data and user 1 password separately because it got them in concatenated form.
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Stephan van Hulst wrote:There's a link to a page that will show you instance counts of classes (including platform classes). Then you click the link to String instances. Then the password you entered will be among the instances listed, if it hasn't been garbage collected yet.
  • I think the password we enter is String literal, I mean in the source code of Scanner it doen't create an object of String using new operator so the reference of String literal of password will be in String literal pool, which will keep referring these password till program is running, no matter in code these passwords are being referred or not. Please correct me If I'm wrong.


  • I think, It is difficult to find local variables, because in my example I purposefully declared String str; char[] charArray; in class because when I had declared them as local variables of method getMethod() I was unable to find them in that browser at port 7000. I think we should either use Arbitrary Object Query Language ( OOL ) or VisualVm but never used before.

  •  
    Dave Tolls
    Ranch Foreman
    Posts: 3067
    37
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    The salt is stored with the password, usually as the first x bytes IIRC.

    Note, the idea of a salt is to prevent simple dictionary look ups of the data should someone manage to get a dump of the user table.

    In a table without salt, all passwords with the same name will have the same value, so discovering that 123456 maps to 'password' means that every entry with 123456 in it is also 'password'.

    With a salt, you have abc@98765 and def@12345 both of which map to 'password', but the attacker won't see that.

    It then forces the attacker to trawl through each individual entry and calculate the value for 'password' and see if it matches.

    That's a very (very) rough precis of what this is trying to do.

    Anyway, when the user logs in what happens is the password is salted using the salt value in the db for that user and then against the hash generated.
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Dave Tolls wrote:Anyway, when the user logs in what happens is the password is salted using the salt value in the db for that user and then against the hash generated.
    do you mean they store separate salt value of password entered by use during registeration and plus has code of that password?
    so password entered by user during login is salted usng salt value stored in db and then checks against has generated with already stored hash in db during registeration? This last step a bit annoying me so please..
     
    Dave Tolls
    Ranch Foreman
    Posts: 3067
    37
    • Likes 2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Taking BCrypt as an example (see the wiki).
    This is the BCrypt password used in that wiki as an example:
    $2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy

    That first two bits are something to do with the algorithm ($2a$ and 10).
    The important stuff (for this) is the rest:
    N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy

    This has two parts, 22 characters are the salt, and the last 31 characters are the hashed password.
    So we can extract the N9qo8uLOickgx2ZMRZoMye salt value and "glue" that to the given password and, when hashed, compare it to the IjZAgcfl7p92ldGxad68LJZdL17lhWy, which will match if the passwords matched.

    I'm not sure where your issue lies?
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ohh ok ok now I got that, I was waiting for such example, cleared all doubts Thank you Dave 
    Actually I had started thread to know how to get String objects created using String literals( Not using new operator )which are in heap but not referred by any reference variable. Why they are still in heap because they were created by String literals like String str = "Java"; so their references will be in String literal pool till program is running so they are not GC. I wanted to to show these String literals by generating heap dump so we can proove that we should not assign passwords( Yes no doubt  now I got about salted password ) to any String variable or store in it.

    What so far I tried is, I generated heap dump using jmap and in browser I can see objects of class, variables declared in class but could not find local variables which are declared in methods anywhere in that browser with port 7000. Because I need to search for main thread property in that those local variables information will be available.
    But anyway I used VisualVm 1.3.8 for anyalyzing heap. It's cool tool. But now it raised one doubt as I mentioned above about Strings created using String literal will be in heap till program is running( I don't thing It matters If String created using literal is an instance variable means declared in class or local variable i.e. declared & initialized in method).
    I read that here Strings, Literally by Corey McGlone

    But when I analyzed heap dump of below code using VisualVm

    After generating heap dump by clicking on heap dump button I followed below process and got the value of String literal stored in password i.e. "JAVA"

    LocalVariableInfoProcess.png
    [Thumbnail for LocalVariableInfoProcess.png]
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    But when I assign password = null; String "Java" should not be eligible for GC as It's is being referrenced from String literal pool till this program is running means that object should reside in heap. I tried below code and generated heap dump same like previous code.
  • In above code although "JAVA" is no more being referred by any reference variable in code but It is still referrenced by String literal pool so this heap dump should show the String value "JAVA" the way It showed in previous case where we didn't assign password = null But It doesn't show String "JAVA" in heap.
  • Here you can see in FOLLOWING picture, I followed same process like previous example but here only String[] means args is available in local vaiables BUT String is not available. Does that mean "JAVA" has been GC?
  • If yes then why the link of article I provided in previous post says, It should never be eligible for GC?
  • I know It's been too many posts on this thread but this is my final doubt so please...

    onlyStringarg-.png
    [Thumbnail for onlyStringarg-.png]
     
    Joe Bishara
    Ranch Hand
    Posts: 175
    17
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ganesh Patekar wrote:Does that mean "JAVA" has been GC?

    Using jhat (not VisualVm), I found the String object in the heap dump even after setting its reference to null.

    P.S.
    Setting an object's reference to null makes the object eligible for GC (if it is no longer referenced); however there is no guarantee that an object that is eligible for garbage collection will be garbage collected because you never know when the garbage collector will run.
    JHAT_1X.jpg
    [Thumbnail for JHAT_1X.jpg]
    String password = "JAVA";
    JHAT_2X.jpg
    [Thumbnail for JHAT_2X.jpg]
    String password = "JAVA_NULL"; password = null;
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Joe Bishara wrote:Using jhat (not VisualVm), I found the String object in the heap dump even after setting its reference to null.
    Will you please tell me exactly where you found that link I mean under which titles or subtitles? I searched a lot for that but couldn't found so tried with VisulVm.

    P.S.
    Setting an object's reference to null makes the object eligible for GC (if it is no longer referenced); however there is no guarantee that an object that is eligible for garbage collection will be garbage collected because you never know when the garbage collector will run.


    But here Strings, Literally by Corey McGlone says
    Strings, Literally by Corey McGlone wrote:Just before the main method ends, how many objects are available for garbage collection? 0? 1? 2?

    The answer is 1. Unlike most objects, String literals always have a reference to them from the String Literal Pool. That means that they always have a reference to them and are, therefore, not eligible for garbage collection. This is the same example as I used above so you can see what our picture looked liked originally there. Once we assign our variables, one and two, to null, we end up with a picture that looks like this:

    See examples and diagram what says


    Example-Diag-1-and-2.png
    [Thumbnail for Example-Diag-1-and-2.png]
    Example1,2 and Diagram 1,2
    ExampleDiag-3.png
    [Thumbnail for ExampleDiag-3.png]
     
    Joe Bishara
    Ranch Hand
    Posts: 175
    17
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ganesh Patekar wrote:Will you please tell me exactly where you found that link I mean under which titles or subtitles? I searched a lot for that but couldn't found so tried with VisulVm.

    I used Stephan's post as a guide.

    Stephan van Hulst wrote:There's a link to a page that will show you instance counts of classes (including platform classes). Then you click the link to String instances. Then the password you entered will be among the instances listed, if it hasn't been garbage collected yet.

    JHAT_3X.jpg
    [Thumbnail for JHAT_3X.jpg]
    JHAT_4X.jpg
    [Thumbnail for JHAT_4X.jpg]
    JHAT_5X.jpg
    [Thumbnail for JHAT_5X.jpg]
     
    Joe Bishara
    Ranch Hand
    Posts: 175
    17
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ganesh Patekar wrote:But here Strings, Literally by Corey McGlone says...

    In your previous post,

    Ganesh Patekar wrote:Does that mean "JAVA" has been GC?

    you asked if the String literal "JAVA" has been garbage collected and the answer to that question is that it has not. It is still in the heap. String literals are never eligible for GC while a program is running because they are always referenced. The point I was making is that when using a tool like jhat to analyze the heap, you cannot tell exactly when an object that is eligible for GC will be garbage collected. You cannot make an object eligible for GC and expect that it will immediately be garbage collected.
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Now I can sleep well , yes finally I found that , Yes Stephan's post clearly mentioned that but don't know where I was searching, your picture made me trace that Thank you so much.  

    Joe Bishara wrote:String literals are never eligible for GC while a program is running because they are always referenced.
    This is what I wanted to confirm.
    Once again, Thank you so much all of you, really great support from you all.
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 7992
    143
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Another little tidbit to think about; if String literals wouldn't have been interned into the String pool, in some circumstances they would never even appear in the heap in the first place. If an object is created inside a method call, and a reference to that object doesn't escape the method, then the object may live on the stack rather than the heap and will be 'collected' automatically when the method call finishes.

    Because String literals refer to objects that are outside the method (in the String pool), they can't live on the stack.
     
    Daniel Cox
    Ranch Hand
    Posts: 231
    12
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Stephan van Hulst wrote:If an object is created inside a method call, and a reference to that object doesn't escape the method, then the object may live on the stack rather than the heap and will be 'collected' automatically when the method call finishes.

    In recent years, Java has been moving at an amazing pace and its hard to keep up sometimes. I hear that this escape analysis has been around since Java 6 and I only recently heard about it.
     
    Campbell Ritchie
    Marshal
    Posts: 56576
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    You don't need to know about such optimisations to write good programs, however.
     
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Stephan van Hulst wrote:If an object is created inside a method call, and a reference to that object doesn't escape the method, then the object may live on the stack rather than the heap and will be 'collected' automatically when the method call finishes. Because String literals refer to objects that are outside the method (in the String pool), they can't live on the stack.
    Yes that is NoEscape  state, one of the three possible escape states of an object.
    Java SE 8 doc wrote:Escape analysis is a technique by which the Java Hotspot Server Compiler can analyze the scope of a new object's uses and decide whether to allocate it on the Java heap.
    Escape analysis is supported and enabled by default in Java SE 6u23 and later.

    I read about it here Java SE 8 Doc and in Escape Analysis for Java paper which present algorithm for escape analysis of objects in Java programs to determine following things
    1. If an object can be allocated on the stack;
    2. If an object is accessed only by a single thread during its lifetime, so that synchronization operations on that object can be removed.
    then according to that
  • If I'm not wrong strOne String object will be created on heap and it's reference will be stored in String literal pool as at the begining String literal pool is always empty.
  • When method compareStrings gets invoked then strTwo String object will be created in the frame of compareStrings method on stack because here object referred by strTwo, doesn't escape compareStrings method means there is no more reference to this object outside of compareStrings method.
  • I think if both are not at same location then strOne == strTwo should return false. Why It is returning true?  
  •  
    Ganesh Patekar
    Bartender
    Posts: 726
    23
    Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:You don't need to know about such optimisations to write good programs, however.
    I also think so.
     
    Campbell Ritchie
    Marshal
    Posts: 56576
    172
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ganesh Patekar wrote:. . . I think if both are not at same location then strOne == strTwo should return false. Why It is returning true?  
    When the JVM loads a class, it checks all String literals (and String compile‑time constants). If two String literals have the same contents (i.e. string1.equals(string2) returns true), they are interned. If they both have the same content, they are converted to the same object in the String pool.

     
    Daniel Cox
    Ranch Hand
    Posts: 231
    12
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ganesh Patekar wrote:When method compareStrings gets invoked then strTwo String object will be created in the frame of compareStrings method on stack...

    Take a look at the statement made by Stephan van Hulst. He's saying that String literals do not live on the stack and you're saying that a String literal lives on the stack.

    Stephan van Hulst wrote:Because String literals refer to objects that are outside the method (in the String pool), they can't live on the stack.





     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!