File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Variables Initializations Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variables Initializations" Watch "Variables Initializations" New topic
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 !!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Variables Initializations
 
Similar Threads
Casting problem
Exception Q?
Exception Handling
Scope of variable declarartions in for loop
Ambiguity Error.