Java String

What is Java String

String is a sequence of characters. Java String class is present in java.lang package to create string object.

How to create String object?

Java provide two ways to create String object.

  1. By String literal
  2. By new keyword

1. String literal

This is the most common way of creating string. In this case a string literal is enclosed with double quotes.

When we create a String using String literal, JVM looks first into String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.

Example: String str = "Hello Java";

Here, JVM first looks "Hello Java" into String pool. If "Hello Java" already stored in String pool, than str wiil refrence to that object. Otherwise new String Object with value "Hello Java" will create in String pool.

2. By new keyword

We can create String object using new operator, just like any normal java class. 

Example: String str = new String("Hello Java");

Here, JVM will create a new string object "Hello Java" in heap memory and the string literal "Hello Java" will be placed in the string constant pool.

NOTE: here two object and one refrence will create.