+ 3

Default value of boolean

The docs state that boolean's default value is false http://bit.ly/2r0LA7y. Still if I try to use an uninitialized boolean variable, I get an error https://code.sololearn.com/cI8Y2SAIyifB/#java Seems like I'm missing something very simple. But what?

28th May 2017, 8:23 AM
Ivan Osadchiy
Ivan Osadchiy - avatar
3 Réponses
+ 5
@Dayve thanks man! In other words, the answer is that local variables are not initialized in Java. Quote from the docs: > Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error
28th May 2017, 8:37 AM
Ivan Osadchiy
Ivan Osadchiy - avatar
+ 15
Actually, you have to declare the Boolean variable(data-type) as static. This is because it is a primitive type : public class Program { static boolean b; public static void main(String[] args) { System.out.print(false); // prints "false" System.out.print(b); // prints "false" } } For more info : https://stackoverflow.com/questions/21950820/is-a-boolean-instance-variable-default-value-true-or-false
28th May 2017, 8:29 AM
Dev
Dev - avatar
+ 11
@Ivan You're always welcome ^_^ and that's right...
28th May 2017, 8:39 AM
Dev
Dev - avatar