Wow just figured this out, before you read further down try thinking what the method below is going to outprint.
1 2 3 4 5 6 7 8 9
| public void test() { String s = "hello"; String s1 = new String("hello"); if (s == s1 || s1 == s) { System.out.println("TRUE"); } else if (s != s1) { System.out.println("FALSE"); } } |
Results: "FALSE".
I'm watching a series on youtube here:
http://www.youtube.com/watch?v=zHF0g-PDO5E&feature=related(Random episode i'm watching).
The video pertaining to that method I created above is 'Strings & StringBuffers'.
Basicly saying that instead of:
You should use this to save the JVM from creating more memory weight:
1
| String s1 = new String("hello"); |
Or, if you were to go:
1 2 3 4 5 6
| public String test() { String s = "hello"; String s1 = "world"; String s2 = s += s1; return s2; } |
It would save more space on the JVM/memory if you were to basically just complete the next method it's going to perform.
(Saving the JVM some heap memory)
1 2 3 4 5 6
| public String test() { String s = new String("hello"); String s1 = new String("world"); String s2 = new StringBuffer("hello").append("world").toString(); return s2; } |
Basically because with this method:
1 2 3 4 5 6
| public String test() { String s = "hello"; String s1 = "world"; String s2 = s += s1; return s2; } |
It's creating 2 Memory Heaps/Storing Memory for each String, because out of those Strings if it involves 's1 += s2' it than has to go through Java's StringBuffer class, as seen in the method above.
Hope this helps somebody out, looks like i'm going to start smart coding.