Wednesday, 31 December 2014

Java boolean Variable Default Value

I have read in a few places that the default value of a boolean variable is false so I decided to check for myself. My first attempt is shown in prog58 below:

andrew@UBUNTU:~/Java$ cat prog58.java
public class prog58
{
public static void main (String args[])
  {
  boolean b1;
  System.out.println("b1 is " + b1);
  }
}
andrew@UBUNTU:~/Java$ javac prog58.java
prog58.java:6: variable b1 might not have been initialized
  System.out.println("b1 is " + b1);
                                ^
1 error
andrew@UBUNTU:~/Java$


My second attempt is shown in prog59 below, which does suggest that the default value of a boolean variable is false:

andrew@UBUNTU:~/Java$ cat prog59.java
public class prog59
{
static boolean b1;
public static void main (String args[])
  {
  System.out.println("b1 is " + b1);
  }
}
andrew@UBUNTU:~/Java$ javac prog59.java
andrew@UBUNTU:~/Java$ java prog59
b1 is false
andrew@UBUNTU:~/Java$


The two programs are slightly different. Once I have worked out why one seems to work and the other does not, I will let you know.