Master java skills

Java Operators

Operators are used to perform operations on values. They have been divided into following categories in java.

  1. Arithmetic Operators (like +,-,*,/ etc)
  2. Assignment Operators (like =, += etc)
  3. Comparision Operators (like >, >=, < etc)
  4. Logical Operators (like &&, || etc)
  5. Bitwise Operators (like &, | etc)

Arithmetic Operators

OperatorNameOperation
+AdditionAdds two numbers
SubtractionSubract one number from another
*MultiplicationMultiplies two numbers
/DivisionDivide one number by another
%ModulousGives the remainder in a division
++IncrementIncreases the value of the operand by 1
– –DecrementDecreases the value of the operand by 1

Example of Airthmetic operators :

package com.sks;

public class ArithmeticOperations {
	
	
	public static void main(String[] args) {
		
		int num1 = 28;
		int num2 = 9;
		
		int sum = num1 + num2;
		System.out.println("Sum = " + sum);
		
		int subtraction = num1 - num2;
		System.out.println("Subtraction = " + subtraction);
		
		int multiplication = num1 * num2;
		System.out.println("Multiplication = " + multiplication);
		
		int division = num1 / num2;
		System.out.println("Division = " + division);
		
		int remainder = num1 % num2;
		System.out.println("Remainder = " + remainder);
		
		num1++;
		System.out.println("Increment = " + num1);
		
		num2--;
		System.out.println("Decrement = " + num2);
	}

}

Output :

Sum = 37
Subtraction = 19
Multiplication = 252
Division = 3
Remainder = 1
Increment = 29
Decrement = 8

Assignment Operators

These operators are used to assign values to variables

OperatorExampleExplanation
=a = 6a = 6
+=a += 3a = a + 3
-=a -= 5a = a – 5
*=a *= 2a = a * 2
/=a /= 6a = a / 6
%=a %= 3a = a % 3
|=a |= 3a = a | 3
&=a &= 4a = a & 4
^=a ^= 6a = a ^ 6
>>=a >>= 4a = a >> 4
<<=a <<= 4a = a << 4

Example of Assignment Operators :

package com.sks;

public class AssignmentOperatorsExample {
	
	public static void main(String[] args) {
		int a = 5;
		a += 3;  //equivalent to (5 + 3)
		System.out.println("Value of a after increment : " + a); //a is 8 now
		
		a -= 3;  //equivalent to (8 - 3)
		System.out.println("Valur of a after decrement : " + a); //a is 5 now
	}
}

Output :

Value of a after increment : 8
Value of a after decrement : 5

Comparision Operators

These operators are used to compare two values.

OperatorNameExample
==Equalsa == b
!=Not Equalsa != b
>Greater thana > b
>=Greater than or equalsa >= b
<Less thana < b
<=Less than or equalsa <= b

Example of Comparision Operators :

package com.sks;

public class ComparisionOperatorsExample {
	
	public static void main(String [] args) {
		int a = 27;
		int b = 29;
		
		System.out.println("a equals b : " + (a == b));
		System.out.println("a not equals b : " + (a != b));
		System.out.println("a greater than b : " + (a > b));
		System.out.println("a greater than or equals b : " + (a >= b));
		System.out.println("a less than b : " + (a < b));
		System.out.println("a less than or equals b : " + (a <= b));
	}

}

Output :

a equals b : false
a not equals b : true
a greater than b : false
a greater than or equals b : false
a less than b : true
a less than or equals b : true

Logical Operators

These operators are used to evaluate the logic between two values

OperatorNameExplanationExample
&&Logical AndReturns true if both statements on either side of the operator are truea > 10 && a < 100
||Logical OrReturns true if either of the statements on either side of the operator is truea > 10 || a > 20
!Logical NotReverses the result of the expression. If the actual result is true, Logical Not will be false and vice-versa!( a > 10 || a > 20)

Example of logical operators :

package com.sks;

public class LogicalOperatorsExample {

	public static void main(String[] args) {

		int a = 20;
		int b = 10;
		int c = 100;

		System.out.println("a lies between a and B ? " + (a > b && a < c));

		int d = 35;
		int e = 30;
		int f = 40;

		System.out.println("d is either less than e or f ? " + (d < e || d < f));

		int x = 50;
		int y = 60;

		System.out.println("x equals to y ? " + !(x == y));
	}
}

Bitwise Operators

Bitwise operators works on the bits of the input numbers. First, decimal numbers are converted to their binary equivalent, and then bitwise operations are performed on them. Below is the list of bitwise operators.

OperatorNameDescription
&Bitwise ANDReturns 1 if both the bits are 1
|Bitwise ORReturns 1 if one of the bits is 1
^Bitwise XORReturns 1 if both the bits are different
~Bitwise Complement (Bitwise NOT)It negates every bit. 0 for 1 and 1 for 0.

Let’s take two integers and get the result of their Bitwise operations in the below example.

package com.sks;

public class BitwiseOperatorsExample {

	public static void main(String[] args) {
		int a = 4;
		int b = 5;
		int bitwiseAndResult = a & b;
		System.out.println("Bitwise And result is : " + bitwiseAndResult);
		int bitwiseOrResult = a | b;
		System.out.println("Bitwise Or result is : " + bitwiseOrResult);
		int bitwiseXorResult = a ^ b;
		System.out.println("Bitwise Xor result is : " + bitwiseXorResult);
		int bitwiseNotResult = ~a;
		System.out.println("Bitwise Not result is : " + bitwiseNotResult);
	}
}

Output :

Bitwise And result is : 4
Bitwise Or result is : 5
Bitwise Xor result is : 1
Bitwise Not result is : -5

Explanation : Let’s understand how ‘Bitwise And result’ is 4. First we need to convert 4 and 5 into their binary form

Bitwise AND
number    binary
________________
4      =   0100 
5      =   0101
________________
&          0100 (This in decimal form is 4. Therefore the result is 4)


Bitwise OR
number    binary
________________
4      =   0100 
5      =   0101
________________
|          0101 (This in decimal form is 5. Therefore the result is 5)


Bitwise XOR
number    binary
________________
4      =   0100 
5      =   0101
________________
^          0001 (This in decimal form is 1. Therefore the result is 1)


Bitwise NOT
number    binary
________________
4      =   0100 
________________
~          1011 (How this will become -5 in decimal format. Read the below explanation for the same.)

Bitwise NOT explanation :

How to calculate Bitwise NOT of any number

1. Convert the decimal number into its binary form
2. Get the Bitwise Complement of the number
3. Find the 2's complement of the binary number that we got in step 2.
4. Convert 2's complement to decimal form. This value will be Bitwise NOT of the number.

Example
1. number 4 in binary :       0000 0100
2. Bitwise not of 4 :         1111 1011 (The left most bit is 1 which represnt -ve number)
3. 2's complement          :  0000 0100 (1's complement of binary in step 2)
                                     +1
------------------------------------------
   2's complement             0000 0101
4. Decimal of 0000 0101 is 5. But since we know, the number is supposed to be negative as we saw in 
step 2. Therefore, the resultant value is -5

Bitwise Shift Operators

There are three Bitwise Shift operators also. Let’s understand them as well.

OperatorNameDescription
<<Singed Left ShiftShifts the number of bits of a number to the left by the number of times mentioned.
>>Signed Right ShiftShifts the number of bits of a number to the right by the number of times mentioned.
>>>Unsigned Right ShiftThis is similar to Signed Right Shift. The only difference is that empty spaces in the left are filled with 0 irrespective of whether the number is negative or positive.

Signed Left Shift Operator

This operator shifts all the bits of a number by number of times mentioned by a digit on right side of the operator. After the bits are shifted, obviously, there would be empty spaces on the right side. These empty spaces are filled with ‘0’. E.g. 14 << 2 will shift all the bits of binary number of 14 to 2 positions towards left and fill right side spaces by ‘0’.

example 1 :
a      = 0000 1010
a << 2 = 0010 10-- (Since it is two positions left shifting there are two spaces created on the   right side)
We have to fill spaces with 0 bit. So, the value of a will become
a = 0010 1000

example 2 :
b      = 1101 0101
b << 3 = 1010 1--- (3 spaces are created here since it is 3 positions left shifting)
b      = 1010 1000

Note -> Shifting bit left by one position is equivalent to multiplying the number by 2. That means shifting bits by n positions means multiplying the number by 2^n.

Let’s take one example

package com.sks;

public class ShiftOperatorExample {

	public static void main(String[] args) {

		System.out.println("Value of 14 left shift by 2 = " + (14 << 2));
	
	}
}

/*Explanation
14        = 00001110
14 << 2   = 001110-- 
Fill the right side spaces by 0
14 << 2   = 00111000 = 56 in decimal

This can also be calculated as (14 * 2^2) = 56
*/

Output :
Value of 14 left shift by 2 = 56

Explanation :

Binary of 14 = 00001110

Shift all the bits by 2 positions : 001110– (Here two spaces will be created after shifting.)

According to the rule, we have to fill these spaces with ‘0’. So, the result becomes : 00111000

00111000 (0 + 0 + 1*2^5 + 1*2^4 + 1*2^3 + 0 + 0 + 0) is 56 in decimal.

Note -> This can also be calculated as 14 * 2^2 = 56

Signed Right Shift Operator

This operator shifts all the bits to the right by number of positions mentioned to the right side of the operator. E.g. 13 >> 3 will shift all the bits of binary number of 13 to 3 positions towards right.

If the numbe is positive, then spaces created on the left side will be filled with 0. If the number is negative, then spaces will be filled by 1.

example 1 :
a       = 0000 1101 (This is 13 in decimal)
a >> 3  = ---0 0001 (Since it is three positions right shifting there are three spaces created on the left side)
Since it is positive number, we have to fill spaces with 0 bit. So, the value of a will become
a       = 0000 0001 (This is 1 in decimal)

example 2 :
b      = 1111 0011 (this is -13 in decimal)
b >> 3 = ---1 1110 (3 spaces are created on the left here since it is 3 positions right shifting)
Since -13 is negative number, we have to fill spaces with 1 bit.
b      = 1111 1110 (this is -2 in decimal)

Java code example :

package com.sks;

public class ShiftOperatorExample {

	public static void main(String[] args) {
		System.out.println("Value of 13 right shift by 3 = " + (13 >> 3));
		System.out.println("Value of -13 right shift by 3 = " + (-13 >> 3));
	}
}

Output :
Value of 13 right shift by 3 = 1
Value of -13 right shift by 3 = -2

//Signed right shift example for positive number 13
number = 13
binary = 0000 1101
>> 3   = 0000 0001   (Decimal value is = 1)
final result = 1
//Signed right shift example for negative number -13
number           = -13
binary           = 0000 1101
1's complement   = 1111 0010
2's complement   =        +1
------------------------------
                 = 1111 0011
>> 3             = 1111 1110   (Left most bits are signed bits and this is decimal equivalent of -2)
------------------------------
          
final result = -2

Unsigned Right Shift Operator

This is represented by >>> symbol. It doesn’t consider sign bit and therefore after shifting all the bits towards right, it fills the spaces created on the left side with 0 bit.

example 1 :
a       = 0000 1010
a >>> 2 = --00 0010 (Since it is two positions right shifting there are two spaces created on the left side)
We have to fill spaces with 0 bit. So, the value of a will become
a       = 0000 0010

example 2 :
b       = 1101 0101
b >>> 3 = ---1 1010 (3 spaces are created on the left here since it is 3 positions right shifting)
b       = 0001 1010

Java code example :

package com.sks;

public class UnsignedRightShiftOperatorExample {

	public static void main(String[] args) {
		System.out.println("Value of 13 right shift by 3 = " + (13 >>> 3));
		System.out.println("Value of -13 right shift by 3 = " + (-13 >>> 3));
	}
}

Output :
Value of 13 right shift by 3 = 1
Value of -13 right shift by 3 = 536870910