Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variables Initializations

 
Jessica Lang
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great !! Have fun !!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic