Variables & Operators – Part 2: Operators

Things will begin to get interesting….

 

So now you know how to install Java and Eclipse, how to create a simple project, a class and print the Hello World message, and also you know that Java has certain data types that can be used to create variables to store data.

 

But… what can be done with the data in the variables?

 

It is time to introduce to you the operators. With them you can do “operations” to your variables.

 

There are quite a few operators in Java, and they are categorized into:

  • Assignment
  • Arithmetic
  • Unary
  • Equality
  • Conditional
  • Bitwise/bit shift

 

I will explain all of these categories in this blog, but will get into more detail about Conditional and Equality operators in the Control Statements block posts.

 

Every category will be explained using an example.

 

Assigment Operator

Simple one. It is used to assign a value to a variable and it is represented by the equal symbol:

 


// Assignment operator

int firstValue = 8;

int secondValue = 24;

 
 

Arithmetic Operators 

In the next table you can see the arithmetic operators and their symbols:

 

Symbol Operation
+ add/concatenate
subtract
* multiply
/ divide
% remainder

 

Remember your elementary school classes. As you probably had already imagined, you can add, subtract, multiply and divide numbers in programming too.

 


// Arithmetic operators

int result = 0;

result = firstValue + secondValue;

System.out.println("Addition operator result: " + result);

result = secondValue - firstValue;

System.out.println("Subtraction operator result: " + result);

result = firstValue * secondValue;

System.out.println("Multiplication operator result: " + result);

result = secondValue / firstValue;

System.out.println("Division operator result: " + result);

You can try to do these operations using different data types, like float, double, long, etc and mixing them to see what happens. Be sure to have consistent data types of your operands and the result. (Later in another post I will explain what “cast” is about… remember this).

 

There is a new function for the plus + sign when you use it with strings. It won’t add the strings, but it will concatenate them, meaning that you can join two strings together with the plus sign.

 


// Arithmetic operator - Strings

String firstString = "This is ";

String secondString = "a good day.";

String stringResult = firstString + secondString;

System.out.println("String concatenation: " + stringResult);

 

It is important to see that depending on the type of data that you have in your operations, you will have a different result.

 

These are the most used operators in programming. But there is another one that will join this family: the remainder operator or modulus. This operator returns the remainder of the division between two numbers.

 


// Arithmetic operator - remainder/modulus

result = secondValue % firstValue;

System.out.println("Remainder: " + result);

result = firstValue % secondValue;

System.out.println("Remainder: " + result);

 

Unary Operators

They are called unary because they only require one operand: they apply to only one variable.

 

Symbol Operation
+ Indicates positive value (no need to use it)
Negates the value
++ Increments the value in one.
Decrements the value in one
! Inverts the boolean value (Logical complement)

 


/* Unary operators */

int unaryValue = 5;

// - operator

result = -unaryValue;

// Result is -5, no big deal here.

System.out.println("Result: " + result);

 

 

For the ++ and — operators, it matters where you use the operator: after or before the variable. If you use it before, first it will make the increment/decrement and then it will perform the operation that you want, and if you use it after, you will use the original value first and then it will increment its value. This will be clearer in the example:

 


System.out.println("========== Unary Operators: value++/value-- ==========");

// ++ operator, unaryValue++

// unaryValue has a 5.

System.out.println("Original value: " + unaryValue);

// unaryValue prints a 5, after printing, it increments to 6

System.out.println("Result unaryValue++, value doesn't change: " + unaryValue++);

// unaryValue incremented to 6 after printing in the previous line.

System.out.println("Result unaryValue, value changed in previous line: " + unaryValue);

System.out.println("========== Unary Operators: ++value/--value ==========");

// ++ operator, ++unaryValue

// unaryValue has a 6.

System.out.println("Original value: " + unaryValue);

// unaryValue prints a 7, because it increments BEFORE printing.

System.out.println("Result ++unaryValue, value changes: " + ++unaryValue);

 

If you want to invert a boolean value, use the ! operator:

 


System.out.println("========== Unary Operators: ! ==========");

boolean booleanValue = true;

System.out.println("Boolean original value: " + booleanValue);

System.out.println("Boolean inverted value: " + !booleanValue);

 

Equality Operators

 They are used in the control statements (next week’s post, wait for it) to evaluate if a value is equal, greater than, less than, greater or equal than or less or equal than another number.

 

Symbol Operation
== Equal to (two equal symbols, one is for assignment!!)
!= Not equal to
> Greater than
< Less than
>= Greater or equal than
<= Less or equal than

 


/* Conditional Operators */

System.out.println("========== Equality Operators ==========");

System.out.println("1 == 2?: " + (1 == 2));

System.out.println("1 >= 2?: " + (1 >= 2));

System.out.println("1 < 2?: " + (1 < 2));

 

It is important to note that the result of an operation using Equality operators will always be true or false.

 

Conditional Operators

They are AND and OR, meaning that they compare two boolean expressions or values and they follow the AND and OR logical table for the results:

 

  • AND: will only be true if all expressions are true, false otherwise.
  • OR: will be true when one or all the expressions are true, false otherwise.

 

Symbol Operation
&& AND
|| OR

 


/* Conditional Operators */

System.out.println("========== Conditional Operators ==========");

System.out.println("true AND false?: " + (true && false));

System.out.println("true AND true: " + (true && true));

System.out.println("true OR false?: " + (true || false));

System.out.println("false OR false?: " + (false || false));

 

IMPORTANT NOTE: Maybe these examples for Equality and Conditional operators are foolish examples, but what I want you to learn are the different operators and the results that they generate. Later on I will create a post with a more realistic example where you can see a real usage of this. Believe me, you will use them everyday and everytime.

 

Bit wise/Bit shift operators

These operators are rarely used but it is good for you to know that they exist. Maybe they will save your life someday!

 

Symbol Operation
~ Inverts a bit pattern: ~1111 = 0000
<< Left shift operator
>> Signed Right shift operator
>>> Unsigned right shift operator
& Bit AND operator
^ Bit XOR operator
| Bit OR operator.

 

For the AND, XOR, and OR, the operation is applied bit by bit (for AND and OR you can see previous explanation, XOR will give true or 1 if one of the operands is 1, but if both are 1 or 0, the result is 0).

 


/* Bitwise/Bitshift Operators */

System.out.println("========== Bitwise/Bitshift Operators ==========");

int bitmask = 0x000F; // 0000 0000 0000 1111

int val = 0x2222;    //  0010 0010 0010 0010

// & result: 0000 0000 0000 0010 = 2

System.out.println("Bitwise AND: " + (val & bitmask));

// | result: 0010 0010 0010 1111 = 8751

System.out.println("Bitwise OR: " + (val | bitmask));

// ^ result: 0010 0010 0010 1101 = 8749

System.out.println("Bitwise XOR: " + (val ^ bitmask));

&nbsp;

bitmask = 0x0001; // this is 1 in binary: 0000 0000 0000 0001

System.out.println("Shift left 2 positions: " + (bitmask<<2)); //it moves the 1 two spaces to the left to get 0100, that is 4.

bitmask = 0x0004; // this is 2 in binary: 0000 0000 0000 0100.

System.out.println("Shift right 1 position: " + (bitmask>>1)); //it moves the 1 one space to the right to get 0010, that is 2.

 

Just remember that these operators exist and what they do, and someday you may come to a situation where these operators will help you solve your problem, and then you can research some more about them.

 

——

That is all for Operators and for the first Block in our diagram: Variables and Operators. Next time I will talk about Control Statements, where you can use everything learned until today.

You can find the code for this post in Warrior Minds Github.

 

**Questions? Comment or email me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s