Wow just figured this out, before you read further down try thinking what the method below is going to outprint.
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:
(Random episode i’m watching).
The video pertaining to that method I created above is ‘Strings & StringBuffers’.
Basicly saying that instead of:
String s = "hello";
You should use this to save the JVM from creating more memory weight:
String s1 = new String("hello");
Or, if you were to go:
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)
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:
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.