Skip to main content

Signed and unsigned arithmetic operation using Java


    If you are familiar with any programming languages such as C, C++, PHP, Python, Java, etc., then you surely must have come across the concept of Operators.

Operator is the most essential and elementary concept related to the programming languages.

In a programming language an operator can be defined as a symbols that instructs the interpreter or compiler to perform some specific operations that could be mathematical, relational or logical. These operators are used to produce final result by performing the specific operation that they are assigned for.

Before, hopping into the actual topic for our discussion, let's take look at some important concepts related to operators and types of operators in Java.


Operands and Operators:

Consider a simple example for addition of two numbers,

Suppose 7 + 9, so here 7 and 9 are operands where as "+ " sign represents arithmetic operators, we will see that in detail later.

Typically, the operators in Java are grouped dependent on the quantity of operands:

·      A unary operator is the operator that has just a single operand, for instance unary plus (e.g., +13).

·      A binary operator is the operator that works on two operands, for instance addition and subtraction.

·      A ternary operator is the operator that works on three operands. Ternary operator is otherwise called conditional operator. This operator can be utilized to supplant specific kinds of if-then-else conditions. 

The operators in Java are also classified based on position:

·      Prefix: Unary operator that precedes its operand (e.g., -1).

·      Postfix: Unary operator that succeeds its operand (e.g., i++; increment the value of i by 1).

·      Infix: Binary or ternary operator between operand of operators (e.g., 5*2).


Types of operators in Java:

In this section, I will like to talk about different types of operators in Java

1.     Relational Operators

2.     Logical Operators

3.     Bitwise Operators

4.     Arithmetic Operators

Here, I would like to give an overview of the above mentioned operators and then we will directly jump into our actual topic.


Relational Operators:

Connection between two operands is really taken a look at utilizing relational operators.

The output thus found can be either true or false.

For example,

72 > 21

Here, “>” greater than is a relational operator while 72 and 21 are two operands. The greater than operator checks if operand 1 which is 72 is greater than operand 2 which is 21 or not. And in this case, 72 is greater than 21 so it will return a true value.

 

Operator

Description

> 

Greater than

< 

Less than

==

Is equal to

!=

Not equal to

>=

Greater than or equal to

<=

Less than or equal to

 

Logical Operators:

Logical operators are used for decision making and to check whether an expression or condition is true or false.

For example,

(8 > 2) && (5 > 2)

Here, (8 > 2) is condition1 and (5 > 2) is condition2 while “&&” is a logical AND operator.

As both condition1 (8 > 2) and condition2 (5 > 2) are true in the above example so true value is returned.

 

Operator

Description

Example

Meaning

&&

Logical AND

condition1 && condition2

True only if both condition1 and condition2 are true and false otherwise

||

Logical OR

condition1 || condition2

True if either condition1 or condition2 is true

!

Logical NOT

!condition

True if condition is false and vice versa

 

Bitwise Operators:

As the name recommends, to perform operations on individual bits, bitwise operators are utilized in Java.

B

 


For example,

Bitwise Complement Operation of 27

27 = 00011011 (Binary)

~ 00011011

       11100100 = 228 (Decimal)

In this example, Binary equivalent of 27 is considered and Bitwise complement operator represented as “~” is used. It converts the value of each bit (0 to 1 and 1 to 0).

 

Operator

Description

~

Bitwise complement

<< 

Left shift

>> 

Right shift

>>> 

Unsigned right shift

&

Bitwise AND

|

Bitwise exclusive OR

^

Bitwise exclusive XOR

 

Arithmetic Operators:

To perform basic arithmetic operations which we have mentioned in the table below, arithmetic operators are utilized.

For example:

13 + 7

Here, 13 and 7 are two operands whereas "+" operator is used to perform addition operation on the given operands. Similarly, Java has many other arithmetic operators which we will see in the later part.

 

Operator

Operation

+

Addition

_

Subtraction

*

Multiplication

/

Division

%

Modulo Operation

++

Increment

--

Decrement

 

For better comprehension about arithmetic operators lets think about a straightforward code model,

Source Code:

package arithmetic_operators;

import java.util.Scanner;

public class Operators {

      public static void main(String[] args)

    {

           Scanner sc = new Scanner(System.in);

           // initializing variables

           System.out.print("Enter First Number : ");

           int number1 = sc.nextInt();

           System.out.print("Enter Second Number : ");

           int number2 = sc.nextInt();

        int sum = 0, sub = 0, multi = 0, div = 0, mod = 0;

 

        // Displaying number1 and number2

        System.out.println("\nNumber 1 = " + number1);

        System.out.println("Number 2 = " + number2);

 

        // adding number1 and number2

        sum = number1 + number2;

        System.out.println("\nAddition = " + sum);

       

        // subtracting number1 and number2

        sub = number1 - number2;

        System.out.println("Subtraction = " + sub);

    // Multiplying number1 and number2

        multi = number1 * number2;

        System.out.println("Multiplication = " + multi);

       // Dividing number1 and number2

        div = number1 / number2;

        System.out.println("Division = "+ div);

       

        // Remaindering number1 and number2

        mod = number1 % number2;

        System.out.println("Remainder = " + mod);


Output:


Enter First Number : 60

Enter Second Number : 12

 

Number 1 = 60

Number 2 = 12

 

Addition = 72

Subtraction = 48

Multiplication = 720

Division = 5

Remainder = 0

So, in the above code example, we take two numbers from the user.

For instance, we considered 60 and 12 here to use all the arithmetic operators and we gain the desired output after performing operations.


Unsigned Numbers:

Unsigned binary numbers are positive numbers which don’t require any arithmetic symbol. For an n-bit unsigned integer all numbers are represented in the range 0 to 2n-1.

For example,

Range of 8-bit unsigned

Decimal

Hexadecimal

binary numbers

0 - 25510

00 – FF16

 

Range of 16-bit unsigned

Decimal

Hexadecimal

binary numbers

0 – 65,53510

0000 – FFFF16

 

Signed Numbers:

Signed numbers are the ones which are always associated with an arithmetic sign. The most significant bit (MSB) of binary number is utilized to address the sign bit. Assuming that the sign bit is equivalent to zero, the signed binary integer is positive in any other case, it is negative. Using the excess bits, the actual number is addressed. All numbers are represented in the range -2n-1 to +2n-1-1 for an n-bit signed binary number.

For example,

Binary number length

Range of signed binary numbers

4 bits

-8 to -1, 0 to +7

8 bits

-128 to -1, 0 to 127

16 bits

-32,768 to -1, 0 to  32,767

32 bits

-21,474,483,648 to -1, 0 to 21,474

 

Signed and unsigned arithmetic operation using Java

Since the rise of Java, all algebraic data types are signed. However, there arises a necessity to use unsigned values. 

For example, if we are counting the number of players in a game or an occurrence of an event, we could use an unsigned value because there will forever be at least 0 or more players and not a negative value.

JDK version 8 introduced the support for unsigned arithmetic. This support was given as the Unsigned Integer API.


Bit- Level Representations

To see how to deal with signed and unsigned arithmetic, let's consider their bit level representation.

In Java, encoding of numbers is performed using the two's complement system. Regardless of the type of operands, we can complete crucial arithmetic operations of adding two operands, subtracting and multiplying them with the assistance of this encoding. These operands can be signed or unsigned.

Let's consider a code example for better understanding. We'll utilize variables of the byte primitive data type. For other integral data types, such as int, short or long these operations are comparable.

Declare a variable m of byte data type with the value 102.

Binary representation of 102 is 0110_0110.

Now, in order to make twice of this value we need to perform the following operation,

byte m = 102;

byte n = (byte) (m<<1);

In the above code, the left shift operator moves all the bits in m variable to the left position, making its value twice as large technically.

Thus, 

Binary representation of variable n will then be 1100_1100.

So if we consider an unsigned arithmetic system, the value 1100_1100 represents a decimal number equivalent to 2^7 + 2^6 + 2^3 + 2^2, or 204.

As we already mentioned above while explaining signed numbers that the most significant bit works as the sign bit in signed arithmetic system.

Therefore, the result is obtained as -2^7 + 2^6 + 2^3 + 2^2, or -52.

We can check if the result is appropriate or not by executing following step,

assertEquals(-52,b2);

Signed and unsigned number's computation are same, difference occurs only if a binary representation is interpreted as a decimal number by JVM. 

The arithmetic operations such as addition, subtraction and multiplication can be performed with unsigned integers without requiring any progressions in JDK. But this is not quite possible with division and modulo operation as signed and unsigned numbers are handled differently.

For this reason, the Unsigned Integer API is required.


The Unsigned Integer API

Java 8 provided a support for unsigned arithmetic in the form of the Unsigned Integer API.

Java's absence of help for unsigned numbers frequently prompts a dreary interpretation process when translating Java from C language- based source code that utilizes unsigned numbers.

To ward off this limitation Unsigned Integer API was introduced in Java 8.


Division and Modulo

As we previously said that the Division and Modulo operation works differently on signed and unsigned integers so let's see how that actually happens.

All bits are processed as value bits by division and modulo operations on an unsigned number. When we perform Division and Modulo operation on signed and unsigned numbers, the quotients and remainders are different.

int positive = Integer.MAX_VALUE;

int negative = Integer.MIN_VALUE;

 

assertEquals(-1, negative / positive);

assertEquals(1, Integer.divideUnsigned(negative, positive));

 

assertEquals(-1, negative % positive);

assertEquals(1, Integer.remainderUnsigned(negative, positive));

 

Conclusion 

In order to perform any operations or calculations, operators are a vital part of Java. Java contributes various operators some of which we already mentioned above.

In arithmetic operators every one of the fundamental mathematical operations are executed. The arithmetic operations such as addition, subtraction and multiplication are performed utilizing two’s complement encoding framework in Java on both signed and unsigned integers.

 Division and modulo operations are performed diversely on signed and unsigned integers. For carrying out division and modulo operation on unsigned numbers, the unsigned integer API introduced in Java 8 is used.

But the support provided for unsigned arithmetic is not the most effectual one. It still comes with some limitations. For this reason, we should be cautious while using this new feature to avoid unexpected errors.


Thank You for reading ! πŸ˜‡


Authors:

Prathmesh Jadhav

Vaishnavi Jadhav

Jai Vardhan Singh Rathore

Anjali Kale

Comments

  1. Very informative.. Nice work πŸ‘

    ReplyDelete
  2. Very informative nice workπŸ‘

    ReplyDelete
  3. Well done guys.. Nice work... Very informative

    ReplyDelete
  4. Bilkul copied nahi hai, WELL DONEπŸ™‚πŸ™‚

    ReplyDelete
  5. Kishan ka dusra naam Ram hai, kiya tumne bohot accha kaam hai

    ReplyDelete
  6. Totally understood arithmetic operatiors, y'all are geniuses

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete

Post a Comment