String
Difference between .equals()
and ==
==
checks for references and.equals()
checks for content.
String s = "jizz";
String s1 = "jizz";
String s2 = new String("jizz");
s == s1; \\true, s1 do not create new obj. ref the same
s.equals(s1); \\true, content is the same
s == s2; \\false, s2 create new obj
s.equals(s2);\\true, content is the same
- Whenever a new string is created using String literal, a object is created in String constant pool, String constant pool resides under heap memory.
- If a string with same content is already available in the pool than new String type variable points to the object that is already there in the memory and new object does
not
created.
Difference between String, StringBuilder, StringBuffer
String
- immutable object
- The object created as a String is stored in the Constant String Pool
- Thread safe: String can not be used by two threads simultaneously
String a = "aa";
a = "bb";
//"aa" string still exists in string constant pool
//and its value is not overrided but we lost reference to the "aa".
StringBuilder
- StringBuilder is mutable
- stores the object in heap and it can also be modified
- StringBuilder is NOT thread safe. (Thus faster
StringBuffer
- StringBuffer is mutable
- StringBuffer has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe.
- StringBuilder is faster than the StringBuffer when calling the same methods of each class.
Swap Character in String
Since String objects are immutable, going to a char[] via toCharArray
, swapping the characters, then making a new String from char[] via the String(char[]) constructor would work.
String originalString = "abcde";
char[] c = originalString.toCharArray();
// Replace with a "swap" function, if desired:
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String(c);
\\ or String swappedString = String.valueOf(c);