Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enum, how and when memory allocated per constant

Tags:

java

enums

I have simple enum class as given below. i want to know how memory is allocated to each constant( is Member class object is created for each constant) and what is its scope.

public enum Member {
    HAPPY("HAPPY"),RAhul("RAhul"),ANSAL("ANSAL");
    private String argument;

    Member(String arguments)
    {
        System.out.println("Enum Constructor work");
        this.argument = arguments;

    }
    public String getValue() {
        return argument;
    }

}
like image 224
user3586231 Avatar asked Jan 14 '15 19:01

user3586231


People also ask

How is memory allocated to enum?

On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less. The GCC C compiler will allocate enough memory for an enum to hold any of the values that you have declared. So, if your code only uses values below 256, your enum should be 8 bits wide.

How is enum stored in memory Java?

In Java, there should only be one instance of each of the values of your enum in memory. A reference to the enum then requires only the storage for that reference. Checking the value of an enum is as efficient as any other reference comparison.

How much memory does an enum use?

ENUMs require relatively little storage space compared to strings, either one or two bytes depending on the number of enumeration values.

Does enum take memory?

An enum does not really take any memory at all; it's understood by the compiler and the right numbers get used during compilation. It's an int, whose size is dependent on your system.


1 Answers

The members HAPPY("HAPPY"),RAhul("RAhul"),ANSAL("ANSAL"); are created when the enum class is loaded (i.e. their scope is static). Enums are compiled to normal classes that extend java.lang.Enum and its instances are allocated in the heap like other class objects.

Each member invokes the constructor that's defined in the enum which takes the string parameter.

This is from the relevant section in the Java Language Specification:

An enum constant may be followed by arguments, which are passed to the constructor of the enum type when the constant is created during class initialization as described later in this section. The constructor to be invoked is chosen using the normal overloading rules (§15.12.2). If the arguments are omitted, an empty argument list is assumed.

like image 61
M A Avatar answered Oct 29 '22 23:10

M A