JAVA - String and StringBuilder
Abhinav Pandey
Posted on April 10, 2021
String
- Single copy of each String literal is maintained in String pool.
- Since literals are immutable, they can be safely referenced by multiple variables. (interning)
- Use variable.intern() to return the literal referenced by the String variable. E.g.
String str2 = str1.intern();
- Initializing using "new" (not recommended as it will not reuse string pool literals) - E.g.
String str1 = new String("Hello"); // or
String str2 = new String(charArray); // charArray is character array
String Builder
- Mutable.
- Extra methods - append, insert, delete, reverse etc.
- Instantiated using "new". E.g.
StringBuilder sb = new StringBuilder(); //empty value
StringBuilder sb = new StringBuilder("Hello"); //value is hello
StringBuilder sb = new StringBuilder(10); //value is empty, default capacity(memory reserved) is 10
Capacity is elastic and will increase if more characters are added in the object.
Reading a character beyond current length(no. of characters stored) throws StringIndexOutOfBoundsException.
💖 💪 🙅 🚩
Abhinav Pandey
Posted on April 10, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
watercooler Why does a reboot make your PC run SO much faster than running all the cleaning tools you can possibly imagine?
November 30, 2024