Home

Introduction to Conditions

 

Boolean Variables

 

Introduction

When interacting with a computer, a user submits values to a running application. Some of these values are valid. Some other values must be rejected or changed. To take care of these, the values must be checked, examined, re-examined, etc. The validity of a value is checked against its type. For example, a number can be checked as being equal to another. A condition can be checked as being true. A measure can be checked as to whether it is higher than a certain threshold.

To perform the necessary validations of values, the Java language provides some symbols, referred to as Boolean operators.

HomePractical Learning: Introducing Boolean Values

  1. Start NetBeans
  2. Create a New Project as a Java Application and name it DepartmentStore2
  3. To create a new class, in the Projects window, inside the DepartmentStore2 folder, right-click the DepartmentStore2 sub-folder -> New -> Java Class...
  4. Specify the name of the class as StoreItem and click Finish
  5. Change the file as follows:
     
    package departmentstore2;
    
    public class StoreItem {
        long itemNumber;
        String itemName;
        double unitPrice;
    
        void createItem()
        {
            this.itemNumber= 792475;
            this.itemName = "Lightweight Jacket";
            this.unitPrice = 185.00D;
        }
    
        void showItem()
        {
            System.out.println("Department Store");
    
            System.out.println("Stock #:    " + this.itemNumber);
            System.out.println("Name:       " + this.itemName);
            System.out.println("Unit Price: " + this.unitPrice);
        }
    }
  6. Access the Main.java file and change it as follows:
     
    package departmentstore2;
    
    public class Main {
        static void main(String[] args) {
            StoreItem dptStore = new StoreItem();
    
            dptStore.createItem();
            dptStore.showItem();
        }
    }
  7. Execute the application. This would produce:
     
    Department Store
    Stock #:    792475
    Name:       Lightweight Jacket
    Unit Price: 185.0

Declaring a Boolean Variable

A variable is referred to as Boolean if it can hold a value that is either true or false. To declare a Boolean variable, you can use the boolean keyword. Here is an example:

public class Exercise {
    static void main(String[] args) {
        boolean drinkingUnderAge;
    }
}

After the variable has been declared, you must initialize it with a true or a false value. Here is an example:

public class Exercise {
    static void main(String[] args) {
        boolean drinkingUnderAge = true;
    }
}

To display the value of a Boolean variable, you can type its name in the parentheses of the System.out.print() or the System.out.println() methods. Here is an example:

public class Exercise {
    static void main(String[] args) {
        boolean drinkingUnderAge = true;
        
        System.out.print("Drinking Under Age? ");
        System.out.println(drinkingUnderAge);
    }
}

This would produce:

Drinking Under Age: True

In the parentheses of System.out.print() or System.out.println(), you can concatenate a string and a boolean variable. To do this, use the + operator. Here is an example:

public class Exercise {
    static void main(String[] args) {
        boolean drinkingUnderAge = true;
        
        System.out.println("Drinking Under Age? " + drinkingUnderAge);
    }
}

To display the value of a Boolean variable using System.out.printf(), use the %b expression.

After declaring and initializing a Boolean variable, at any time and when you judge it necessary, you can change the value of the Boolean variable by assigning it a true or false value. Here is an example:

public class Exercise {
    static void main(String[] args) {
        boolean drinkingUnderAge = true;

        System.out.println("Drinking Under Age: " + drinkingUnderAge);

        drinkingUnderAge = false;
        System.out.println("Drinking Under Age: " + drinkingUnderAge);
    }
}

This would produce:

Drinking Under Age: True
Drinking Under Age: False

Retrieving the Value of a Boolean Variable

As reviewed for the other data types, you can request the value of a Boolean variable from the user. In this case, the user must type either True (or true) or False (or false) and you can retrieve it using the Scanner.nextBoolean() methods. Here is an example:

import java.util.Scanner;

public class Exercise {
    static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        boolean drivingUnderAge = false;

        System.out.println("Were you driving under age?");
        System.out.print("If Yes, enter True. Otherwise enter False: ");
        drivingUnderAge = input.nextBoolean();

        System.out.println("Was Driving Under Age: " + drivingUnderAge);
    }
}

Here is an example of running the program:

Were you driving under age?
If Yes, enter True. Otherwise enter False: true

Was Driving Under Age: True

Creating a Boolean Field

 

Like the other types of variables we used in previous lessons, a Boolean variable can be made a field of a class. You declare it like any other variable, using the boolean data type. Here is an example:

public class House {
    String houseType;
    int bedrooms;
    float bathrooms;
    byte stories;
    boolean hasCarGarage;
    int yearBuilt;
    double value;
}

When initializing an object that has a Boolean variable as a member, simply assign true or false to the variable. In the same way, you can retrieve or check the value that a Boolean member variable is holding by simply accessing it. Here are examples:

public class Exercise {
    static void main(String[] args) {
        House home = new House();
        
        home.houseType = "Condominium";
        home.bedrooms = 2;
        home.bathrooms = 1.5F;
        home.stories = 1;
        home.hasCarGarage = false;
        home.yearBuilt = 2002;
        home.value = 355825;

        System.out.println("=//= Altair Realty =//=");
        System.out.println("=== Property Listing ===");
        System.out.println("Type of Home:        " + home.houseType);
        System.out.println("Number of Bedrooms:  " + home.bedrooms);
        System.out.println("Number of Bathrooms: " + home.bathrooms);
        System.out.println("Number of Stories:   " + home.stories);
        System.out.println("Year Built:          " + home.yearBuilt);
        System.out.println("Has Car Garage:      " + home.hasCarGarage);
        System.out.println("Monetary Value:      " + home.value);
    }
}

This would produce:

=//= Altair Realty =//=
=== Property Listing ===
Type of Home:        C
Number of Bedrooms:  2
Number of Bathrooms: 1.5
Number of Stories:   18
Year Built:          2002
Has Car Garage:      False
Monetary Value:      155825

HomePractical Learning: Creating a Boolean Field

  1. Access the StoreItem.java file and change it as follows:
     
    package departmentstore2;
    
    public class StoreItem {
        long itemNumber;
        String itemName;
        boolean isClothingItem;
        double unitPrice;
    
        void CreateItem()
        {
            this.itemNumber = 792475;
            this.itemName = "Lightweight Jacket";
            this.isClothingItem = true;
            this.unitPrice = 185.00D;
        }
    
        void ShowItem()
        {
            System.out.println("Department Store");
    
            System.out.println("Stock #:    " + this.itemNumber);
            System.out.println("Name:       " + this.itemName);
            System.out.println("Unit Price: " + this.unitPrice);
        }
    }
  2. Save the file

Boolean Arguments

 

Like parameters of the other types, you can pass an argument of type boolean to a method. Such an argument would be treated as holding a true or false value.

Enumerations

 

Introduction

Consider that, when creating a program for a real estate company that sells houses, you want the program to ask a customer the type of house that he or she wants to purchase and/or the type of garage that the desired house should have. Here is an example:

import java.util.Scanner;

public class Exercise {
    static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int TypeOfHouse = 0;
        int TypeOfGarage = 0;

        System.out.println("Enter the type of house you want to purchase");
        System.out.println("1 - Single Family");
        System.out.println("2 - Townhouse");
        System.out.println("3 - Condominium");
        System.out.print("Your Choice: ");
        TypeOfHouse = input.nextInt();

        System.out.println("Enter the type of garage you want");
        System.out.println("0 - Doesn't matter");
        System.out.println("1 - Interior");
        System.out.println("2 - Exterior");
        System.out.print("Your Choice: ");
        TypeOfGarage = input.nextInt();

        System.out.println("\nHouse Type: " + TypeOfHouse);
        System.out.println("Garage Type: " + TypeOfGarage);
    }
}

Here is an example of running the program:

Enter the type of house you want to purchase
1 - Single Family
2 - Townhouse
3 - Condominium
Your Choice: 3
Enter the type of garage you want
0 - Doesn't matter
1 - Interior
2 - Exterior
Your Choice: 1

House Type: 3
Garage Type: 1

For such a program, the numbers can be vague. 1 can be considered a general number but, in our program, it can represent a Single Family house or an Interior type of garage. At the same time, our program uses the constant 1 in particular meaningful ways. To make it possible to give more meaning to a constant number, when the number can be made part of a series, Java allows you to create a type of list.

An enumeration is a series of constant integers that each has a specific position in the list and can be recognized by a meaningful name. Based on this, instead of just remembering that the constant 1 represents Single Family, you can create a list that has that type of house. In another list, instead of using 1 again, you can give it a name. Consequently, in each list, although the constant 1 would still be considered, at least it would mean something precise.

Creating an Enumeration

To create an enumeration, you use the enum keyword, followed by the name of the enumeration, followed by a name for each item of the list. The name of the enumerator and the name of each item of the list follows the rules we reviewed for names. The formula of creating an enumeration is:

enum Series_Name {Item1, Item2, Item_n};

Here is an example:

enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }

Based on suggestions of the Java language, it is a tradition to write the members of an enumeration in uppercase:

enum HouseType { UNKNOWN, SINGLEFAMILY, TOWNHOUSE, CONDOMIMIUM }

HomePractical Learning: Creating an Enumeration

  1. Access the StoreItem.java file and change it ss as follows:
     
    package departmentstore2;
    
    enum ItemCategory {
        WOMEN,
        MEN,
        GIRLS,
        BOYS,
        BABIES
    }
    
    public class StoreItem {
        . . . No Change
    }
  2. Save the file

Declaring an Enumeration Variable

After creating an enumeration, each member of the enumeration holds a value of a natural number, such as 0, 4, 12, 25, etc. In Java, an enumeration cannot hold character values (of type char). After creating an enumeration, you can declare a variable from it. Here is an example:

enum HouseType { UNKNOWN, SINGLEFAMILY, TOWNHOUSE, CONDOMIMIUM }

public class Exercise {

    static void main(String[] args) {
	HouseType propType;
    }
}

Initializing an Enumeration Variable

After declaring a variable for an enumeration, to initialize it, specify which member of the enumeration would be assigned to the variable. You should only assign a known member of the enumeration. To do this, on the right side of the assignment operator, type the name of the enumeration, followed by the period operator, and followed by the member whose value you want to assign. Here is an example:

enum HouseType { UNKNOWN, SINGLEFAMILY, TOWNHOUSE, CONDOMIMIUM }

public class Exercise {

    static void main(String[] args) {
	HouseType propType = HouseType.SINGLEFAMILY;
    }
}

You can also find out what value the declared variable is currently holding. For example, you can display it using System.out.print() or System.out.println(). Here is an example:

enum HouseType { UNKNOWN, SINGLEFAMILY, TOWNHOUSE, CONDOMIMIUM }

public class Exercise {

    static void main(String[] args) {
	HouseType propType = HouseType.SINGLEFAMILY;

	System.out.println("House Type: " + propType);
    }
}

This would produce:

House Type:  SINGLEFAMILY

An enumeration is in fact a list of numbers where each member of the list is identified with a name.

Enumerations Visibility

By default, if you create an enumeration the way we have proceeded so far, it would be available only in the project it belongs to. As done for a class, you can make an enumeration public by creating it in its own file and preceding it with the public keyword. Here is an example:

File: HouseType.java
public enum HouseType {
    UNKNOWN,
    SINGLEFAMILY,
    TOWNHOUSE,
    CONDOMINIUM
}
File: Exercise.java
public class Exercise {

    static void main(String[] args) {
	HouseType propType = HouseType.TOWNHOUSE;

	System.out.println("House Type: " + propType);
    }
}

An Enumeration as a Field

After creating an enumeration, you can use it as a data type to declare a variable. To create a field that is of an enumeration type, follow the same rules as done for the primitive types: the name of the enumeration, followed by the name of the variable, and followed by a semi-colon. Here is an example:

enum HouseType {
    UNKNOWN,
    SINGLEFAMILY,
    TOWNHOUSE,
    CONDOMINIUM
}

public class House {
    HouseType PropertyType;
}

In the same way, you can create as many enumeration fields as you want. After creating the field, to initialize it, assign it the desired member of the enumeration. Here is an example:

enum HouseType {
    UNKNOWN,
    SINGLEFAMILY,
    TOWNHOUSE,
    CONDOMINIUM
}

public class House {
    HouseType PropertyType;

    House()     {
        PropertyType = HouseType.UNKNOWN;
    }
}

Once the field has been initialized, you can use it as you see fit as we will learn and practice in future sections and lessons. At a minimum, you can use System.out.print() or System.out.println() to display its value. Here is an example:

enum HouseType {
    UNKNOWN,
    SINGLEFAMILY,
    TOWNHOUSE,
    CONDOMINIUM
}

class House {
    HouseType PropertyType;

    House() {
        PropertyType = HouseType.UNKNOWN;
    }

    void Display() {
        System.out.println("Property Type: " + PropertyType);
    }
}

public class Exercise {

    static void main(String[] args) {
	House prop = new House();
 
        prop.Display();
        System.out.println();

        prop.PropertyType = HouseType.SINGLEFAMILY;
        prop.Display();
        System.out.println();
    }
}

This would produce:

Property Type: UNKNOWN

Property Type: SINGLEFAMILY

Using it as normal data type, you can create a method that returns an enumeration. You can also pass an enumeration to a method as argument.

HomePractical Learning: Creating an Enumeration Field

  1. Change the StoreItem class as follows:
     
    package departmentstore2;
    
    enum ItemCategory {
        WOMEN,
        MEN,
        GIRLS,
        BOYS,
        BABIES
    }
    
    public class StoreItem {
        long itemNumber;
        ItemCategory category;
        String itemName;
        boolean isClothingItem;
        double unitPrice;
    
        void CreateItem()
        {
            this.itemNumber = 792475;
            this.category = ItemCategory.MEN;
            this.itemName = "Lightweight Jacket";
            this.isClothingItem = true;
            this.unitPrice = 185.00D;
        }
    
        void ShowItem()
        {
            System.out.println("Department Store");
            System.out.println("Stock #:    " + this.itemNumber);
            System.out.println("Category:   " + this.category);
            System.out.println("Name:       " + this.itemName);
            System.out.println("Unit Price: " + this.unitPrice);
        }
    }
  2. Execute the application to see the result. This would produce:
     
    Department Store
    Stock #:    792475
    Category:   MEN
    Name:       Lightweight Jacket
    Unit Price: 185.0

 

 

Introduction to Conditions

 

Logical Operators

 

Introduction

A program is a series of instructions that ask the computer (actually the compiler) to check some situations and to act accordingly. To check such situations, the computer spends a great deal of its time performing comparisons between values. A comparison is a Boolean operation that produces a true or a false result, depending on the values on which the comparison is performed.

A comparison is performed between two values of the same type; for example, you can compare two numbers, two characters, or the names of two cities. On the other hand, a comparison between two disparate values doesn't bear any meaning. For example, it is difficult to compare a telephone number and somebody's age, or a music category and the distance between two points. Like the binary arithmetic operations, the comparison operations are performed on two values. Unlike arithmetic operations where results are varied, a comparison produces only one of two results. The result can be a logical true or a logical false. When a comparison is true, it has an integral value of 1 or positive; that is, a value greater than 0. If the comparison is not true, it is considered false and carries an integral value of 0.

The Java language is equipped with various operators used to perform any type of comparison between similar values. The values could be numeric, strings, or objects (operations on objects are customized in a process referred to as Operator Overloading).

There are primary assumptions you should make when writing statements used in conditions:

  • Simplicity and Clarity: A statement should be clear enough and possibly simple but as complete as possible. When a statement becomes long, it can lead to being segmented in short parts, which deceives its clarity and may create other issues.
  • Factual: The statement must be presented as fact and not as opinion. This means that you don't have to like the statement but the majority, including you, must agree that it is true or it is false. In fact, the statement doesn't have to be correct but it must be agreed upon to be true. Based on this, a statement such as "An hour contains 45 minutes" doesn't have to fit your way of thinking but it must be considered as true or as false. A statement such as "This job applicant is attractive" is an opinion and therefore must not be considered in a conditional statement.
  • Circumstantial Truthfulness: At the time the statement is made, it must be considered as true or as false even if it can change at another time. For example, suppose that, in a certain year, a statement is formulated as "This year, the month of February has 28 days". Although allowed, you should refrain from regularly using circumstantial truthfulness, unless you have to.
  • Inverse: A statement must be able to find its reverse. This means that, when a statement is made and decided upon to be true or false, an inverse statement must be found to make it false or true. For example, if you have a statement such as "This job applicant is 18 years old", you must be able to state that "This job applicant is not 18 years old" or "This job applicant is younger than 18".

In your programs, make sure you clearly formulate your statements. This would make your programs easy to read and troubleshoot when problems occur (not if, but when).

The Equality Operator ==

To compare two variables for equality, Java uses the == operator. The formula used is:

Value1 == Value2

The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. From our syntax, the compiler would compare the value of Value1 with that of Value2. If Value1 and Value2 hold the same value, the comparison produces a true result. If they are different, the comparison renders false.

Equal

Most of the comparisons performed in Java will be applied to conditional statements. The result of a comparison can also be assigned to a variable. To store the result of a comparison, you should include the comparison operation between parentheses. Here is an example:

public class Exercise {
    static void main(String[] args) {
        int Value1 = 15;
	int Value2 = 24;

	System.out.println("Value 1 = " + Value1);
	System.out.println("Value 2 = " + Value2);
	System.out.print("Comparison of Value1 == 15 produces ");
	System.out.println(Value1 == 15);
    }
}

This would produce:

Value 1 = 15
Value 2 = 24
Comparison of Value1 == 15 produces true

It is important to make a distinction between the assignment "=" and the logical equality operator "==". The first is used to give a new value to a variable, as in Number = 244. The operand on the left side of = must always be a variable and never a constant. The == operator is never used to assign a value; this would cause an error. The == operator is used only to compare to values. The operands on both sides of == can be variables, constants, or one can be a variable while the other is a constant. If you use one operator in place of the other, you would receive an error when you compile the program.

The Logical Not Operator !

When a variable is declared and receives a value (this could be done through initialization or a change of value) in a program, it becomes alive. It can then participate in any necessary operation. The compiler keeps track of every variable that exists in the program being processed. When a variable is not being used or is not available for processing (in visual programming, it would be considered as disabled) to make a variable (temporarily) unusable, you can nullify its value. Java considers that a variable whose value is null is stern. To render a variable unavailable during the evolution of a program, apply the logical not operator which is !. Its syntax is:

!Value

There are two main ways you can use the logical not operator. As we will learn when studying conditional statements, the most classic way of using the logical not operator is to check the state of a variable.

To nullify a variable, you can write the exclamation point to its left. Here is an example:

public class Exercise {
    static void main(String[] args) {
        boolean HasAirCondition = true;
	boolean DoesIt;

	System.out.println("HasAirCondition = " + HasAirCondition);
	DoesIt = !HasAirCondition;
	System.out.println("DoesIt ? = " + DoesIt);
    }
}

This would produce:

HasAirCondition = true
DoesIt ? = false

When a variable holds a value, it is "alive". To make it not available, you can "not" it. When a variable has been "notted", its logical value has changed. If the logical value was true, which is 1, it would be changed to false, which is 0. Therefore, you can inverse the logical value of a variable by "notting" or not "notting" it.

The Inequality Operator !=

As opposed to Equality, Java provides another operator used to compare two values for inequality. This operation uses a combination of equality and logical not operators. It combines the logical not ! and a simplified == to produce !=. Its syntax is:

Value1 != Value2

The != is a binary operator (like all logical operator except the logical not, which is a unary operator) that is used to compare two values. The values can come from two variables as in Variable1 != Variable2. Upon comparing the values, if both variables hold different values, the comparison produces a true or positive value. Otherwise, the comparison renders false or a null value:

Not Equal

Here is an example:

public class Exercise {
    static void main(String[] args) {
        int Value1 = 212;
	int Value2 = -46;
	boolean Value3 = (Value1 != Value2);

	System.out.println("Value1 = " + Value1);
	System.out.println("Value2 = " + Value2);
	System.out.println("Value3 = " + Value3);
    }
}

This would produce:

Value1 = 212
Value2 = -46
Value3 = true

The inequality is obviously the opposite of the equality.

The Comparison for a Lower Value <

To find out whether one value is lower than another, use the < operator. Its syntax is:

Value1 < Value2

The value held by Value1 is compared to that of Value2. As it would be done with other operations, the comparison can be made between two variables, as in Variable1 < Variable2. If the value held by Variable1 is lower than that of Variable2, the comparison produces a true or positive result.

Flowchart: Less Than

Here is an example:

public class Exercise {
    static void main(String[] args) {
        int Value1 = 15;
	boolean Value2 = (Value1 < 24);

	System.out.println("Value 1 = " + Value1);	
	System.out.println("Value 2 = " + Value2);
    }
}

This would produce:

Value 1 = 15
Value 2 = true

Combining Equality and Lower Value <=

The previous two operations can be combined to compare two values. This allows you to know if two values are the same or if the first is less than the second. The operator used is <= and its syntax is:

Value1 <= Value2

The <= operation performs a comparison as any of the last two. If both Value1 and VBalue2 hold the same value, result is true or positive. If the left operand, in this case Value1, holds a value lower than the second operand, in this case Value2, the result is still true.

Less Than Or Equal

Here is an example:

public class Exercise {
    static void main(String[] args) {
        int Value1 = 15;
	boolean Value2 = (Value1 <= 24);

	System.out.println("Value 1 = " + Value1);	
	System.out.println("Value 2 = " + Value2);
    }
}

This would produce:

Value 1 = 15
Value 2 = True

The Comparison for a Greater Value >

When two values of the same type are distinct, one of them is usually higher than the other. Java provides a logical operator that allows you to find out if one of two values is greater than the other. The operator used for this operation uses the > symbol. Its syntax is:

Value1 > Value2

Both operands, in this case Value1 and Value2, can be variables or the left operand can be a variable while the right operand is a constant. If the value on the left of the > operator is greater than the value on the right side or a constant, the comparison produces a true or positive value . Otherwise, the comparison renders false or null:

Greater Than

 

The Greater Than or Equal Operator >=

The greater than or the equality operators can be combined to produce an operator as follows: >=. This is the "greater than or equal to" operator. Its syntax is:

Value1 >= Value2

A comparison is performed on both operands: Value1 and Value2. If the value of Value1 and that of Value2 are the same, the comparison produces a true or positive value. If the value of the left operand is greater than that of the right operand,, the comparison produces true or positive also. If the value of the left operand is strictly less than the value of the right operand, the comparison produces a false or null result:

Flowchart: Greater Than Or Equal To

Here is a summary table of the logical operators we have studied:

 
Operator Meaning Example Opposite
== Equality to a == b !=
!= Not equal to 12 != 7 ==
< Less than 25 < 84 >=
<= Less than or equal to Cab <= Tab >
> Greater than 248 > 55 <=
>= Greater than or equal to Val1 >= Val2 <

 

 
 
 

Previous Copyright © 2008-2016, FunctionX, Inc. Next