Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we have pools for all primitive types in PermGen area of Heap?

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?

like image 217
Aniket Thakur Avatar asked Dec 15 '22 10:12

Aniket Thakur


1 Answers

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 executing new String("ala") will always create a new String object; you cannot change the semantics of new;
  • 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 of Integers, Floats etc.).
like image 119
fdreger Avatar answered May 10 '23 10:05

fdreger