How to convert a negative number to positive in Java

Java program to convert a negative number to positive:

In this post, we will learn how to convert a negative number to positive in Java. We can solve this in two different ways. The easiest way is to multiply the number with -1. Also, we can use Math.abs method to find the absolute value, which also changes the negative value to positive.

In this post, we will write one Java program that will take one negative number as input from the user and print out its positive value.

Method 1: Multiply by -1:

In this method, we are multiplying the number by -1. It will give the positive number. But, first we will have to check if the number is positive or not.

Below is the complete program:

package com.company;

import java.util.Scanner;

public class Example {

    public static void main(String[] args) {
        int givenNumber;
        int positiveNumber;

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number: ");

        givenNumber = sc.nextInt();

        if (givenNumber < 0) {
            positiveNumber = givenNumber * (-1);
            System.out.println("Positive number: " + positiveNumber);
        }
    }
}

It will give output as like below:

Enter a number: 
-23
Positive number: 23

Method 2: By using Math.abs():

abs is a static method defined in the Math class of Java. We can use this method to convert a negative number to positive. This method can be used as like below:

package com.company;

import java.util.Scanner;

public class Example {

    public static void main(String[] args) {
        int givenNumber;
        int positiveNumber;

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number: ");

        givenNumber = sc.nextInt();

        if (givenNumber < 0) {
            positiveNumber = Math.abs(givenNumber);
            System.out.println("Positive number: " + positiveNumber);
        }
    }
}

It will give similar output.

java negative to positive math abs()

You might also like: