String in Java?

Strings are immutable. A string can’t be altered once created. Applying a method on string won’t change string’s value; rather it will create a new string. String is also final, and so can’t be sub classed. When you assign one String variable to another, no copy is made. Even when you take a substring there is no new String created.
Creating String : String can be created by assigning string literals as shown below. The text between double quotes is a string literal. By assigning a string literal, you can avoid using the new keyword. In fact, this special shortcut syntax was designed to improve String performance. 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 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

Note: 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.

Related Post

What will be output of the following program?
String.intern in Java
Converting Date to String object
Converting String to Date object
String Number conversion in JavaScript

Comments

Leave a Reply