Wednesday, January 3, 2018

String in java

  • In java, strings are objects that represents a sequence of characters. 
  • java.lang.String class is used to create string object. 
  • String objects are immutable. 
  • java.lang.String class is final. 
  • java.lang.String class is Serializable.


Create String object

In java, there are 2 ways to create String object:
  1. By using string literal
  2. By using new keyword

1- String literal

In Java String literals are created by using double quotes.

String str="india";

When we create a string literal, the JVM checks the string in constant pool first. If the string already available in the pool, a reference of the pooled instance is returned. If string doesn't available in the pool then a new string instance will created and stored in the constant pool.

String str1="india"; 
String str2="india";  // No new instance created


In this case only one object will be created. Firstly JVM will not find any string object with the value "india" in string constant pool, so that it will create a new object. After that it will find the string with the value "india" in the pool then it will not create any new object but will return the reference of the same available instance.

Note: String objects are stored in a special kind of memory area known as string constant pool.

2- new keyword

String str=new String("india");   // Creates 2 objects and 1 reference variable    


In this case, JVM will create a new string object "india" in (non pool) heap memory and checks the availability in String constant pool area. If not exists then store the one copy of literal "india" in String constant pool area for future reference. The variable "str" will refer to the object in heap(non pool).

Java String sample example

public class SampleExample {  
  
public static void main(String args[]) {  
    String str1 = "india";  
    String str2 = new String("sample example");  
    System.out.println(str1);  
    System.out.println(str2);  
}  

Output:
india
sample example

Note:
Java Library provides 4 classes to represent & manipulate a string:
    1. String
    2. StringBuffer
    3. StringBuilder
    4. StringTokenizer
We will discuss in upcoming topics.

1 comment:

  1. Well explained string internal functionality, useful for interview...

    ReplyDelete

Java Functional Interface

Java Lambda expression Lambda expression came to enable to use functional programming feature in java. It provides the facility t...