LogicTable: results of logical operations in Java

Here is a program in two files: LogicTable.java and LogicTableDemo.java, that demonstrates results of logical operators, &&, ||, and ! in Java:

// LogicTableDemo.java: print two forms of a table showing
//   Java logical operators
public class LogicTableDemo {
   public static void main(String[] args) {
      LogicTable logicTable = new LogicTable();
      logicTable.displayTable(1);
      logicTable.displayTable(2);
   }
}


// LogicTable.java: print one of two forms of a table of Java // logical operators public class LogicTable { private boolean form1; // keeps track of which form we're printing // displayTable: print the entire table public void displayTable(int form) { form1 = true; // first form by default if (form != 1) form1 = false; // second form displaySeparator(); displayHeader(); displaySeparator(); displayLine(true, true); displayLine(true, false); displayLine(false, true); displayLine(false, false); displaySeparator(); System.out.println(); } // displaySeparator: print separator between lines private void displaySeparator() { for (int i = 0; i < 7; i++) System.out.print("+-------"); System.out.println("+"); } // displayHeader: print the header line private void displayHeader() { System.out.println("| a | b | a" + (form1 ? "||" : "&&") + "b |!(a" + (form1 ? "||" : "&&") + "b)| !a | !b | !a" + (form1 ? "&&" : "||") + "!b|"); } // displayLine: print one of the four data lines private void displayLine(boolean a, boolean b) { System.out.println("| " + pad(a) + " | " + pad(b) + " | " + (form1 ? pad(a||b) : pad(a&&b)) + " | " + (form1 ? pad(!(a||b)) : pad(!(a&&b))) + " | " + pad(!a) + " | " + pad(!b) + " | " + (form1 ? pad(!a&&!b) : pad(!a||!b)) + " |"); } // pad: put an extra blank on "true" so it matches "false" private String pad(boolean c) { String s = new String(c+""); if (c) s += " "; return s; } }
Here is the output when the Java program is run:
 
+-------+-------+-------+-------+-------+-------+-------+
|   a   |   b   |  a||b |!(a||b)|   !a  |   !b  | !a&&!b|
+-------+-------+-------+-------+-------+-------+-------+
| true  | true  | true  | false | false | false | false |
| true  | false | true  | false | false | true  | false |
| false | true  | true  | false | true  | false | false |
| false | false | false | true  | true  | true  | true  |
+-------+-------+-------+-------+-------+-------+-------+

+-------+-------+-------+-------+-------+-------+-------+
|   a   |   b   |  a&&b |!(a&&b)|   !a  |   !b  | !a||!b|
+-------+-------+-------+-------+-------+-------+-------+
| true  | true  | true  | false | false | false | false |
| true  | false | false | true  | false | true  | true  |
| false | true  | false | true  | true  | false | true  |
| false | false | false | true  | true  | true  | true  |
+-------+-------+-------+-------+-------+-------+-------+


Revision date: 2001-01-25. (Please use ISO 8601, the International Standard.)