Issue
I know the concept of String pool in PermGen area of heap. So when we do something like
String firstString = "Stack";
String secondString = "Stack";
both references firstString
and secondString
point to the same object in the pool. But I tried the same for a variable of type int.
int firstInt = 5;
int secondInt = 5;
if(firstInt == secondInt) {
System.out.println("Both point to same allocated memory");
} else {
System.out.println("Both point to different allocated memory");
}
and the result is Both point to same object
and when i tried
Integer firstInteger = new Integer(2);
Integer secondInteger = new Integer(2);
if(firstInteger == secondInteger) {
System.out.println("Both point to same object");
} else {
System.out.println("Both point to different object");
}
output is Both point to different object
I tried the same for char and the result is similar. So my question do we have pools for all primitive types like int
, char
? And when we actually create objects with same content using new ()
as in the second case mentioned above is the object cloned and stored in same pool area or is it outside the pool?
Solution
There is so much misconception in your post, it is hard even to start explaining. Get some decent book. For now, some facts that might help you:
- String is not a primitive type,
- there are no pools of primitive types, because there cannot be a reference to a primitive type (the answer saying that they are only kept on the stack is plain wrong!)
- if you use
new
, you bypass pools anyway; so executingnew String("ala")
will always create a new String object; you cannot change the semantics ofnew
; - if you want to use available pools, use factory methods on objects (like
Integer.valueOf
), they will - to some extent - pool instances (it is not viable or beneficial to pool all possible values ofIntegers
,Floats
etc.).
Answered By - fdreger
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.