Java OCAJP7: boolean variable initialization

In Java is possible to initialize a boolean variable during its declaration with the result of an expression evaluation. For example we can use the result of two integer literals comparison to initialize our boolean variable.

public class JavaCertification  {
	public static void main(String[] args) {  
		boolean b = 3>=2;
		System.out.println(b); 
	}
}

This snippet of code compiles without errors and gives us the following result:

true

Let’s look to another example where we declare two int variables and we use them to initialize a boolean variable with the result of the equality test between them. This is not so readable so it would be better to avoid this syntax, but it’s valid and doesn’t produce any compilation errors.

public class JavaCertification  {
	public static void main(String[] args) {  
		int x = 1;
		int y = 2;
		boolean b = x==y;
		System.out.println(b); 
	}
}

Again, the result will be:

false
This entry was posted in $1$s. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *