03 - Java String
What is String?
String is an object that represents a collection of characters. String class is used to create string object.
Difference between String and StringBuffer
1) String class is immutable. StringBuffer class is mutable. 2) String is slow and consumes more memory when you concat too many strings because every time it creates new instance. StringBuffer is fast and consumes less memory when you cancat strings. 3) String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method. StringBuffer class doesn't override the equals() method of Object class.
Difference between StringBuffer and StringBuilder?
1) StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously. StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously. 2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
Substring:
A part of string is called substring. 1) public String substring(int startIndex) 2) public String substring(int startIndex,int endIndex)
Why String objects are immutable in java:
Because java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object "sachin". If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.
String isEmpty()
String isEmpty() method checks if this string is empty. It returns true, if length of string is 0 otherwise false.
String valueOf()
String valueOf() method converts different types of values into string.
StringBuffer class
StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.
StringBuilder class
StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized.
String comparison:
There are 3 ways to compare the String objects: 1) By equals( ) method : It compares values of string for equality. 2) By == operator : It compares references, not values. 3) By compareTo( ) method : It compares values and return an int which tells if the values compare less than, equal or greater than.
toString() method
If you want to represent any object as a string, toString() method comes into existence. The toString() method returns the string representation of the object.
StringTokenizer class
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break string.