- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
- Related Articles
- How to convert a negative image to positive image using Java OpenCV library?
- Java Program to Check Whether a Number is Positive or Negative
- How to convert positive value to negative while inserting in MySQL?
- How to convert a positive image to Negative to using OpenCV library?
- Distinguish positive and negative numbers.
- Schizophrenia Symptoms: Positive and Negative?
- Java program to find if the given number is positive or negative
- Java Menu Driven Program to Check Positive Negative or Odd Even Number
- How to convert a negative number to a positive one in JavaScript?
- Python program to count positive and negative numbers in a list
- Lambda expression in Python Program to rearrange positive and negative numbers
- Why negative multiplied by negative is positive?
- Sum a negative number (negative and positive digits) - JavaScript
- Convert negative denominator into positive:$\frac{5}{-3}$
- How to convert negative values in an R data frame to positive values?

Advertisements