Click to See Complete Forum and Search --> : Java language secret?


nanode
02-23-2001, 12:20 AM
Today a co-worker approached me and shared a strange technique some people use in their java code.

I can write it better than I can explain verbally:


public class FxCnx {
int a;
int b;

public FxCnx() {
System.out.println("" + a + " " + b);
}

{
a = 1;
System.out.println("Bull**** constructor 1");
}

{
b = 2;
System.out.println("Bull**** constructor 2");
}

public static void main(String[] args) {
System.out.println("main");
FxCnx x = new FxCnx();
}
}


Apparently the plain { } blocks get called before the constructor.

Check the console:


nanode@stout:~/myjava$ java FxCnx
main
Bull**** constructor 1
Bull**** constructor 2
1 2
nanode@stout:~/myjava$


Can someone fill me in?

Energon
02-23-2001, 01:29 AM
hmm... something tells me that it's being treated like static something in the class... a way to fake initialization w/o the constructor maybe... or it could be an "undocumented feature" of the way Java was created... I've never seen it as an official practice...

error27
02-23-2001, 02:40 AM
woah... that is pretty weird.

I would never have thought that those lines would be executed in that order.

cotfessi
02-23-2001, 11:20 AM
actually, the code between the {} on the same level as a method is known as a static initilizer(I'm not in front of my java book right now, so the name may be a little different) anway, the code within those block is excuted first, before the constructor, but only once per application - meaning that if you made some sort of a program that looped and created several "FxCnx " objects, the code between the {}s would be run the first time through the loop but subsequent times through the loop only the constructor itself would be run... like this:


public class stuff
{
public static void main(String[] args)
{
for(int i=0; i<5; i++)
new FxCnx();
}
}


would produce:

Bull**** constructor 1
Bull**** constructor 2
1 2
1 2
1 2
1 2
1 2

[ 23 February 2001: Message edited by: cotfessi ]