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;
}
}
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.
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.
ENUMs require relatively little storage space compared to strings, either one or two bytes depending on the number of enumeration values.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With