+ 1

String interning in java.

Can anybody explain string interning, string pool and intern() method of java ?

15th Oct 2017, 2:12 PM
Sbk0103 - avatar
3 Answers
+ 4
The intern() method will forcefully check the SCP to see if a String is already defined with that value. If it is, no new String will be created. The SCP is an optimization by JVM for Strings. If two Strings have the same value, it will only create one and have both variables point to that one String. This works since Strings are Immutable. String a = "Totes"; a += "bob"; When I wrote a += "bob", a new String with the value "Totesbob" was created. This is also why concatenation is considered slow for Strings. In order for the SCP to not effect the runtime of the code, JVM will determine what Strings have the same value at compile time. So, in lots of scenerios it may not be able to determine whether or not they have the same value (I believe it will only pool together constants, where the value is already defined without using a method¿). This is where intern() can come in handy. For example, If you have lots of Strings being taken as user input they won't be put as the same memory location unless intern() is used. This will avoid creating a new String and thus saving memory. You may also be able to save some computation time if you use intern() then compare with == instead of equals(). Although, you need to know == and the SCP well so this doesn't cause any issues. https://code.sololearn.com/cGquk1UvwLrJ/?ref=app
15th Oct 2017, 4:51 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
15th Oct 2017, 2:25 PM
Suhail Pappu
Suhail Pappu - avatar
@Suhail I need explaination and real usage of approach not google search link.. I already have searched it.. Thanks..
15th Oct 2017, 2:27 PM
Sbk0103 - avatar