Home

Operators and Operands

 

Fundamental Java Operators

 

Introduction

An operation is an action performed on one or more values either to modify the value held by one or both of the values, or to produce a new value by combining existing values. Therefore, an operation is performed using at least one symbol and at least one value. The symbol used in an operation is called an operator. A value involved in an operation is called an operand.

A unary operator is an operator that performs its operation on only one operand. An operator is referred to as binary if it operates on two operands.

Semi-Colon;

The semi-colon is used to indicate the end of an expression, a declaration, or a statement. As we will learn in other sections, there are other uses of the semi-colon.

Curly Brackets { }

Curly brackets are used to create a section of code. As such they are required to delimit the bodies of classes and other statement, such as conditional statements. Curly brackets are also used to create variable scope. We will see various examples.

Parentheses ( )

Like most computer languages, Java uses parentheses to isolate a group of items that must be considered as belonging to one entity. For example, parentheses are used to differentiate a method such as main from a regular variable. Here is an example:

main()

Parentheses can also be used to isolate an operation or an expression with regard to another operation or expression.

Square Brackets [ ]

Square brackets are mostly used to control the dimension or index of an array. We will learn how to use them when we study arrays. Here is an example:

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

The Comma ,

The comma is used to separate variables used in a group. For example, a comma can be used to delimit the names of variables that are declared with the same data type. Here is an example:

public class Exercise {
    public static void main(String[] args)
    {
        String firstName, lastName, fullName;
    }
}

The comma can also be used to separate the members the arguments of a method, as we will review them.

Practical LearningPractical Learning: Introduction Operators

  1. Start the NetBeans IDE
  2. On the main menu, click File -> New Project...
  3. In the first page of the wizard, click General. In the Projects list, make sure that Java Application is selected and click Next
  4. In the Project Location, accept the suggested path or type a new one, such as C:\Programs\JavaLessons.
    In the Project Name text box, type Operations1
  5. Click Finish
  6. From what we have learned so far, change the file as follows:
     
    package operations1;
    
    public class Main {
    
        public static void main(String[] args) {
            String customerName, homePhone;
    	int numberOfShirts, numberOfPants, numberOfDresses;
    	double priceOneShirt, priceAPairOfPants, priceOneDress;
    	int orderMonth, orderDay, OrderYear;
    	double mondayDiscount;
        }
    }
  7. Save the file

The Assignment =

When you declare a variable, a memory space is reserved for it. That memory space is filled with garbage. To "put" a value in the memory space allocated to a variable, you can use the assignment operator represented as =. Based on this, the assignment operation gives a value to a variable. Its formula is:

VariableName = Value

The VariableName factor must be a valid variable name. It cannot be a value such as a number or a (double-quoted) string. Here is an example that assigns a numeric value to a variable:

public class Exercise {
    public static void main(String[] args) {
        double salary;

	// Using the assignment operator
	salary = 12.55;
    }
}

Once a variable has been declared and assigned a value, you can call print() or println() to display its value.  Here is an example:

public class Exercise {
    public static void main(String[] args) {
        double salary;

	// Using the assignment operator
	salary = 12.55;
        System.out.print(salary);
    }
}

This would produce:

12.55

The above code declares a variable before assigning it a value. You will usually perform this assignment when you want to change the value held by a variable. Providing a starting value to a variable when the variable is declared is referred to as initializing the variable. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        // Initializing a variable
        double salary = 12.55;

        System.out.print(salary);
    }
}

We saw that you could declare various variables at once by using the same data type but separating their names with commas. When doing this, you can also initialize each variable by assigning it the desired value before the comma or the semi-colon. Here is an example:

public class Exercise {
    public static void main(String[] args) {
       	// Initializing various variables when declaring them with the same data type
	double value1 = 224.58, value2 = 1548.26;
			
	System.out.println(value1);
	System.out.println(value2);
    }
}

This would produce:

224.58
1548.26

Practical LearningPractical Learning: Assigning Values to Variables

  1. To use the assignment operator, change the file as follows:
     
    package operations1;
    
    public class Main {
    
        public static void main(String[] args) {
            String customerName, homePhone;
    	int numberOfShirts = 5, numberOfPants = 2, numberOfDresses = 8;
    	double priceOneShirt = 0.95D, priceAPairOfPants = 2.95D,
                   priceOneDress = 3.25D;
    	int orderMonth = 3, orderDay = 15, orderYear = 2002;
    	double mondayDiscount = 0.25; // 25%
        }
    }
  2. Save the file

Single-Quote '

The single quote is used to include one character to initialize, or assign a symbol to, a variable declared as char. A single qoute is usually combined with another single-quote and a character can be included between them. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        char gender;

        gender = 'M';
        System.out.print(gender);
    }
}

You can include only one character between single-quotes except if the combination of symbols can be evaluated to one character. This is the case for escape sequences. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        char gender;

        gender = 'M';
        System.out.print(gender);
        System.out.print('\n');
    }
}

Double Quotes "

The double quote " is used to delimit a string. As mentioned for the single-quote, the double-quote is usually combined with another double quote. Between the combination of double-quotes, you can include an empty space, a character, a word, or a group of words, making it a string. Here is an example:

public class Exercise {
    public static void main(String[] args) {
       	String message;

	message = "Welcome to the wonderful world of Java";
       	System.out.print(message);
    }
}

A double-quoted string can also be declared and then assigned to a variable.

Practical LearningPractical Learning: Using Quotes

  1. To use single and double-quotes, change the file as follows:
     
    package operations1;
    
    public class Main {
    
        public static void main(String[] args) {
            String customerName = "James Burreck",
                   homePhone = "(202) 301-7030";
    	int numberOfShirts = 5, numberOfPants = 2, numberOfDresses = 8;
    	double priceOneShirt = 0.95D, priceAPairOfPants = 2.95D,
                   priceOneDress = 3.25D;
    	int orderMonth = 3, orderDay = 15, orderYear = 2002;
    	double mondayDiscount = 0.25; // 25%
            
            	System.out.println("-/- Georgetown Cleaning Services -/-");
    	System.out.println("========================");
    	System.out.print("Customer:   ");
    	System.out.println(customerName);
    	System.out.print("Home Phone: ");
    	System.out.println(homePhone);
    	System.out.print("Order Date: ");
    	System.out.print(orderMonth);
    	System.out.print('/');
    	System.out.print(orderDay);
    	System.out.print('/');
    	System.out.println(orderYear);
    	System.out.println("------------------------");
    	System.out.println("Item Type  Qty Sub-Total");
    	System.out.println("------------------------");
    	System.out.print("Shirts      ");
    	System.out.print(numberOfShirts);
    	System.out.print("     ");
    	System.out.println(priceOneShirt);
    	System.out.print("Pants       ");
    	System.out.print(numberOfPants);
    	System.out.print("     ");
    	System.out.println(priceAPairOfPants);
    	System.out.print("Dresses     ");
    	System.out.print(numberOfDresses);
    	System.out.print("     ");
    	System.out.println(priceOneDress);
    	System.out.println("------------------------");
    	System.out.print("Monday Discount: ");
    	System.out.print(mondayDiscount);
    	System.out.println('%');
    	System.out.println("========================");
    	System.out.println();
        }
    }
  2. Execute the application. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    ========================
    Customer:   James Burreck
    Home Phone: (202) 301-7030
    Order Date: 3/15/2002
    ------------------------
    Item Type  Qty Sub-Total
    ------------------------
    Shirts      5     0.95
    Pants       2     2.95
    Dresses     8     3.25
    ------------------------
    Monday Discount: 0.25%
    ========================

The Positive Operator +

Algebra uses a type of ruler to classify numbers. This ruler has a middle position of zero. The numbers on the left side of the 0 are referred to as negative while the numbers on the right side of the rulers are considered positive:

-∞   -6 -5 -4 -3 -2 -1   1 2 3 4 5 6   +∞
   0
-∞   -6 -5 -4 -3 -2 -1   1 2 3 4 5 6   +∞

A value on the right side of 0 is considered positive. To express that a number is positive, you can write a + sign on its left. Examples are +4, +228, +90335. In this case the + symbol is called a unary operator because it acts on only one operand. The positive unary operator, when used, must be positioned on the left side of its operand, never on the right side.

As a mathematical convention, when a value is positive, you don't need to express it with the + operator. Just writing the number without any symbol signifies that the number is positive. Therefore, the numbers +4, +228, and +90335 can be, and are better, expressed as 4, 228, 90335. Because the value doesn't display a sign, it is referred as unsigned.

To express a variable as positive or unsigned, you can just type it. here is an example:

public class Exercise {
    public static void main(String[] args) {
       	System.out.print("Number = ");
	System.out.println(+802);
    }
}

This would produce:

Number = 802

The Negative Operator -

As you can see on the above ruler, in order to express any number on the left side of 0, it must be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A value accompanied by - is referred to as negative. The - sign must be typed on the left side of the number it is used to negate. Remember that if a number does not have a sign, it is considered positive. Therefore, whenever a number is negative, it MUST have a - sign. In the same way, if you want to change a value from positive to negative, you can just add a - sign to its left.

Here is an example that uses two variables. One has a positive value while the other has a negative value:

public class Exercise {
    public static void main(String[] args) {
       	System.out.print("First Number  = ");
	System.out.println(+802);
	// Displaying a negative number
	System.out.print("Second Number = ");
	System.out.println(-802);
    }
}

This would produce:

First Number      = 802
Second Number = -802
 

Operators/Operands in

C#
C++
Visual Basic

 

 

 

 

 

 

 

 

The Addition Operations

 

Introduction

The addition is an operation used to add things of the same nature one to another, as many as necessary. Sometimes, the items are added one group to another. The concept is still the same, except that this last example is faster. The addition is performed in mathematics using the + sign. The same sign is used in Java.

To get the addition of two values, you add the first one to the other. After the addition of two values has been performed, you get a new value. This means that if you add Value1 to Value2, you would write Value1 + Value2. The result is another value we could call Value3. You can also add more than two values, like a + b + c.

With numbers, the order you use to add two or more values doesn't matter. This means that Value1 + Value2 is the same as Value2 + Value1. In the same way a + b + c is the same as a + c + b the same as b + a + c and the same as c + b + a

Here is an example that adds two numbers:

public class Exercise {
    public static void main(String[] args) {
        	System.out.print("244 + 835 = ");
	System.out.print(244 + 835);
    }
}

Here is the result:

244 + 835 = 1079

You can also add some values already declared and initialized in your program. You can also get the values from the user.

In Java, you can also add string variables to add a new string. The operation is performed as if you were using numbers. For example, "Pie" + "Chart" would produce "PieChart". You can also add add as many strings as possible by including the + operator between them. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        String firstName = "Alexander";
	String lastName  = "Kallack";
	String fullName  = firstName + " " + lastName;
	System.out.print("Full Name: " + fullName);
    }
}

This would produce:

Full Name: Alexander Kallack

Practical LearningPractical Learning: Using the Addition Operator

  1. Reopen the Exercise.cs file from the GCS2 folder
  2. To use the addition, change the file as follows:
     
    package operations1;
    
    public class Main {
    
        public static void main(String[] args) {
            String customerName = "James Burreck",
                   homePhone = "(202) 301-7030";
    	int numberOfShirts = 5, numberOfPants = 2, numberOfDresses = 8;
    	double priceOneShirt = 0.95D, priceAPairOfPants = 2.95D,
                   priceOneDress = 3.25D;
            int totalNumberOfItems;
    	int orderMonth = 3, orderDay = 15, orderYear = 2002;
    	double mondayDiscount = 0.25; // 25%
            
            totalNumberOfItems = numberOfShirts + numberOfPants + numberOfDresses;
            
            System.out.println("-/- Georgetown Cleaning Services -/-");
    	System.out.println("========================");
    	System.out.print("Customer:   ");
    	System.out.println(customerName);
    	System.out.print("Home Phone: ");
    	System.out.println(homePhone);
    	System.out.print("Order Date: ");
    	System.out.print(orderMonth);
    	System.out.print('/');
    	System.out.print(orderDay);
    	System.out.print('/');
    	System.out.println(orderYear);
    	System.out.println("------------------------");
    	System.out.println("Item Type  Qty Sub-Total");
    	System.out.println("------------------------");
    	System.out.print("Shirts      ");
    	System.out.print(numberOfShirts);
    	System.out.print("     ");
    	System.out.println(priceOneShirt);
    	System.out.print("Pants       ");
    	System.out.print(numberOfPants);
    	System.out.print("     ");
    	System.out.println(priceAPairOfPants);
    	System.out.print("Dresses     ");
    	System.out.print(numberOfDresses);
    	System.out.print("     ");
    	System.out.println(priceOneDress);
    	System.out.println("------------------------");
    	System.out.print("Monday Discount: ");
    	System.out.print(mondayDiscount);
    	System.out.println('%');
    	System.out.print("Number of Items: ");
    	System.out.println(totalNumberOfItems);
    	System.out.println("========================");
    	System.out.println();
        }
    }
  3. Execute the application. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    ========================
    Customer:   James Burreck
    Home Phone: (202) 301-7030
    Order Date: 3/15/2002
    ------------------------
    Item Type  Qty Sub-Total
    ------------------------
    Shirts      5     0.95
    Pants       2     2.95
    Dresses     8     3.25
    ------------------------
    Monday Discount: 0.25%
    Number of Items: 15
    ========================

Incrementing a Variable

We are used to counting numbers such as 1, 2, 3, 4, etc. In reality, when counting such numbers, we are simply adding 1 to a number in order to get the next number in the range. The simplest technique of incrementing a value consists of adding 1 to it. After adding 1, the value or the variable is (permanently) modified and the variable would hold the new value. This is illustrated in the following example:

// This program studies value incrementing
public class Exercise {
    public static void main(String[] args) {
	int Value = 12;

	System.out.println("Techniques of incrementing a value");
	System.out.print("Value = ");
	System.out.println(Value);

	Value = Value + 1;

	System.out.print("Value = ");
	System.out.println(Value);
    }
}

This would produce:

Techniques of incrementing a value
Value = 12
Value = 13

C# provides a special operator that takes care of this operation. The operator is called the increment operator and is represented by ++. Instead of writing Value = Value + 1, you can write Value++ and you would get the same result. The above program can be re-written as follows:

// This program studies value incrementing
public class Exercise {
    public static void main(String[] args) {
	int Value = 12;

	System.out.println("Techniques of incrementing a value");
	System.out.print("Value = ");
	System.out.println(Value);

	Value++;

	System.out.print("Value = ");
	System.out.println(Value);
    }
}

The ++ is a unary operator because it operates on only one variable. It is used to modify the value of the variable by adding 1 to it. Every time the Value++ is executed, the compiler takes the previous value of the variable, adds 1 to it, and the variable holds the incremented value:

// This program studies value incrementing
public class Exercise {
    public static void main(String[] args) {
	int Value = 12;

	System.out.println("Techniques of incrementing a value");

	Value++;
	System.out.print("Value = ");
	System.out.println(Value);

	Value++;
	System.out.print("Value = ");
	System.out.println(Value);
		
	Value++;
	System.out.print("Value = ");
	System.out.println(Value);
    }
}

This would produce:

Techniques of incrementing a value
Value = 13
Value = 14
Value = 15

Pre and Post-Increment

When using the ++ operator, the position of the operator with regard to the variable it is modifying can be significant. To increment the value of the variable before re-using it, you should position the operator on the left of the variable:

// This program studies value incrementing
public class Exercise {
    public static void main(String[] args) {
	int Value = 12;

	System.out.println("Techniques of incrementing a value");

	System.out.print("Value = ");
	System.out.println(Value);

	System.out.print("Value = ");
	System.out.println(++Value);
		
	System.out.print("Value = ");
	System.out.println(Value);
    }
}

This would produce:

Techniques of incrementing a value
Value = 12
Value = 13
Value = 13

When writing ++Value, the value of the variable is incremented before being called. On the other hand, if you want to first use a variable, then increment it, in other words, if you want to increment the variable after calling it, position the increment operator on the right side of the variable:

// This program studies value incrementing
public class Exercise {
    public static void main(String[] args) {
	int Value = 12;

	System.out.println("Techniques of incrementing a value");

	System.out.print("Value = ");
	System.out.println(Value);

	System.out.print("Value = ");
	System.out.println(Value++);
		
	System.out.print("Value = ");
	System.out.println(Value);
    }
}

This would produce:

Techniques of incrementing a value
Value = 12
Value = 12
Value = 13

Compound Addition

It is not unusual to add a constant value to a variable. All you have to do is to declare another variable that would hold the new value. Here is an example:

// This program studies value incrementing and decrementing
public class Exercise {
    public static void main(String[] args) {
	double Value = 12.75;
	double NewValue;

	System.out.println("Techniques of incrementing and decrementing a value");
	System.out.print("Value = ");
	System.out.println(Value);

	NewValue = Value + 2.42;
		
	System.out.print("Value = ");
	System.out.println(NewValue);
    }
}

This would produce:

Techniques of incrementing and decrementing a value
Value = 12.75
Value = 15.17

The above technique requires that you use an extra variable in your application. The advantage is that each value can hold its own value although the value of the second variable depends on whatever would happen to the original or source variable. Sometimes in your program you will not need to keep the original value of the source variable. You may want to permanently modify the value that a variable is holding. In this case, you can perform the addition operation directly on the variable by adding the desired value to the variable. This operation modifies whatever value a variable is holding and does not need an additional variable.

To add a value to a variable and change the value that the variable is holding, you can combine the assignment “=” and the addition “+” operators to produce a new operator as +=. Here is an example:

// This program studies value incrementing and decrementing
public class Exercise {
    public static void main(String[] args) {
	double Value = 12.75;

	System.out.println("Techniques of incrementing and decrementing a value");
	System.out.print("Value = ");
	System.out.println(Value);

	Value += 2.42;
		
	System.out.print("Value = ");
	System.out.println(Value);
    }
}

This program produces the same result as the previous.

The Multiplication Operations

 

Introduction

The multiplication allows adding one value to itself a certain number of times, set by a second value. As an example, instead of adding a value to itself in this manner: A + A + A + A, since the variable a is repeated over and over again, you could simply find out how many times A is added to itself, then multiply a by that number which, is this case, is 4. This would mean adding a to itself 4 times, and you would get the same result.

Just like the addition, the multiplication is associative: a * b * c = c * b * a. When it comes to programming syntax, the rules we learned with the addition operation also apply to the multiplication.

Here is an example:

public class Exercise {
    public static void main(String[] args) {
        double value1 = 224.58, value2 = 1548.26;
	double result = value1 * value2;
			
	System.out.print(value1 + " * " + value2 + " = " + result);
    }
}

This would produce:

224.58 * 1548.26 = 347708.2308

Practical LearningPractical Learning: Using the Multiplication Operator

  1. To multiply, change the file as follows:
     
    package operations1;
    
    public class Main {
    
        public static void main(String[] args) {
            final double priceOneShirt     = 0.95D;
    	final double priceAPairOfPants = 2.95D;
    	final double priceOneDress     = 3.25D;
            
            	String customerName = "James Burreck",
                   		homePhone = "(202) 301-7030";
    	int numberOfShirts = 5, numberOfPants = 2, numberOfDresses = 8;
            	int totalNumberOfItems;
            
            	double subTotalShirts, SubTotalPants, SubTotalDresses;
    	double totalOrder;
    	
            	int orderMonth = 3, orderDay = 15, orderYear = 2002;
    	double mondayDiscount = 0.25; // 25%
            
            totalNumberOfItems = numberOfShirts + numberOfPants + numberOfDresses;
            subTotalShirts  = priceOneShirt * numberOfShirts;
    	SubTotalPants   = priceAPairOfPants * numberOfPants;
    	SubTotalDresses = numberOfDresses * priceOneDress;
    	totalOrder      = subTotalShirts + SubTotalPants + SubTotalDresses;
                            
            	System.out.println("-/- Georgetown Cleaning Services -/-");
    	System.out.println("====================================");
    	System.out.print("Customer:   ");
    	System.out.println(customerName);
    	System.out.print("Home Phone: ");
    	System.out.println(homePhone);
    	System.out.print("Order Date: ");
    	System.out.print(orderMonth);
    	System.out.print('/');
    	System.out.print(orderDay);
    	System.out.print('/');
    	System.out.println(orderYear);
    	System.out.println("------------------------------------");
    	System.out.println("Item Type  Qty Unit/Price Sub-Total");
    	System.out.println("------------------------------------");
    	System.out.print("Shirts      ");
    	System.out.print(numberOfShirts);
    	System.out.print("     ");
    	System.out.print(priceOneShirt);
    	System.out.print("     ");
    	System.out.println(subTotalShirts);
    	System.out.print("Pants       ");
    	System.out.print(numberOfPants);
    	System.out.print("     ");
    	System.out.print(priceAPairOfPants);
    	System.out.print("     ");
    	System.out.println(SubTotalPants);
    	System.out.print("Dresses     ");
    	System.out.print(numberOfDresses);
    	System.out.print("     ");
    	System.out.print(priceOneDress);
    	System.out.print("     ");
    	System.out.println(SubTotalDresses);
    	System.out.println("------------------------------------");
    	System.out.print("Number of Items: ");
    	System.out.println(totalNumberOfItems);
    	System.out.print("Total Order:     ");
    	System.out.println(totalOrder);
    	System.out.println("====================================");
    	System.out.println();
        }
    }
  2. Execute the program. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   James Burreck
    Home Phone: (202) 301-7030
    Order Date: 3/15/2002
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      5     0.95     4.75
    Pants       2     2.95     5.9
    Dresses     8     3.25     26.0
    ------------------------------------
    Number of Items: 15
    Total Order:     36.65
    ====================================

Compound Multiplication

We saw that you could add or subtract a value to a variable and assign the result to the same variable. You can perform the same operation with the multiplication. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        double Value = 12.75;

        System.out.print("Value = ");
        System.out.println(Value);

        Value = Value * 2.42;

        System.out.print("Value = ");
        System.out.println(Value);
    }
}

This would produce:

Value = 12.75
Value = 30.855

To make this operation easy, the Java language supports the compound multiplication assignment operator represented as *=. To use it, use the *= operator and assign the desired value to the variable. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        double Value = 12.75;

        System.out.print("Value = ");
        System.out.println(Value);

        Value *= 2.42;

        System.out.print("Value = ");
        System.out.println(Value);
    }
}

The Subtraction Operations

 

Introduction

The subtraction operation is used to take out or subtract a value from another value. It is essentially the opposite of the addition. The subtraction is performed with the - sign.

Here is an example:

public class Exercise {
    public static void main(String[] args) {
        // Values used in this program
	double value1 = 224.58, value2 = 1548.26;
	double result = value1 - value2;

	System.out.print(value1);
	System.out.print(" - ");
	System.out.print(value2);
	System.out.print(" = ");
	System.out.print(result);
    }
}

This would produce:

224.58 - 1548.26 = -1323.68

Unlike the addition, the subtraction is not associative. In other words, a - b - c is not the same as c - b - a. Consider the following program that illustrates this:

public class Exercise {
    public static void main(String[] args) {
        // This tests whether the addition is associative
	System.out.println(" =+= Addition =+=");
	System.out.print("128 + 42 +   5 = ");
	System.out.println(128 + 42 + 5);
	System.out.print("  5 + 42 + 128 = ");
	System.out.println(5 + 42 + 128);

	System.out.println();

	// This tests whether the subtraction is associative
	System.out.println(" =-= Subtraction =-=");
	System.out.print("128 - 42 -   5 = ");
	System.out.println(128 - 42 - 5);
	System.out.print("  5 - 42 - 128 = ");
	System.out.println(5 - 42 - 128);
    }
}

This would produce:

=-= Subtraction =-=
128 - 42 -   5 = 81
  5 - 42 - 128 = -165

Notice that both operations of the addition convey the same result. In the subtraction section, the numbers follow the same order but produce different results.

Practical LearningPractical Learning: Using the Subtraction Operator

  1. To Subtract, change the file as follows:
     
    package operations1;
    
    public class Main {
    
        public static void main(String[] args) {
    	final double priceOneShirt     = 0.95D;
    	final double priceAPairOfPants = 2.95D;
    	final double priceOneDress     = 4.55D;
    	final double salestaxRate      = 0.0575D; // 5.75%
    
    	String customerName = "James Burreck",
    	       homePhone = "(202) 301-7030";
    	int numberOfShirts   = 5,
                numberOfPants    = 2,
    	    numberOfDresses  = 3;
    	int totalNumberOfItems;
    	double subTotalShirts, subTotalPants, subTotalDresses;
    	double taxAmount, totalOrder, netPrice;
    	int orderMonth = 3, orderDay = 15, OrderYear = 2002;
    
    	totalNumberOfItems = 
    		numberOfShirts + numberOfPants + numberOfDresses;
    	subTotalShirts  = priceOneShirt * numberOfShirts;
    	subTotalPants   = priceAPairOfPants * numberOfPants;
    	subTotalDresses = numberOfDresses * priceOneDress;
    	totalOrder      = subTotalShirts + subTotalPants + subTotalDresses;
    	taxAmount = totalOrder * salestaxRate;
    	netPrice  = totalOrder - taxAmount;
    
    	System.out.println("-/- Georgetown Cleaning Services -/-");
    	System.out.println("====================================");
    	System.out.println("Customer:   " + customerName);
    	System.out.println("Home Phone: " + homePhone);
    	System.out.print("Order Date: ");
    	System.out.print(orderMonth);
    	System.out.print('/');
    	System.out.print(orderDay);
    	System.out.print('/');
    	System.out.println(OrderYear);
    	System.out.println("------------------------------------");
    	System.out.println("Item Type  Qty Unit/Price Sub-Total");
    	System.out.println("------------------------------------");
    	System.out.print("Shirts      " + numberOfShirts + "     ");
    	System.out.println(priceOneShirt + "     " + subTotalShirts);
    	System.out.print("Pants       " + numberOfPants + "     ");
    	System.out.println(priceAPairOfPants + "     " + subTotalPants);
    	System.out.print("Dresses     " + numberOfDresses + "     ");
    	System.out.println(priceOneDress + "     " + subTotalDresses);
    	System.out.println("------------------------------------");
    	System.out.println("Number of Items: " + totalNumberOfItems);
    	System.out.println("Total Order:     " + totalOrder);
    	System.out.print("Tax Rate:        " + salestaxRate * 100);
    	System.out.println('%');
    	System.out.println("Tax Amount:      " + taxAmount);
    	System.out.println("Net Price:       " + netPrice);
    	System.out.println("====================================");
        }
    }
  2. Execute the application. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   James Burreck
    Home Phone: (202) 301-7030
    Order Date: 3/15/2002
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      5     0.95     4.75
    Pants       2     2.95     5.9
    Dresses     3     4.55     13.649999999999999
    ------------------------------------
    Number of Items: 10
    Total Order:     24.299999999999997
    Tax Rate:        5.75%
    Tax Amount:      1.3972499999999999
    Net Price:       22.902749999999997
    ====================================

Decrementing a Variable

When counting numbers backward, such as 8, 7, 6, 5, etc, we are in fact subtracting 1 from a value in order to get the lesser value. This operation is referred to as decrementing a value. This operation works as if a value is decremented by 1, as in Value = Value – 1:

// This program studies value decrementing
public class Exercise {
    public static void main(String[] args) {
	int Value = 12;

	System.out.println("Techniques of decrementing a value");
	System.out.print("Value = ");
	System.out.println(Value);

	Value = Value - 1;

	System.out.print("Value = ");
	System.out.println(Value);
    }
}

This would produce:

Techniques of decrementing a value
Value = 12
Value = 11

As done to increment, C# provides a quicker way of subtracting 1 from a value. This is done using the decrement operator, that is --. To use the decrement operator, type –- on the left or the right side of the variable when this operation is desired. Using the decrement operator, the above program could be written:

// This program studies value decrementing
public class Exercise {
    public static void main(String[] args) {
	int Value = 12;

	System.out.println("Techniques of decrementing a value");
	System.out.print("Value = ");
	System.out.println(Value);

	Value--;

	System.out.print("Value = ");
	System.out.println(Value);
    }
}

Pre Decrementing a Value

Once again, the position of the operator can be important. If you want to decrement the variable before calling it, position the decrement operator on the left side of the operand. This is illustrated in the following program:

// This program studies value decrementing
public class Exercise {
    public static void main(String[] args) {
	int Value = 12;

	System.out.println("Techniques of decrementing a value");
	System.out.print("Value = ");
	System.out.println(Value);

	System.out.print("Value = ");
	System.out.println(--Value);
		
	System.out.print("Value = ");
	System.out.println(Value);
    }
}

This would produce:

Techniques of decrementing a value
Value = 12
Value = 11
Value = 11

If you plan to decrement a variable only after it has been accessed, position the operator on the right side of the variable. Here is an example:

// This program studies value decrementing
public class Exercise {
    public static void main(String[] args) {
	int Value = 12;

	System.out.println("Techniques of decrementing a value");
	System.out.print("Value = ");
	System.out.println(Value);

	System.out.print("Value = ");
	System.out.println(Value--);
		
	System.out.print("Value = ");
	System.out.println(Value);
    }
}

This would produce:

Techniques of decrementing a value
Value = 12
Value = 12
Value = 11

Compound Subtraction

You may want to subtract a constant value from a variable. To decrement a value from a variable, use the subtraction and apply the same technique. This is done with the -= operator. Here is an example:

// This program studies compound subtraction
public class Exercise {
    public static void main(String[] args) {
	double Value = 12.75;

	System.out.println("Techniques of incrementing and decrementing a value");
	System.out.print("Value = ");
	System.out.println(Value);

	Value -= 2.42;
		
	System.out.print("Value = ");
	System.out.println(Value);
    }
}

This would produce:

Techniques of incrementing and decrementing a value
Value = 12.75
Value = 10.33

The Division Operations

 

Introduction

Dividing an item means cutting it in pieces or fractions of a set value. For example, when you cut an apple in the middle, you are dividing it in 2 pieces. If you cut each one of the resulting pieces, you will get 4 pieces or fractions. This is considered that you have divided the apple in 4 parts. Therefore, the division is used to get the fraction of one number in terms of another. The division is performed with the forward slash /.

Here is an example:

public class Exercise {
    public static void main(String[] args)  {
        double value1 = 224.58, value2 = 1548.26;
	double result = value1 / value2;
			
	System.out.print(value1 + " / " + value2 + " = " + result);
    }
}

This would produce:

224.58 / 1548.26 = 0.145053156446592

When performing the division, be aware of its many rules. Never divide by zero (0). Make sure that you know the relationship(s) between the numbers involved in the operation.

Practical LearningPractical Learning: Using the Division Operator

  1. To use the division, change the file as follows:
     
    package operations1;
    
    public class Main {
    
        public static void main(String[] args) {
    	final double priceOneShirt     = 0.95D;
    	final double priceAPairOfPants = 2.95D;
    	final double priceOneDress     = 4.55D;
    	final double salesTaxRate      = 5.75D; // 5.75%
    
    	String customerName = "James Burreck",
    	          homePhone = "(202) 301-7030";
    	int numberOfShirts   = 5,
                	     numberOfPants    = 2,
    	     numberOfDresses  = 3;
    	int totalNumberOfItems;
    	double subTotalShirts, subTotalPants, subTotalDresses;
    	double taxAmount, totalOrder, netPrice;
    	int orderMonth = 3, orderDay = 15, OrderYear = 2002;
    
    	totalNumberOfItems = numberOfShirts + numberOfPants + numberOfDresses;
    	subTotalShirts     = priceOneShirt * numberOfShirts;
    	subTotalPants      = priceAPairOfPants * numberOfPants;
    	subTotalDresses    = numberOfDresses * priceOneDress;
    	totalOrder         = subTotalShirts + subTotalPants + subTotalDresses;
    	taxAmount          = totalOrder * salesTaxRate / 100;
    	netPrice           = totalOrder - taxAmount;
    
    	System.out.println("-/- Georgetown Cleaning Services -/-");
    	System.out.println("====================================");
    	System.out.println("Customer:   " + customerName);
    	System.out.println("Home Phone: " + homePhone);
    	System.out.print("Order Date: ");
    	System.out.print(orderMonth);
    	System.out.print('/');
    	System.out.print(orderDay);
    	System.out.print('/');
    	System.out.println(OrderYear);
    	System.out.println("------------------------------------");
    	System.out.println("Item Type  Qty Unit/Price Sub-Total");
    	System.out.println("------------------------------------");
    	System.out.print("Shirts      " + numberOfShirts + "     ");
    	System.out.println(priceOneShirt + "     " + subTotalShirts);
    	System.out.print("Pants       " + numberOfPants + "     ");
    	System.out.println(priceAPairOfPants + "     " + subTotalPants);
    	System.out.print("Dresses     " + numberOfDresses + "     ");
    	System.out.println(priceOneDress + "     " + subTotalDresses);
    	System.out.println("------------------------------------");
    	System.out.println("Number of Items: " + totalNumberOfItems);
    	System.out.println("Total Order:     " + totalOrder);
    	System.out.print("Tax Rate:        " + salesTaxRate * 100);
    	System.out.println('%');
    	System.out.println("Tax Amount:      " + taxAmount);
    	System.out.println("Net Price:       " + netPrice);
    	System.out.println("====================================");
        }
    }
  2. Execute the program. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:   James Burreck
    Home Phone: (202) 301-7030
    Order Date: 3/15/2002
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      5     0.95     4.75
    Pants       2     2.95     5.90
    Dresses     3     4.55     13.65
    ------------------------------------
    Number of Items: 10
    Total Order:     24.30
    Discount Rate:   20.00%
    Discount Amount: 4.8600
    After Discount:  19.4400
    Tax Rate:        5.75%
    Tax Amount:      1.39725
    Net Price:       20.83725
    ====================================
    Amount Tended:   50
    Difference:      29.16275
    ====================================
  3. Return to Notepad

Compound Division

Remember that you can add, subtract, or multiply a value to a variable and assign the result to the variable itself. You can also perform this operation using the division. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        double Value = 12.75;

        System.out.print("Value = ");
        System.out.println(Value);

        Value = Value / 2.42;

        System.out.print("Value = ");
        System.out.println(Value);
    }
}

This would produce:

Value = 12.75
Value = 5.26859504132231

To perform this operation faster, the Java language provides the /= operator. Here is an example of using it:

public class Exercise {
    public static void main(String[] args) {
        double Value = 12.75;

        System.out.print("Value = ");
        System.out.println(Value);

        Value /= 2.42;

        System.out.print("Value = ");
        System.out.println(Value);
    }
}

The Remainder

 

Introduction

The division program above will give you a result of a number with double values if you type an odd number (like 147), which is fine in some circumstances. Sometimes you will want to get the value remaining after a division renders a natural result. Imagine you have 26 kids at a football (soccer) stadium and they are about to start. You know that you need 11 kids for each team to start. If the game starts with the right amount of players, how many will seat and wait?

The remainder operation is performed with the percent sign (%) which is gotten from pressing Shift + 5.

Here is an example:

public class Exercise {
    public static void main(String[] args) {
        int Players = 16;

	// When the game starts, how many players will wait?.
	System.out.print("Out of ");
	System.out.print(Players);
	System.out.print(" players, ");
	System.out.print(16 % 11);
	System.out.print(" players will have to wait when the game starts.\n");
    }
}

This would produce:

Out of 16 players, 5 players will have to wait when the game starts.

The Compound Remainder

As seen with the other arithmetic operators, you can find the remainder of a variable and assign the result to the variable itself. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        int Players = 18;

        // When the game starts, how many players will wait?.
        System.out.print("Out of ");
        System.out.print(Players);
        System.out.print(" players, ");

        Players = Players % 11;
            
        System.out.print(Players);
        System.out.println(" players will have to wait when the game starts.\n");
    }
}

To support a faster version of this operation, the Java language provides the compound remainder operator represented as %=. To use it, assign its value to the variable. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        int Players = 18;

        // When the game starts, how many players will wait?.
        System.out.print("Out of ");
        System.out.print(Players);
        System.out.print(" players, ");

        Players %= 11;
            
        System.out.print(Players);
        System.out.println(" players will have to wait when the game starts.\n");
    }
}

Bit Operations

 

Introduction

From our introduction to variables, you may remember that the computer stores its data in memory using small locations that each contains a bit of information. Because a bit can be represented only either as 1 or 0, we can say that each bit contains 1 or 0. Bit manipulation consists of changing the value (1 or 0, or 0 or 1) in a bit. As we will see in the next few operations, it is not just about changing a value. It can involve reversing a value or kind of "moving" a bit from its current position to the next position.

The operations on bits are performed on 1s and 0s only. This means that any number is decimal or hexadecimal format involved in a bit operation must be converted to binary first.

You will almost never perform some of the operations we are going to review. You will hardly perform some other operations. There is only one operation you will perform on a regular basis. The OR operation is very regular in Microsoft Windows (Win32) programming so much that we were obliged to include this whole section in the lesson, as opposed to mentioning only OR.

"Reversing" a Bit

Remember that, at any time, a box (or chunk) in memory contains either 1 or 0:

Bit 0 Bit 1
0 1

Bit reversal consists of reversing the value of a bit. If the box contains 1, you can reverse it to 0. If it contains 0, you can reverse it to 1. To support this operation, the Java language provides the bitwise negation operator represented with the ~ symbol.

As an example, consider the number 286. The decimal number 286 converted to binary is 100011110. You can reverse each bit as follows:

286 1 0 0 0 1 1 1 1 0
Not 286 0 1 1 1 0 0 0 0 1
 

To use the bitwise negation operator, type ~ on the left side of the value. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        int Number1 = 286;

        System.out.print("Not 286 = ");
        System.out.println(~Number1);
    }
}

This would produce:

Not 286 = -287

Bitwise Conjunction

Bitwise conjunction consists of adding the content of a bit to the content of another bit. To support the bitwise conjunction operation, the Java language provides the & operator.

To perform the bit addition on two numbers, remember that they must be converted to binary first. Then:

  • If a bit with value 0 is added to a bit with value 0, the result is 0
     
    Bit0 0
    Bit1 0
    Bit0 And Bit1 0
  • If a bit with value 1 is added to a bit with value 0, the result is 0
     
    Bit0 1
    Bit1 0
    Bit0 And Bit1 0
  • If a bit with value 0 is added to a bit with value 1, the result is 0
     
    Bit0 0
    Bit1 1
    Bit0 And Bit1 0
  • If a bit with value 1 is added to a bit with value 1, the result is 1
     
    Bit0 1
    Bit1 1
    Bit0 And Bit1 1

As an example, consider the number 286 bit-added to 475. The decimal number 286 converted to binary is 100011110. The decimal number 4075 converted to binary is 111111101011. Based on the above 4 points, we can add these two numbers as follows:

286 0 0 0 1 0 0 0 1 1 1 1 0
4075 1 1 1 1 1 1 1 0 1 0 1 1
286 & 4075 0 0 0 1 0 0 0 0 1 0 1 0

Therefore, 286 & 4075 produces 100001010 which is equivalent to:

  Bit8 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0
  256 128 64 32 16 8 4 2 1
286 & 4075 1 0 0 0 0 1 0 1 0
  256 0 0 0 0 8 0 2 0

This means that 286 & 4075 = 256 + 16 + 2 = 266. To perform a bitwise conjunction, use the & operator. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        int Number1 = 286;
        int Number2 = 4075;
        int Result = Number1 & Number2;

        System.out.print("286 & 4075 = ");
        System.out.println(Result);
    }
}

This would produce:

286 & 4075 = 266

You can perform a bitwise conjunction on a variable and assign the result to the same variable. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        int Number = 286;
        System.out.println(Number);

        Number = Number & 48;
        System.out.println(Number);
    }
}

This would produce:

286
16

Instead of performing the operation on two steps, a shorter version of this operator consists of using the &= operator. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        int Number = 286;
        System.out.println(Number);

        Number &= 48;
        System.out.println(Number);
    }
}

Bitwise Disjunction

Bitwise disjunction consists of disjoining a bit from another bit. To support this operation, the Java language provides the bitwise disjunction operator represented with |.

To perform a bitwise conjunction on two numbers, remember that they must be converted to binary first. Then:

  • If a bit with value 0 is added to a bit with value 0, the result is 0
     
    Bit0 0
    Bit1 0
    Bit0 Or Bit1 0
  • If a bit with value 1 is added to a bit with value 0, the result is 1
     
    Bit0 1
    Bit1 0
    Bit0 Or Bit1 1
  • If a bit with value 0 is added to a bit with value 1, the result is 1
     
    Bit0 0
    Bit1 1
    Bit0 Or Bit1 1
  • If a bit with value 1 is added to a bit with value 1, the result is 1
     
    Bit0 1
    Bit1 1
    Bit0 Or Bit1 1

As an example, consider the number 305 bit-disjoined to 2853. The decimal number 305 converted to binary is 100110001. The decimal number 2853 converted to binary is 101100100101. Based on the above 4 points, we can disjoin these two numbers as follows:

305 0 0 0 1 0 0 1 1 0 0 0 1
2853 1 0 1 1 0 0 1 0 0 1 0 1
305 | 2853 1 0 1 1 0 0 1 1 0 1 0 1

Therefore, 305 | 2853 produces 101100110101 which is equivalent to:

  Bit11 Bit10 Bit9 Bit8 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0
  2048 1024 512 256 128 64 32 16 8 4 2 1
305 Or 2853 1 0 1 1 0 0 1 1 0 1 0 1
  2048 0 512 256 0 0 32 16 0 4 0 1

This means that 286 | 4075 = 2048 + 512 + 256 + 32 + 16 + 4 + 1 = 2869

This can also be programmatically calculated as follows:

public class Exercise {
    public static void main(String[] args) {
        int Number1 = 305;
        int Number2 = 2853;
        int Result = Number1 | Number2;

        System.out.print("305 Or 2853 = ");
        System.out.println(Result);
    }
}

This would produce:

305 Or 2853 = 2869

You can disjoint a number of bits on a variable and assign the result to the same variable. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        int Number = 305;
        System.out.println(Number);

        Number = Number | 22;
        System.out.println(Number);
    }
}

This would produce:

305
311

A short version of this operation consists of using the |= operator. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        int Number = 305;
        System.out.println(Number);

        Number |= 22;
        System.out.println(Number);
    }
}

Bitwise Exclusion

Bitwise exclusion consists of adding two bits with the following rules. To support bitwise exclusion, the Java language provides the ^ operator:

  • If both bits have the same value, the result is 0
     
    Bit0 0 1
    Bit1 0 1
    Bit0 ^ Bit1 0 0
  • If both bits have different values, the result is 1
     
    Bit0 0 1
    Bit1 1 0
    Bit0 ^ Bit1 1 1

As an example, consider the number 618 bit-excluded from 2548. The decimal number 618 converted to binary is 1001101010. The decimal number 2548 converted to binary is 100111110100. Based on the above 2 points, we can bit-exclude these two numbers as follows:

618 0 0 1 0 0 1 1 0 1 0 1 0
2548 1 0 0 1 1 1 1 1 0 1 0 0
618 ^ 2548 1 0 1 1 1 0 0 1 1 1 1 0

Therefore, 305 ^ 2853 produces 101110011110 which is equivalent to:

  Bit11 Bit10 Bit9 Bit8 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0
  2048 1024 512 256 128 64 32 16 8 4 2 1
618 ^ 2548 1 0 1 1 1 0 0 1 1 1 1 0
  2048 0 512 256 128 0 0 16 8 4 2 0

This means that 286 ^ 4075 = 2048 + 512 + 256 + 128 + 16 + 8 + 4 + 2 = 2974

This can also be programmatically calculated as follows:

public class Exercise {
    public static void main(String[] args) {
        int Number1 = 618;
        int Number2 = 2548;
        int Result = Number1 ^ Number2;

        System.out.println(Result);
    }
}

This would produce:

2974

You can bitwise exclude a number of bits from a variable and assign the result to the variable itself. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        int Number = 618;
        System.out.println(Number);

        Number = Number ^ 38;
        System.out.println(Number);
    }
}

This would produce:

618
588

As an alternative, you can use the ^= operator to get the same result. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        int Number = 618;
        System.out.println(Number);

        Number ^= 38;
        System.out.println(Number);
    }
}

Left-Shifting the Bits

Left shifting the bits consists of pushing each bit from right to left. You can do this by one ore more bits. Once again, to perform this operation, the number has to be converted to its binary equivalent. To support this operation, the Java language provides an operator represented as <<.

Imagine you have a number as 741. Its binary equivalent is 1011100101 and can be represented as:

1 0 1 1 1 0 0 1 0 1

To perform a left shift operation on these bits, you push each from its position to the left, depending on the number of pushes you want. For example, to left-shift by 1 bit, you push each bit to the left by one position. Actually, you consider the bit at position x and the bit to its left at position y. You replace the value of Bit y by the value of Bit x. If Bit x is the most right bit, it receives a value of 0. This can be illustrated as follows:

Original   1 0 1 1 1 0 0 1 0 1
<< by 1 1 0 1 1 1 0 0 1 0 1 0

As a result, we get 10111001010. The decimal result can be calculated as follows:

  Bit10 Bit9 Bit8 Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0
  1024 512 256 128 64 32 16 8 4 2 1
741 << 1 1 0 1 1 1 0 0 1 0 1 0
  1024 0 256 128 64 0 0 8 0 2 0

Consequently, 741 << 1 = 1024 + 256 + 128 + 64 + 8 + 2 = 1482. To programmatically perform this operation, use the << operator. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        System.out.println(741 << 1);
    }
}

This would produce:

1482

In the same way, you can push the bits to the left by more than one unit. Here is an example:

public class Exercise {
    public static void main(String[] args) {
        int Number = 248 << 5;

        System.out.println(Number);
    }
}

This would produce:

7936

You can push a few bits to the left of a variable and assign the result to the variable itself. Here is an example:

public class Exercise {
    public static void main(String[] args) {
            int Number = 248;
            System.out.println(Number);

            Number = Number << 5;
            System.out.println(Number);
    }
}

This would produce:

248
7936

To provide another version of this operation, the Java language is equipped with the <<= operator. Here is an example of using it:

public class Exercise {
    public static void main(String[] args) {
        int Number = 248;
        System.out.println(Number);

        Number <<= 5;
        System.out.println(Number);
    }
}

Right-Shifting the Bits

You can shift the bits to the right. Everything is done as reviewed for the left shift but in reverse order. To support this operation, the Java language provides the >> operator.

 

 

Computer Languages

C#
C++
Visual Basic

   

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