DEV Community

Nsairithish
Nsairithish

Posted on

String handling in java

String is an object that represents sequence of characters. In Java, String is represented by String class which is located into java.lang package

It is probably the most commonly used class in java library. In java, every string that we create is actually an object of type String. One important thing to notice about string object is that string objects are immutable that means once a string object is created it cannot be changed.

string-handling-feature
In Java, Char Sequence Interface is used for representing a sequence of characters. Char Sequence interface is implemented by String, String Buffer and String Builder classes. This three classes can be used for creating strings in java.

char-string-handling-feature
What is an Immutable object?
An object whose state cannot be changed after it is created is known as an Immutable object. String, Integer, Byte, Short, Float, Double and all other wrapper classes objects are immutable.

Creating a String object
String can be created in number of ways, here are a few ways of creating string object.

1) Using a String literal

String literal is a simple string enclosed in double quotes " ". A string literal is treated as a String object.
2) Using new Keyword
We can create a new string object by using new operator that allocates memory for the object.

public class Demo{

public static void main(String[] args) {

String s1 = new String("Hello Java");
System.out.println(s1);
}

}

Each time we create a String literal, the JVM checks the string pool first. If the string literal already exists in the pool, a reference to the pool instance is returned. If string does not exist in the pool, a new string object is created, and is placed in the pool. String objects are stored in a special memory area known as string constant pool inside the heap memory.

String object and How they are stored

When we create a new string object using string literal, that string literal is added to the string pool, if it is not present there already.
Concatenating String
There are 2 methods to concatenate two or more string.

Using concat() method

Using + operator
1) Using concat() method
Concat() method is used to add two or more string into a single string object. It is string class method and returns a string object.
2) Using + operator
Java uses "+" operator to concatenate two string objects into single one. It can also concatenate numeric value with string object.

Top comments (0)