String object creation with and without new

What is the difference between below statements?
1. String str = “Hello”;
In this case, “Hello” memory is allocated during compile time itself, and str refers to “Hello” String literal address. Also note that

String str_a = “Hello”;
String str_b = “Hello”;
Both of these refers to same String object, and another object does not get created for str_b.

2. String str1 = new String(“Hello”);

In case of new version, “Hello” is dynamically allocated during run time, and “Hello” gets memory allocate on Heap.
String str1 = new String(“Hello”);
String str2 = new String(“Hello”);
Both of these refers to different String object, and another object gets created for str2

Below is an example showing the same


public class Stringnew {
public static void main(String args[])
{
	String str_a = "Hello";
	String str_b = "Hello";

	String str1 = new String("Hello");
	String str2 = new String("Hello");

	if(str_a==str_b)//== checks address location
	{
		System.out.println("if(str_a==str_b)");
	}
	else
	{
		System.out.println("else (str_a==str_b)");
	}

	if(str_a.equals(str_b))//equals() checks content
	{
		System.out.println("if str_a.equals(str_b)");
	}
	else
	{
		System.out.println("else str_a.equals(str_b)");
	}

	if(str1==str2)//== checks address location
	{
		System.out.println("if str1.equals(str2)");
	}
	else
	{
		System.out.println("else (str_a==str_b)");
	}

	if(str1.equals(str2))//equals() checks content
	{
		System.out.println("if str1.equals(str2)");
	}
	else
	{
		System.out.println("else str1.equals(str2)");
	}
}
}

Output:
if(str_a==str_b)
if str_a.equals(str_b)
else (str_a==str_b)
if str1.equals(str2)

You may also like to read:
Difference between == and equals()
Can String be inherited?
How to override toString()

One thought on “String object creation with and without new”

Leave a Reply