+ 1
String interning in java.
Can anybody explain string interning, string pool and intern() method of java ?
3 Respuestas
+ 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
+ 1
https://dzone.com/articles/string-interning-what-why-and
0
@Suhail I need explaination and real usage of approach not google search link.. I already have searched it.. Thanks..