Sunday, March 04, 2007

Looping Instantiation of Objects in Java

/*Class: TestClass1
*Programer: Daniel Williams
*Date: March 4, 2007
*
*Inspired by:
* Recurse.java found at http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4905527
*
*Purpose: To simplify Recuse.java to a program I could understand and to test
* what was happening to the objects being instanciated inside of the loop
*
*
*/



class TestClass1 {

static double total = 0.0;
double idNum = 0.0;

public TestClass1() {
total++;
idNum = total;
System.out.print(TestClass1.total + "\t");
System.out.println(this.toString());
}

public static void main(String[] args) {

/*Only one of the following loop beginings may be enables at any given
* time. It is not nessicary for either to be enabled.
*/

for (int index = 0; index < 100; index++) {
//while (true) {

TestClass1 testObject = new TestClass1();

/*If neither of the above loop beginings are enabled, the following
* close bracket must be disabled to avoid a syntax error
*/

}

/*When either of the loops are enabled the testObject can not be
* refereced from outside of the loop and the following print statment
* must be disabled for the program to compile without errors.
*/

//System.out.println("Id# = " + testObject.idNum);
}
}

/*In the case that the for loop is enabled and the print statement is disabled
* the program compiles and runs.
*
*Example output:
*
* 1.0 TestClass1@f72617
* 2.0 TestClass1@1e5e2c3
* 3.0 TestClass1@18a992f
* 4.0 TestClass1@4f1d0d
* 5.0 TestClass1@1fc4bec
* 6.0 TestClass1@8dc569
* ...
* 100.0 TestClass1@19616c7
*/

/*In the case that all of the loops are disabled and the print statement is
* enabled the program compiles and runs.
*
*Example output:
*
* 1.0 TestClass1@f72617
* Id# = 1.0
*/

/*In the case that the for loop is enabled and the print statement is enabled
* the program throws an error durning compilation.
*
*Example error:
*
* TestClass1.java:50: cannot find symbol
* symbol : variable testObject
* location: class TestClass1
* System.out.println("Id# = " + testObject.idNum);
* ^
* 1 error
*/

/*The only conclusion I can draw from this is that during the course of each
* loop, the testObject is instatiated, and then trash collected. This means
* that only only one instance of TestClass1 would exist at a time, and that
* the testObject instance would not exist after the completion of the loop.
*/