Some remarkable samples about String equals vs == comparator in Java.
You may have different output if you use == comparator instead equals for String test.
See sample code:
public class StringTest {
public static void main (String [] args){
testA();
testB();
}
static void testA(){
System.out.println (" testA");
// good memory usage!! RECOMENDED constructor
String s1 = "a";
String s2 = "a";
System.out.println (" s1 = \"a\"");
System.out.println (" s2 = \"a\"");
if (s1 == s2 ){
System.out.println (" s1 == s2 is true");
} else {
System.out.println (" s1 == s2 is false");
}
if (s1.equals(s2) ){
System.out.println (" s1.equals(s2) is true ");
} else {
System.out.println (" s1.equals(s2) is false ");
}
}
static void testB(){
System.out.println (" testB");
// waste memory !! NOT RECOMENDED CONSTRUCTOR FOR STRINGS
String s1 = new String ("a");
String s2 = new String("a");
System.out.println (" s1 = new String(\"a\")");
System.out.println (" s2 = new String(\"a\")");
if (s1 == s2 ){
System.out.println (" s1 == s2");
} else {
System.out.println (" s1 == s2 is false");
}
if (s1.equals(s2) ){
System.out.println (" s1.equals(s2) is true ");
} else {
System.out.println (" s1.equals(s2) is false ");
}
}
This is code output:
testA
s1 = "a"
s2 = "a"
s1 == s2 is true
s1.equals(s2) is true
testB
s1 = new String("a")
s2 = new String("a")
s1 == s2 is false
s1.equals(s2) is true
/**
* Comments :
* String offeres many constructors for Strings:
* in testA
* String s1 = "a"; create a literal "a" in pool memory ans s1 refers to it
* String s2 = "a"; s2 refers to same previous literal in pool.
*
* otherwise in testB
* String s1 = new String("a") ; because we use new keyword a new String object is created in not pool memory (s1 refers to it) and in addiction literal "a" is placed in pool memory;
* String s2 = new String("a") ; because we use new keyword a new String object is created in not pool memory and (different from previous) s2 refers to it
*/
}
Nessun commento:
Posta un commento