Boolean Values In Java

April 30, 2017
Categorised in: Java Core
Understanding Through Code
public class BooleanInJava { static boolean staticBool; //Remember primitives are assigned defaults public static void main( String[] args ){ boolean boolVal1 = true; boolean boolVal2 = false; System.out.println("boolVal1: " +boolVal1); System.out.println("boolVal2: " +boolVal2); System.out.println("staticBool: " +staticBool); boolean boolVal3 = !boolVal1; //negation of boolVal1 is assigned to boolVal3 System.out.println("boolVal3: " +boolVal3); int someInt = 1; boolean boolVal4 = (someInt != 1); System.out.println("boolVal4: " +boolVal4); String strBool = "false"; //this should be either true or false only boolean convertedBool = Boolean.parseBoolean(strBool); System.out.println("Parsing of boolean: " +convertedBool); } }
Output
- boolVal1: true
- boolVal2: false
- staticBool: false
- boolVal3: false
- boolVal4: false
- Pasrsing of boolean: false
Notes:
- Unassigned boolean variable defaults to false.
- We can use negation (!) to switch boolean values from true to false or vice versa.
- Expressions result can be captured in boolean variable
- E.g. someInt != 1;
- Boolean helper class lets you convert string to boolean type only if the string is either true or false.
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.