constructors

class Test42

{

String str=new String("Hello");

public static void main(String args[])

{

Test42 a = new Test42();

System.out.println(a.str);

}

}

can any one tell me why is the output coming as hello and why is an error not generated. str is an instance member of class Test42 and should be initialized only inside the it's constructor which i have not done. Then why is an error not generated here. Plz help.

[469 byte] By [javneetgambhira] at [2007-10-2 6:44:42]
# 1
The lineString str=new String("Hello");also initialises str for any Test42 you create.
pbrockway2a at 2007-7-16 13:53:12 > top of Java-index,Java Essentials,New To Java...
# 2

> initialized only inside the it's constructor which i

Nope, it in inited before the ctor, this would be inside the ctor.

String str;

Test() {

str = "Hello";

}

> have not done. Then why is an error not generated

> here. Plz help.

If no ctor exists, the compiler creates one for you.

mlka at 2007-7-16 13:53:12 > top of Java-index,Java Essentials,New To Java...