Showing posts with label Strings. Show all posts
Showing posts with label Strings. Show all posts

Sunday, 11 January 2015

SCJP notes: Strings, StringBuffer and StringBuilder

Strings
  • String are immutable objects, so when you trying to change it like: "s.concat("bla")" - you not changing the current object, you creating the new one
  • This statement String s = "dsfsf" creates new String literal in the run time constant pool and even if the reference for this literal is lost it still will exist (the most likely) in memory
  • This statement String s = new String ("dsfsf") will create two objects: one on the heap and second in the run time constant pool there is such String. And the variable will be reference to the String in the heap
  • If call the intern() method it will return the reference to the same String in  the run time constant pool, if there is no such string there it will create it
  • For Strings we can use the +=  operator to concatenation and assign in a one line
  • Important String methods: charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toString(), toUpperCase(), trim() 
  • If you ask charAt() with the index more than letters in the word-1(indexes starts with 0), you will get StringIndexOutOfBoundsException
  • If you ask substring() with the index more than letters in the word-1(indexes starts with 0), you won't get an exception, you will get an empty String
StringBuffer and StringBuilder

  • StringBuffer is StringBuilder
  • Important StringBuffer and StringBuilder methods: append(), delete(), insert(), reverse(), toString()
  • Almost all mentioned methods(except toString) returns the modified StringBuffer and StringBuilder object, but in comparison with String this methods change the object on which this methods will be called