Java Program to convert positive int to negative and negative to positive


To convert positive int to negative and vice-versa, use the Bitwise Complement Operator.

Let us first initialize a positive int −

int positiveVal = 200;

Now, let us convert it to negative −

int negativeVal = (~(positiveVal - 1));

Now, let’s say we have the following negative int −

int negativeVal = -300;

The following will convert the negative to positive int −

positiveVal = ~(negativeVal - 1);

Example

 Live Demo

public class Demo {
   public static void main(String[] args) throws java.lang.Exception {
      int positiveVal = 100;
      int negativeVal = (~(positiveVal - 1));
      System.out.println("Result: Positive value converted to Negative = "+negativeVal);
      positiveVal = ~(negativeVal - 1);
      System.out.println("Actual Positive Value = "+positiveVal);
      negativeVal = -200;
      System.out.println("Actual Negative Value = "+negativeVal);
      positiveVal = ~(negativeVal - 1);
      System.out.println("Result: Negative value converted to Positive = "+positiveVal);
   }
}

Output

Result: Positive value converted to Negative = -100
Actual Positive Value = 100
Actual Negative Value = -200
Result: Negative value converted to Positive = 200

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements