1

I want to know that what's the difference in memory allocation if i use

String s = new String("This is a string");
System.out.println(s);
editText.setText(s);

and

System.out.println("This is a string");
editText.setText("This is a string");

Is there any kind of differnce in both the steps..??

2 Answers2

0

In your first case, you are initializing string using new operator, so your string will be created in heap as your string will be treated as a object.

In the second case, you are directly initializing string, so it will exist in String Constant Pool, as your string will be treated as literal. String Literals are created String Constant Pool.

Technically String constant pool has efficient memory management in java as String pool values are garbage collected if they are not in use.

user2068260
  • 373
  • 1
  • 3
  • 10
0

Yes but mostly because your first example is suboptimal. Your first example should have been:

String s = "This is a string";
System.out.println(s);
editText.setText(s);

A string constant is already a String object, there is no need to make a copy of it you can assign it directly to the variable.

Theoretical the second example is still different as it has a variable less but for all intends and purposes it is the same. The two identical strings are merged by the compiler into a single object. However the first version is better style because it is clearer you want the same string used in both statements and is thus easier to maintain.

Eelke
  • 20,897
  • 4
  • 50
  • 76