String is a special class in java. It is the most widely used class in Java . It consists of immutable sequence of unicode characters and is object of class Java.Lang.
Why Java String is Immutable or final ?
String class is ubiquitous in Java code therefore its resource utilization must be efficient in order to judicially use heap memory. Java string holds some data which needed to be unmodifiable/immutable in nature. Such as, db connection URL, cloud connection access keys etc needs to be immutable in nature and it must not get modified at any time.
Also, Strings are mostly used as a key in Hashmap. Hashmap locates or maps keys on the basis of hashcode principal, hence it is essential that the value of String remains constant after insertion of key-value pair or else retrieval can’t be performed which is based on the hashcode of keys.
String pool can only be used due to String immutability. Several string objects referring to same name will have references to single object created in pool. This enhances JVM memory utilization.
String is implicitly thread safe, i.e it can be used by multiple threads and its immutability will enable synchronization between multiple threads operating on it.
Operations on String such as ‘+’ or overloaded string concatenation operator, toUpperCase() generates new string in order to comply with String immutability.
String name = "shane";
String fullname = name + "warne";
System.out.println(name.equals(fullname)); //Not equal
String name1 = "shane";
System.out.println(name.equals(name1)); //equal
What is String pool in Java?
String pool facilitates efficient memory utilization for String class. It is a special memory unit located in heap.
String s1="devmedium";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("javablog");//creating javablog string by new keyword
System.out.println(s1); //devmedium
System.out.println(s2); //strings
System.out.println(s3); //javablog
String can be instantiated in two ways.
- String literals: In this method, first “devmedium” is searched in String pool, if it exists a new reference will be created for the same or else new object is created on string pool.
- Using new keyword: In this method, if pool consist of “javablog”, then one object is created in heap or else one object in heap and one in String pool is created.
In the above image, s1, s2, s3 is created using Java String literals. Since S1 and S3 has same String object, they are referring to same object in string pool. And to corroborate this, string equality checks have been done which shows s1 and s2 are equal as they are referring to same object and s3 is referring to different object.
Relevant Posts:
- Java Fundamentals – JVM
- Java Fundamentals – Static
- Polymorphism in JAVA
- 犀利士 ://www.devmedium.com/java-stream-api-introduction/”>Java Stream API