String Flashcards
Strings are IMMUTABLE
Strings are immutable so doing variable.concat(“abc”) will create a new string “abc” but will not affect the original string variable.’
*String class itself is final and so all of its methods are implicitly final.
String methods
*s.add(obj)–> return true if the obj was added to the list, all the other elem are pushed in the list
*indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
*indexOf(int ch, int fromIndex)
returns the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
*indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
*indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
*substring(int beginIndex)
Returns a new string that is a substring of this string.
–> if the index cannot be found it returns an empty string???????
String and StringBuilder and StringBuffer are FINAL classes(cannot be extended) and they all extend Object class
String compareTo()
“hello world”.compareTo(“Hello world”) < 0
The value returned by compareTo is =Unicode value of the left hand side - Unicode value of the right hand side!!!!!!
*for English alphabets, the unicode value of any lower case letter is always 32 more than the unicode value of the same letter in upper case. So, ‘a’ - ‘A’ or ‘h’ - ‘H’ is 32.
Note that int value of ASCII ‘a’ is 97, while that of ‘A’ is 65.
public String intern()
public String intern()
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned. String literals are defined in 3.10.5 of the Java Language Specification
Returns:
a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.
StringBuilder vs StringBuffer
String and StringBuffer are thread safe!(StringBuffer is implemented by using syncronised keywor on all the methods)
StringContactenation in loop is to be avoided as it creates unnecesary objects and performance issues. Use StringBuilder or StringBuffer instead!