String Handling in Java

String Handling



As you know whenever you take input or output from user in java you get always String type of data, and in Java String is a predefine class. That means the JVM create a new memory for String all the time then how to manage memory by JVM.

What is String in Java ?

String is a group of characters or sequence of characters.

String is a predefine class in Java which exist in java.lang package.

String is a final class in Java that means it can never be inherited.

String class implements Serializable, Comparable, CharSequence interface etc.

String objects are immutable that means when once created it can never be changed.

String Object always represented by double quotes.

You can create String object by the help of two way:

  1. Using Literals Concept
  2. Using new Keyword

Using Literals Concept

You can create String literals with double quotes like below:

String name="Deep Singh";

In case of Literals one reference variable and one object is created.

When you use String literals Concept JVM firstly check its in String Pool. If that object is exist then it will return the same address to the refrence variable.

For Example:

   
 String first="Deep";
 String last="Singh";
 String lname="Singh";

Using new keywords

You can create String instance by the help of new keyword like below:

String name=new String("Ashok Singh");

In case of new keyword there is a single reference variable two objects are created. one inside String or Constant pool and another one is inside Heap Area.

In case of new keyword by default it points Heap Area address.

For Example:

String name=new String("Ashok Singh");

String Objects are Immutable example.

String name="Deep";
name.concat("Singh");
System.out.println(name);
Result: Deep

2 comments:

Chandan said...

Very nice sir but am dout in Literals
Can you explan it....

Chandan said...

Very nice sir but am dout in Literals
Can you explan it....