The BASE for JAVA LEARNING

by PRO FE S S OR


SECTION IV - Operators and Casting

Step 11: Kinds of Operators and the Assignment Operator


Operators in all languages are used to facilitate code operation and algorithms.

The different kinds of Operators in JAVA can be classified into 6 groups:


The Assignment Operator as its name implies is used to initialize, or assign values to variables. It can also be used to instantiate a class (Object creation), or to initialize an array when used with the 'new' operator.(to be covered later).

Example of Assignment Operators usage: int day = 30; // the day variable is set to be 30.

Exercise quiz = new Exercise();           // An Object is created (to be covered in later)

double[] amount = new amount[12]; // An array is created (to be covered in later)

amount = payment ; // value for 'money' is made equal to value 'payment'.

String greetings = "Welcome...." ;      // A message is assigned to the String greeting


Click here to go to the JAVA Mini-Course page



The BASE for JAVA LEARNING

by PRO FE S S OR


SECTION IV - Operators and Casting

Step 12A: Arithmetic Operators


The Arithmetic Operators are represented by the following symbols:
+           -            *           /           %

Arithmetic Operators are applied upon 'int' , 'long', 'float' or 'double'.   When applied upon 'byte', 'short' or 'char' explicit casting may have to be utilized. (to be covered later)


The '+' and '-' signs (plus and minus signs): It implies addition and subtration respectively.

When it's used upon a character type, the ASCII code value is incremented or decremented accordingly. But remember that the char type has to be explicitly casted.

See the following code:

class Exercise
{
      public static void main(Stringp[] args)
      {
             char letter = 'A'; ;
             letter = (char)(letter+2);
             System.out.println(letter); // displays C.
             letter = (char)(letter-1);
             System.out.println(letter); // displays B.
      }
}

The + sign can also be used for concatenating Strings into other Strings. By virtue of implicit casting, (to be covered in next Step) this sign can be used in the console output method "System.out.println(... + ... + ....)" as delimiter between the various variables within the set of parenthesis. (Each variable that is not a String is cast into a String and concatenated into a console output String.)

See the following code:

class Exercise
{
public static void main(String[] args)
{
int year=1998;
String name = "John Smith";
System.out.println(name + " was born in " + year + ".");
}
}

When executed above code, it will display "John Smith was born in 1958."


Other Arithmetic Operators:

The * and / operators:
The * and / signs imply multiplication and division respectively.


The % modulo operator:
This operator yields the remainder of a division of two numbers. For example: 46 % 4 yields 2.

This operator is usually applied to integers. It can be used to find whether a number is divisible by a known integer.

See code below to find our whether a year is leap or not. Notice that the modulo operator is used to find out when a given year is divisible by 4, 100, and by 400. We are using
Input.class to enter the year as an integer via the Keuboard. (Make certain the Input.class is in the same directory where this program is.)

class Exercise
{
public static void main(String[] args)
{
System.out.println("Enter a year ");
int year = Input.enterInt();
if((year%400)==0) System.out.println("It's a Leap Year"); else if ((year%100)==0) System.out.println("It's NOT a Leap Year"); else if ((year%4)==0) System.out.println("It's a Leap Year"); else System.out.println("It's NOT a Leap Year");
}
}



Arithmetic and Assignment Operator combined

When we want to assign an operation to a variable, we will have the variable on the left side of the equal sign, and the expression to the right side of the equal sign. The arithmetic operators are used upon the fields on the expression on the right side.

Examples: a = a + b ; // this results in adding b to a and place result on a.
a = a - 1 ; // this results in decrementing a by one
a = a + 2 ; // this results in incrementing a by two.
a = a * c ; // this results in multiplying a by c, and place result on a.

There is another way of doing this in JAVA, and that is by placing the arithmetic operator directly on the left of the equal sign, and then eliminating the variable to which is assigned from the right side expression.

The 3 examples below are equivalent to the ones above: a += b; // this results in adding b to a and place result on a.
a -= 1; // this results in decrementing a by one.
a += 2; // this results in incrementing a by two.
a *= c; // this results in multiplying a by c, and place result on a.

Click here to go to the JAVA Mini-Course page


The BASE for JAVA LEARNING

by PRO FE S S OR


SECTION IV - Operators and Casting

Step 12B: Unary Arithmetic Operators



Unary Arithmetic Operators:    ++         --
These operators are called Unary, because they operate on a single term. They can be applied upon any primitive data type except boolean.
++ implies increment by one, and -- implies decrement by one.

They can be pre-fixed if they are used preceding the term, or post-fixed if they are used after the term.

Usually pre-fixed and post-fixed usages are meaningful when combined with other statements, that is, in the same line of code.

There are 2 examples below, the first example the ++ operator is post-fixed. In the second example, the -- operator is pre-fixed.

In these examples the operator is used on the same line of code that displays the variable value. Notice that in the case of the post-fixed usage, (first example below) the variable increment takes effect only after the output display is implemented. In the case of the pre-fixed usage, (second example below) the char variable decrement takes effect before the output display is implemented.

class Exercise
{
public static void main(String[] args)
{
int month = 4;
System.out.println(a++); // Post-fixed usage. Here the number 4 is displayed, // as the increment of month is implemented afterwards. System.out.println(a); // Here the number 5 is displayed.
}
}
class Exercise
{
public static void main(String[] args)
{
char letter = 'E';
System.out.println(--letter); // Pre-fixed usage. Here the letter 'D' is displayed, // as the decrement of month is implemented before the display. System.out.println(letter); // Here the letter 'D' is displayed.
}
}

The BASE for JAVA LEARNING

by PRO FE S S OR


SECTION III - Operators and Casting

Step 13: Casting


Casting is the change of a variable from one Data Type to a different one on the fly, that is, temporarily on that line of code where it's implemented. We can also have some Object casting, and we'll discuss that in later Sections.

After the variable is cast on that line of code where implemented, then it returns back to its data types for the remainder of the code.

In JAVA there are 2 different ways of Casting:

  • Implicit Casting


  • Explicit Casting



Implicit Casting

As the name implies, Implicit Casting is done automatically by the compiler, and it always happen when we try to assign or set a variable to a larger size data type. More about Object casting in later Sections.

In the example below, the compiler casts the sum of 2 float variable into a 'double', and the sum of two chars into an int. This casting is done when the sum is implemented. This is because a 'float' can fit into an 'double', and a 'char' can fit into an 'int'. (Notice that this is transparent to the programmer, as the compiler will not give you any warning.)

See below:

class Exercise
{
public static void main(String[] args)
{
float a = 4.2f;
float b = 45.67f;
double sum = a + b; // the sum of the 2 floats are implicitly casted into a double.

char c = 'C'; // 'C' is the Ascii code 67.
char d = 'D'; // 'D' is the Ascii code 68.
int e = c + d ; // the sum of 67 and 68 is implicitly casted into an int.
System.out.println(e); // displays 135 }
}
}



Explicit Casting

As the name implies, Explicit Casting is explicitly stated by the Programmer, and it has to be used when we try to assign or set a variable to a smaller size data type. More about Object casting in later Sections.

In the example below, the compiler by virtue of explictly casting, casts the sum of 2 'doubles' into a 'float', and the sum of two 'int's into a char. This casting is forced by using a set of parentheses around the desired data type. Explicit casting is needed because a 'double' does not fit into a 'float', and an 'int' does not fit into a 'char'.

See below:

class Exercise
{
public static void main(String[] args)
{
double a = 4.2f;
double b = 45.67f;
float sum = (float)(a + b); // the sum of the doubles is explicitly casted into a float.

int c = '1'; // '1' is the Ascii code 49.
int d = '2'; // '2' is the Ascii code 50.
char e = (char)(c + d) ; // the sum of 49 and 50 is explicitly casted into a char.
System.out.println(e); // display 'c' which is the ASCII of 99. }
}
}


Click here to go to the JAVA Mini-Course page


The BASE for JAVA LEARNING

by PRO FE S S OR


SECTION IV - Operators and Casting

Step 14: Relational Operators


Relational Operators

The Relational Operators are those used for Comparison.

There are 5 Relational Operators:        ==        <        >        <=        >=

The Relational Operators are applied upon left and right term of an expression. It compares the left and right term and makes an evaluation to either true or false.

==   compares if the right and left terms are equal.
>    compares if the left term is greater than the right term.
<    compares if the left term is less than the right term.
>=   compares if the left term is greater or equal to the right term.
<=   compares if the left term is less or equal to the right term.

Example: if (a>b) will evaluate to true if a is greater than b, otherwise it will evaluate to false.
There is a trap that many programmer fall into, and that's when the assignment operator "=" is mistakenly used for the equality Relational Operator "==". Most Java and C, C++ Programmers have made this mistake one time or another.

See Example below:

class Exercise
{
public static void main(String[] args)
{
boolean flag1 = false;
boolean flag2 = true;
if (flag1=flag2) System.out.println("True"); // "True" is displayed. // The 'if' construct above does not compare flag1 with flag2.
// Instead it assigns the value of flag2 to flag1,
// and since flag1 becomes true, the display statement is implemented.
}
}
}
Click here to go to the JAVA Mini-Course page



The BASE for JAVA LEARNING

by PRO FE S S OR


SECTION IV - Operators and Casting

Step 15: Logical Operators


Logical Operators

The Logical Operators are:    &&       ||       !

The Logical Operators are used to represent the boolean AND and OR for a term within an expression.
&&     represents the boolean AND (applied to two terms or more)
||         represents the boolean OR (applied to two terms or more)
!         represents the boolean NOT (Unary operator: applied to one term)
         (if true, makes it false, if false, makes it true)
For example: if (flag1 && flag2) -> here both flag1 and flag2 have to be true in order for the 'if' construct to evalutate to true.

if (flag1 || flag2) -> here only if either flag1 or flag2 is true, will make the 'if' construct evaluate to true.
Of course, multiple terms can be used.

Other Examples: if ( (flag1 && flag2) || flag3 ) -> here the 'if' construct evaluates to true if flag3 is true, OR if both flag1 AND flag2 are true.

if ( !flag1 || (flag2 && flag3) ) -> here the 'if' construct evaluates to true if flag1 is false, OR if both flag1 AND flag2 are true.



The && and || operators are called short-circuit Operators. When a boolean term is encountered, if it is false and followed by   &&  , the compiler would not evaluate the next term, as the result is already known to be false. By the same token, if the first boolean term encountered is true, and is followed by   ||   , the compiler would not evaluate the next term, as the result if already known to be true.
Let's say we have two boolean variables: flag1 and flag2; and let's further say that flag1 is false. But we don't know what flag2 is.

Then, when evaluating the expression (flag1 && flag2) we don't need to know what flag2 is. That expression is false, no matter what the flag2 value is. That is, the compiler does not need to evaluate flag2, as the whole expression is false.

If flag1 would have been true, then flag2 would have to be evaluated to find out the result of (flag1 && flag2).



Click here to go to the JAVA Mini-Course page



The BASE for JAVA LEARNING

by PRO FE S S OR


SECTION IV - Operators and Casting

Step 16: Bitwise Operators


Bitwise Operators

The operators are:       &       |       <<       >>       >>>       ~

These Operators are used for Binary Arithmetic. Their results are of the data type 'int'.

&         means binary AND applied upon multiple terms
|           means binary OR applied upon multiple terms
<<       means shift to the left applied upon one term and number of bits to shift.
>>       means shift to the right applied upon one term and number of bits to shift.
>>>    means shift to the right, ignoring the MSB (sign), applied upon one term and number of bits to shift.
~         means one's complement, or binary invert (Unary operator applied only on one term)
            (each bit of the term changes value.)


Binary AND & and BINARY OR |

In order to show ANDing and ORing of numbers, it's best done when we use hexadecimal numbers. As you recall from Section II, a hexadecimal number can be expressed by having 0x in front of the number. That is, 0x1000 is the number 1000hex which is equivalent to 4096 in the regular base 10 system.

In the following example, first we apply the AND upon 3 hex numbers, then we apply the OR upon the same numbers. And finally we apply both AND and OR upon some other numbers.

class Exercise
{
public static void main(String[] args)
{
int a = 0x1AAF;
int b = 0xFF55;
int c = 0xFFF1;
int ANDresult = a & b & c;
System.out.println(ANDresult); // the number 6657 is displayed which is 1A01 in hex.

int ORresult = a | b | c;
System.out.println(ORresult); // the number 65535 is displayed which is FFFF in hex.

int d = 0xAAAA;
int e = 0x5500;
int f = 0x1733;
int AND_ORresult = d & e | f; // d is ANDed with e and its result ORed with f.
System.out.println(AND_ORresult); // the number 5939 is displayed which is 1733 in hex. }
}
}



The    ~    Operator

This operator is applied upon one term and it inverts all its bits.

There is an easy way to find the result when the ~ operator is applied. The sign of the number is changed, and 1 is subtracted from it.
Example: int a = -12;
System.out.println(~a);

// displays 11.        (-12 changes sign to 12, and then 12 - 1 = 11).



More about Bitwise Operators later.....


Click here to go to the JAVA Mini-Course page