- 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
Advertisements