-1

Possible Duplicate:
What is the difference between strings allocated using new operator & without new operator in java J2ME?

Difference between

String str=new String("Thamilan");

and

String str="Thamilan"; 

in java and j2me,with respect to memory constraints.

Community
  • 1
  • 1
  • sivakumar, Why you are asking [repeated question?](http://stackoverflow.com/questions/6952581/what-is-the-difference-between-strings-allocated-using-new-operator-without-new) – bharath Aug 05 '11 at 08:59

2 Answers2

1

You can calculate the memory allocation of string by following code

int NumOfBytes = 8 * (int) ((((no chars) * 2) + 45) / 8) ;
Coder
  • 1,917
  • 3
  • 17
  • 33
0

The first form creates a new String object each time you run it. The second form does not.

This applies to both Java SE and Java ME. Indeed, the basic representation of Java SE and Java ME strings is the same.


Using new String(...) is almost always unnecessary and wasteful. There is rarely any point having a new instance. All String objects are immutable in Java.

(There are rare situations where creating a new String is advisable. One is when you take a substring of a large String and that substring is likely to be reachable for much longer than the original one.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216