How to Convert Negative Number to Positive in Java


In this example, we will learn how to convert a set of negative numbers into positive numbers.

Source Code

package com.beginner.examples;

import java.util.Arrays;

public class ConvertNegativeNumToPositive {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] nums = {-2, -3, -4, -5, -6};
        System.out.println("Array: " + Arrays.toString(nums));
        System.out.println("After the transformation:" + Arrays.toString(toPositive(nums)));



    }
    static int[] toPositive(int[] nums) {
        int[] positiveNum = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            positiveNum[i] = Math.abs(nums[i]);

        }
        return positiveNum;
    }

}

Output:

Array: [-2, -3, -4, -5, -6]
After the transformation:[2, 3, 4, 5, 6]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments