Main Tutorials

How to convert negative number to positive in Java

To convert negative number to positive number (this is called absolute value), uses Math.abs(). This Math.abs() method is work like this “number = (number < 0 ? -number : number);".

See a complete example :


package com.mkyong;

public class app{
	
	public static void main(String[] args) {
		
		int total = 1 + 1 + 1 + 1 + (-1);
		
		//output 3
		System.out.println("Total : " + total);
		
		int total2 = 1 + 1 + 1 + 1 + Math.abs(-1);
		
		//output 5
		System.out.println("Total 2 (absolute value) : " + total2);
		
	}
	
}

Output


Total : 3
Total 2 (absolute value) : 5

In this case, Math.abs(-1) will convert the negative number 1 to positive 1.

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
abhijit mondal
12 years ago

tell me a program of negative and positive

Tina Majumdar Mitra
10 months ago
Reply to  abhijit mondal

Class positive
{
void main (int n )
{
if (n>0)
System.out println (n+”is positive “);
else
System.out . println (n+”is negative “);
}
}

josh tranchant
2 years ago
Reply to  abhijit mondal

shut up bro

wellerion
4 years ago
Reply to  abhijit mondal

Literally just had to write a program to determine if Palindrome or not. 7 years later this was helpful.

great green
6 years ago
Reply to  abhijit mondal

time clock like for example calculating employees hours in and out with minutes included and seconds, it should create a negative number, so Math.abs is a really good tool, because it can actually convert the – sign to and absolute value number, plus it saves the programmer time and work.