String is an immutable class in Java. That means, once value has been assigned to a String, it can’t be changed and if changed, a new object is created.
Create
The most commonly used methods of creating a String are,
1. As object
String s = new String("Test");
2. As literal
String s = "Test"
Retrieve
String characters can be retrieved with the index.
Char x = s.charAt(8);
int pos = str.lastIndexOf("o");
Add/Update/Delete
str = "Hello" + str;
str = str.replace('e', 'E');
str = str.substring(0, 10);
In all the three cases, the result has to be reassigned to the value, else value will return unchanged.
Operations
Other operations we can do with a String are,
str.length(), str.equals(str1), str.indexof("t"), str.split("_") etc.
Memory
String objects are saved in the heap just like any other object. String literals are stored in a space called 'String pool' within the heap. If the same literal is already present in the pool, Java uses that instead of creating a new literal. This saves a lot of memory.
The reference variable is stored in the stack which holds the memory address of the String.
Wrapper classes
Just like String, Wrapper classes (Integer, Boolean, BigDecimal etc.) are also immutable because they are defined as final. So a set method cannot be used to alter its state once constructor sets the state value. So there is no need to synchronize String and Wrappers. Since immutable, they both can be used as map keys.
StringBuilder and StringBuffer
If there is a necessity to make a lot of modifications to Strings, then you should use StringBuffer or StringBuilder instead. The only difference between both of them is that a few methods of StringBuffer are synchronized. Because of this fundamental difference, concatenation of String using StringBuilder is faster than StringBuffer. Since they are mutable, no need to assign the result after any change.
StringBuilder sb=new StringBuilder("Hello "); // create
sb.append("World"); //insert
sb.replace(6,10,"Java"); //update
sb.delete(6,9); //delete
str = new StringBuffer(str).reverse().toString(); //reverse a String
No comments:
Post a Comment