user3658679 user3658679 - 2 years ago 68
Java Question

Java: Member object allocated in constructor destroyed?

I've been having some trouble understanding and finding information on a particular circumstance; if a member object is declared and initialized in a constructor, why is the allocation destroyed when the constructor finishes? It works okay for any other method that does the same thing, so I wondered if someone could clear this up for me.


public class Main {
Integer i;
public void Main() {
i = new Integer(5);
void init() {
i = new Integer(5);
public static void main(String[] args) {
Main m = new Main();

Output is:


Shouldn't the first output be 5 as well? Thanks in advance.

Answer Source

Your constructor should not contain void.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download