String Handling in Java

  1. String Handling
  2. How to create string objects?
    1. String literal
    2. new keyword
  3. Why Java uses the concept of String literal?
String Handling provides a lot of concepts that can be performed on a string such as concatenating string, comparing string, substring etc.
In java, string is basically an immutable object. We will discuss about immutable string later. Let's first understand what is string and how we can create the string object.

String

Generally string is a sequence of characters. But in java, string is an object. String class is used to create string object.


Do You Know ?
  • Why String objects are immutable ?
  • How to create an immutable class ?
  • What is string constant pool ?
  • What code is written by the compiler if you concat any string by + (string concatenation operator) ?
  • What is the difference between StringBuffer and StringBuilder class ?

How to create String object?

There are two ways to create String object:
  1. By string literal
  2. By new keyword

1) String literal

String literal is created by double quote.For Example:
  1. String s="Hello";  
Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.For example:
  1. String s1="Welcome";  
  2. String s2="Welcome";//no new object will be created  
string literal
In the above example only one object will be created.First time JVM will find no string object with the name "Welcome" in string constant pool,so it will create a new object.Second time it will find the string with the name "Welcome" in string constant pool,so it will not create new object whether will return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool inside the Heap memory.

Why java uses concept of string literal?

To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

2) By new keyword

  1. String s=new String("Welcome");//creates two objects and one reference variable  

In such case, JVM will create a new String object in normal(nonpool) Heap memory and the literal "Welcome" will be placed in the string constant pool.The variable s will refer to the object in Heap(nonpool).

1 comments :

 
Top