I am new please dont mind if you find the question dumb.I was messing with singleton code.I changed it a bit(My question has nothing to do with singleton and yes I have removed single instance check).My question is though a class instance in java can only be one why there are two static class "instance" in output(see hash).I know "new" keyword will give a new memory address(thats what is getting printed in hash) but isn't static class instance supposed to be one?So I am getting two hashes for printing object instance,static variable k has same value,which is fine.
public class Singleton { private static Singleton instance; static int k; public static Singleton getInstance(){ try{ instance = new Singleton(); System.out.println(instance); }catch(Exception e){ throw new RuntimeException("Exception occured in creating singleton instance"); } return instance; } public static void main(String[] ar) { Singleton c1=Singleton.getInstance(); c1.k=1; Singleton c2=Singleton.getInstance(); c2.k=2; System.out.println(c1.k); System.out.println(c2.k); } } Output:
Singleton@15db9742 Singleton@6d06d69c 2 2
getInstance()is called.staticmeans only 1 variable instance. It has nothing do with how many object instances you create.getInstance()method is called.static Singleton s=new Singleton()is perfectly allowed, as long as that definition is in a class body, not in a method body.