Java String Tutorial

4 Flares Twitter 0 Facebook 0 Google+ 4 LinkedIn 0 Filament.io 4 Flares ×

Understanding and mastering the usage of String class is a very important goal in learning java and it can actually go a long way in writing effective, efficient code.

What is a  Java String 

A String is nothing but a sequence of characters. String is a class in java language.

How do I create a String 

Easiest way to create a String is using the literal notation. For instance, String s=”Hello”; Here the sequence of characters are enclosed with in the quotes. Whenever the compiler encounters such String literals it actually creates a String object and initializes it with the literal value. Remember String is a java Object. Like any other objects, a String can be created using the new operator

What is so special about Strings 

Strings are constant and they are immutable. Their values cannot be changed after they are created. Because String objects are immutable they can be shared. When you use a String literal , java checks whether such a string exists in the Constant pool and if it exists, it just points to it. If not, a new string is created in the constant pool.  That means when you execute a program like

This will not create a million strings – of  value “apple”. All references of   ‘t’ refers to  the same object each time. But if you use a new Operator

a million objects will be created in heap all having the value “apple” and one entry will be created in the String constant pool of value “apple”. So a total of million +1 objects gets created.  Note that if there is already an  entry in the String constant pool with value “apple”, then a million objects will be created. There is no need for the entry in Constant pool, as it already exists.

String Constant Pool

To minimize the number of String objects created, JVM keeps a special memory called String Constant Pool. Every time we create a  String literal, JVM checks this pool and if that String already exists in the pool, a reference to that is returned. If this String doesn’t exist in the pool, a new String object gets created in the pool. All String literals of the same value ( text)  refers to the same object in the pool. But when you explicitly create a String object using the new Operator, the constant pool is not checked, JVM simply creates a new object in the heap.

Reference

Oracle String Tutorial

  • farooq

    good information on String. Can you please give similar information for String[] also. How it stores. How memory consumes..