Boolean Class


A Boolean type is declared with the boolean keyword and can only take the values true or false:

 boolean isJavaFun = true;
 boolean isFishTasty = false;
 System.out.println( isJavaFun   );     // Output: true
 System.out.println( isFishTasty );     // Output: false

A Boolean expression is a Java expression that returns a Boolean value: true or false. You can use a comparison operator, such as the greater than (>) operator, to find out if an expression (or a variable) is true:

 int x = 10;
 int y = 9;
 System.out.println( x > y );     // Returns true.
 System.out.println( x == y );    // Returns false.

Java provides the java.lang.Boolean class which wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean. In addition, this class provides many methods for converting a Boolean to a String and a String to a Boolean, as well as other constants and methods useful when dealing with a boolean.

The bubble sort algorithm is given on the right. It repeatedly steps through the list to be sorted, compares each pair of adjacent items, and swaps them if they are in the wrong order.

procedure bubbleSort( A : list of sortable items )
  n = length(A)
  repeat
    swapped = false
    for i = 1 to n-1 inclusive do
      /* if this pair is out of order */
      if A[i-1] > A[i] then
        /* Swap them and remember something changed. */
        swap( A[i-1], A[i] )
        swapped = true
      end if
    end for
    n = n - 1
  until not swapped
end procedure

The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. Below is the program implementing the algorithm, where a list of unsorted integers is sent through the command-line arguments, args.

BubbleSort.java (bubble sort)

 public class BubbleSort {
   public static void main( String[ ] args ) {
     int     j = 0, tmp;
     Boolean swapped  = true;

     Integer array[ ] = new Integer[args.length];
     for ( int i = 0; i < args.length; i++ )
       array[i] = Integer.parseInt( args[i] ); 

     while (  ) {
       swapped = false;   j++;
       for ( int i = 0; i < array.length - j; i++ )
         if ( array[i] > array[i + 1] ) {
           tmp          = array[i];
           array[i]     = array[i + 1];
           array[i + 1] = tmp;
           swapped      = true;
         }
     }
     for ( int i = 0; i < args.length; i++ )
       System.out.print( array[i] + " " );
   }
 }
Integers to be sorted:            




      A cat in gloves catches no mice.