| Author |
Variables Initializations
|
Jessica Lang
Ranch Hand
Joined: Jul 23, 2002
Posts: 61
|
|
Hello, The following runs perfectly: ************************************************** *** VariableInit.java: public class VariableInit { boolean Boolean; } *** TestVariableInit.java: public class TestVariableInit { public static void main (String args[]) { VariableInit ActivateVariableInit = new VariableInit(); System.out.println ("boolean: " + ActivateVariableInit.Boolean); } } *** Output: boolean: false ************************************************** However, the following code generates Compilation error: *** TestVariableInit2.java public class TestVariableInit2 { public static void main (String args[]) { boolean Boolean; System.out.println ("boolean: " + Boolean); } } *** Compilation error: TestVariableInit2.java:17: variable Boolean might not have been initialized System.out.println ("boolean: " + Boolean); ^ 1 error ************************************************** Why TestVariableInit2.java program generates compilation error (but not TestVariableTest.java), even though all variables in both programs are not initialised. Thanks.....
|
 |
Ram Kumar Subramaniam
Ranch Hand
Joined: Jan 17, 2003
Posts: 68
|
|
|
Instance variables(variable that is declared inside the class but outside the methods) are initialized by default(in this case to false). Thats whey your first example works. However local variables(the variable that u mentioned inside your main method) are not initialized by default. Hence you get a compilation error.
|
 |
Jessica Lang
Ranch Hand
Joined: Jul 23, 2002
Posts: 61
|
|
Hi Ram, Thanks for the explanation. I tested the codes....initialising TestVariableInit2.java variable to false and it compiled perfectly. Then, I initialised the boolean variable in VariableInit.java to true. When I ran the TestVariableInit, it gave me a value of true (due to my earlier initilisation). By playing with the codes, it helps me to understand the "Java behaviour" better..... Thanks again.....
|
 |
Ram Kumar Subramaniam
Ranch Hand
Joined: Jan 17, 2003
Posts: 68
|
|
|
Great !! Have fun !!!
|
 |
 |
|
|
subject: Variables Initializations
|
|
|