Strings
String is collection of characters.
String syntax:
String Concatenation
When using concatenation operator with strings, we should be careful.
This happened because of precedence...
Firstly, It became ("Sum is " + x) = Sum is 10
Then, It became ("Sum is 10" + y) = Sum is 1020
So, we can use braces to set the precedence.
Accessing String Characters
We can access each character using this method.
String Comparison
This happened because, when we created string variable s2 without new keyword, String s2 also started pointing to the same string to which s1 is pointing.
It is also called Interning.
But, using equals() function, the actual value of the string was compared, instead of its pointer.
String Lexicographic Comparison
If value is 0, means strings are equal.
If value is less than 0, means str1 is less than str2
If value is greater than 0, means str1 is greater than str2
For example,
Javais greater thanCpp, because (74 > 67) i.e. (J > C)ABCis smaller thanabc, because (65 < 97) i.e. (A < a)
String Builder
When we modify existing string, a new string is created inside the memory.
For example,
Now, a new string is created HelloA, and str will point to the new string.
This is because, Strings are immutable in java.
String Builder is a mutable string class.
toString() functions converts a object into string.
For example,
Adding Characters
We can add characters in the StringBuilder object, by using append() method.
It appends character to the end of the string.