Java Basic Operations Explained with Examples

Basic Operations

Java supports the following operations on variables:

  • Arithmetic : Addition (+) , Subtraction (-) , Multiplication (*) , Division (/) , Modulus (%) , Increment (++) , Decrement (--) .
  • String concatenation : + can be used for String concatenation, but subtraction - on a String is not a valid operation. In java *** + *** operator is overloaded on functionality to concatenate strings and to perform addition information
  • Relational : Equal to (==) , Not Equal to (!=) , Greater than (>) , Less than (<) , Greater than or equal to (>=) , Less than or equal to (<=) Always remember sign of greater and less than always come before assign i.e "="
  • Bitwise : Bitwise And (&) , Bitwise Or (|) , Bitwise XOR (^) , Bitwise Compliment (~) , Left shift (<<) , Right Shift (>>) , Zero fill right shift (>>>) . **Bitwise operators are used to perform bitwise operation in places where calculation on binary numbers are required like-in ciphers,and to design virtual electronic circut replication etc. **
  • Logical : Logical And (&&) , Logical Or (||) , Logical Not (!)
  • Assignment : = , += , -= , *= , /= , %= , <<= , >>= , &= , ^= , |=
  • Others : Conditional/Ternary(?:) , instanceof **Ternary because it work on the functionality of If Then Else i.e If condition is right then first alternative anotherwise the second one ** While most of the operations are self-explanatory, the Conditional (Ternary) Operator works as follows:
    expression that results in boolean output ? return this value if true : return this value if false;

The Assignment operators ( += , -= , *= , /= , %= , <<= , >>= , &= , ^= , |= ) are just a short form which can be extended. Example: ( a += b ) does the same thing as ( a = a + b )!

Example: True Condition:

int x = 10;
int y = (x == 10) ? 5 : 9; // y will equal 5 since the expression x == 10 evaluates to true

False Condition:

int x = 25;
int y = (x == 10) ? 5 : 9; // y will equal 9 since the expression x == 10 evaluates to false

The instanceof operator is used for type checking. It can be used to test if an object is an instance of a class, a subclass or an interface. General format- object instance of class/subclass/interface

Here is a program to illustrate the instanceof operator:

Person obj1 = new Person();
Person obj2 = new Boy();
// As obj is of type person, it is not an
// instance of Boy or interface
System.out.println("obj1 instanceof Person: " +  (obj1 instanceof Person)); /*it returns true since obj1 is an instance of person */

Operation of ASSIGNMENT Operators explained:

Often times students come across questions in exam/quizes involving complex equations/relations between different variables established with different combinations of assignmen operators. On face, they look preety ambiguous. But follwoing a simpe rule might make solving them preety straigh forward. The rule itself is simple… On any circumstance, first one must deal with PRE-operations, then ‘Assignment’ operator and then finally comes with ‘POST - operations’.

In summary, the order of operation is -

Step 1. PRE-operations

Step 2. Assignment

Step 3. POST - operations.

For example:

 int a = 1;
 int b;
 int b = a-- + ++a ;

What will be the value of a & b after the program compiles?

Step 1. PRE-operations:

a is assigned value 1.

Upon pre-assignment, it becomes 2(since it is ‘+’ here)

Step 2. Assignment:

At this point,

a = 2

and for b ,

b =a-- + ++a

or, b = 2-- + 2 = 4. [Note:POST - operations has not yet come to play yet]

Step 3. POST - operations:

At this point, b = 4 a = 2. But WAIT, there’s still one ‘post operation’ on a to deal with… i.e. a–

So it follows:

a-- // 2-- =  1 (since it is '-' here).

Again, consider this example:

int num1 = 10;
int num2 = 0;
int num3 = 4;
int num4 = 6;

num3 = ++num1 - num4++;

What will be the value of num3 & num4 ?

num3 = 5
num4 = 7

Bitwise operators

Truth table

The bitwise operators are similar to the logical operators, except that they work on a smaller scale – binary representations of data. Any data can be converted to its binary equivalent. Though binary operators work at binary level but they are operated between normal decimal values only.

Types of Bitwise Operators

Bitwise OR

Bitwise OR is a binary operator (operates on two operands). It’s denoted by |. The | operator compares corresponding bits of two operands. If either of the bits is 1, it gives 1. If not, it gives 0.

Bitwise AND

Bitwise AND is a binary operator (operates on two operands). It’s denoted by &. The & operator compares corresponding bits of two operands. If both bits are 1, it gives 1. If either of the bits is not 1, it gives 0.

Bitwise Complement

Bitwise complement is an unary operator (works on only one operand). It is denoted by ~. The ~ operator inverts the bit pattern. It makes every 0 to 1, and every 1 to 0.

Bitwise XOR

Bitwise XOR is a binary operator (operates on two operands). It’s denoted by ^. The ^ operator compares corresponding bits of two operands. If corresponding bits are different, it gives 1. If corresponding bits are same, it gives 0.

Left Shift

The left shift operator << shifts a bit pattern to the left by certain number of specified bits, and zero bits are shifted into the low-order positions.

Right Shift

The right shift operator >> shifts a bit pattern to the right by certain number of specified bits.If the number is a 2’s complement signed number, the sign bit is shifted into the high-order positions.

Unsigned Right Shift

The unsigned right shift operator >>> shifts zero into the leftmost position.

Example bitwise operators :

    int a = 60;	      /* 60 = 0011 1100 represents 60 in binary*/
    int b = 13;	      /* 13 = 0000 1101 */
    int c = 0;
    
    c = a & b;        /* 12 = 0000 1100 */
    c = a | b;        /* 61 = 0011 1101 */
    c = a ^ b;        /* 49 = 0011 0001 */
    c = ~a;           /*-61 = 1100 0011  :Invert all bits */
    
    // shift operators : zeros are shifted in to replace the discarded bits
    c = a << 2;       /* 240 = 1111 0000 : Shift left 2 bits*/
    c = a >> 2;       /* 15 = 1111 */
    c = a >>> 2;      /* 15 = 0000 1111 : Zero fill right shift*/