Basics about String (java.lang.String)
I guess this thing is non-avoidable when you are working in Java. Just trying to note down some very basic things about it. Took help of Java API
Strings are constant; their values cannot be changed after they are created. Applying a method on a String will create a new string. When you assign one String variable to another, no copy is made. Even when you take a substring there is no new String created. Some examples of using String below:
System.out.println("abc");String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);// Yes you can directly call function from literal string
String d = cde.substring(1, 2);
Each JVM only keeps one copy of each string literal. In the following code firstStr and secondStr points to same string reference. thirdStr creates a new String in String pool.
String is final class so you can not extend it.
String firstStr = "I am a String Literal";
String secondStr = "I am a String Literal";
// Points to the same object as firstString
String thirdStr = new String("I am a String Literal");// By using constructor, It will create a new Object in JVM
You almost always want to initialize String references with literals to avoid creating unnecessary objects in the JVM. This can really add up if you are creating hundreds of identical Strings.
Most Commented Posts
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments
No comments yet.
Leave a comment