Tuesday, April 10, 2007

How to convert between boolean and int

Program

public class Main {
    public static void main(String[] args) {
        int i = booleanToInt(false);
        System.out.println(i);
        
        boolean b = intToBoolean(42);
        System.out.println(b);
    }
    
    /*
     * Returns 1 if the argument is true, 0 if the argument is false.
     */
    static int booleanToInt(boolean b) {
        return (b ? 1 : 0);  
    }
    
    /*
     * Returns false if the argument is 0, true for any other argument.
     */
    static boolean intToBoolean(int i) {        
        return (i == 0 ? false : true);
    }
}

Output

0
true

No comments: