String is the most commonly used class in Java programming language. In java every string we create is an object of String Class that implements Serializable, Comparable and CharSequence interfaces. It is nothing but a character array for example “AbhiAndroid” is a string of 11 characters as shown.
char[] test= { 'A' , 'b' , 'h' , 'i' , 'A' , 'n' , 'd' , 'r' , 'o' , 'i' , 'd' }; String testString= new String(test);
Strings are Immutable in nature, which means once string is created its value cannot be altered, but we can create a new Instance of it.
Immutable: Any object whose state cannot be altered once created are called Immutable objects. String, Integer, Byte, Short, all other wrapper class objects are immutable in nature.
Table of Contents
There are two ways by which String can be created:
Using String Literal
Strings can be created very easily, by assigning a string value to the string literal as shown:
String string1 = "Welocome to AbhiAndroid"; String string2 = "Welocome to AbhiAndroid";
As, discussed above String is a class, but we have not created any object above using new keyword, so how new object is created? Don’t worry compiler did your task. But problem here is that, if the object is already present in the memory compiler do not create a new object rather it assigns the same old object to the new instance created, which means even though we have two string instances above string1 and string2, compiler only creates one string object having the value “Welocome to AbhiAndroid” and assigns the same to both the instances String1 and String2.
Using New keyword:
As we saw above, by using only String literal compiler assigned the same string object to two different string literals, To overcome this approach we can create string using new keyword as shown
String string1 = new String(" Welocome to AbhiAndroid "); String string2 = new String(" Welocome to AbhiAndroid ");
In this approach compiler will create two different objects in memory having the same value.
Use character array for storing sensitive information likes passwords instead of Strings.
Premium Project Source Code: