开发者

Java String variable [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help cen开发者_运维问答ter. Closed 11 years ago.

What's the difference of the following String s1, s2, s3, and s3:

class A {

String s1;

String s2 = null;

String s3 = "";

String s4 = new String();

...

}

I have checked the memory allocation by class A1 contains s1, class A2 contains s2, and so on. I found that they consumes memory differently. While s4 style consumes more memory than s3 is quite understandable. But s2 (set to null explicitly) and s1 (rely on smart compiler to set to the default value) are different too! s2 consumes 0 memory, while s1 consumes some non-zero memory. Why? Everyone says s1 and s2 are the same.


Let's see.

String s1;

Declares a new String variable, but does not initializes it. If this is a instance variable, it will be initialized to null, if it is a local variable, the compiler makes sure it is assigned at least once before each use.

String s2 = null;

Declares a new String variable, and initializes it with null. For an instance variable this is equivalent to the case before (but human readers don't have to memorize the default value).

String s3 = "";

Declares a new String variable, and initializes it with the canonical empty string. All such variables will contain (e.g. point to) the same String object.

String s4 = new String();

Declares a new String variable, and initializes it with a new empty string. This is a new object, not identical to any object which existed before. Doing this is almost never a good idea - for all real uses the s3 case is equivalent, and this uses more memory. If you rely on having different String objects (with same content), you are doing something wrong. (I think even the existence of this constructor is wrong.)


In general, instance variables should either get suitable values in the constructor (then you don't need to initialize them before), or default values if such values are acceptable for the usage of the object. Then it may be sensible to use s2 or s3 (but most often s2, I think).

For local variables, it often is useful not to initialize them, or initialize them right away with the value it really should have, instead of a dummy value like "" or null. Then the s1 variant will be more sensible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜