How to convert a negative number to positive in Java

How to convert a negative number to positive  will learn in this article . We can will make a negative number positive using different methods as following .

 Convert a negative number to positive by multiply -1

Now we write a java program to make a negative number to positive by multiply -1 . In this java program we will take input from user as negative number then multiply by -1 it .

import java.util.Scanner;

public class NegToPos1 {
	public static void main(String[] args) {
		    int negtiveNumber;
	        int positiveNumber;

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

	        if (negtiveNumber < 0) {
	            positiveNumber = negtiveNumber * (-1);
	            System.out.println("Positive number: " + positiveNumber);
	        }else{
	        	System.out.println("Please Try with negtive number");
	        }
	}

}

Output :

Enter a negtive number: 
-80
Positive number: 80

Java program to convert a negative number  to positive By using Math.abs()

We can convert a negative int to positive by using Math.abs() method . Math.abs() method return the absolute value of the given argument.

import java.util.Scanner;

public class NegToPos2 {
	public static void main(String[] args) {
	    int negtiveNumber;
        int positiveNumber;

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

        if (negtiveNumber < 0) {
            positiveNumber = Math.abs(negtiveNumber );
            System.out.println("Positive number: " + positiveNumber);
        }else{
        	System.out.println("Please Try with negtive number");
        }
}
}

Output :

Enter a negtive number: 
-90
Positive number: 90

Convert a negative number to positive By using Bitwise Complement Operator

To convert negative int to positive  we will use the Bitwise Complement Operator in this java program .

import java.util.Scanner;

public class NegToPos3 {
	public static void main(String[] args) {
	    int negtiveNumber;
        int positiveNumber;

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

        if (negtiveNumber < 0) {
            positiveNumber = ~(negtiveNumber-1);
            System.out.println("Positive number: " + positiveNumber);
        }else{
        	System.out.println("Please Try with negtive number");
        }
}
}

Output:

Enter a negtive number: 
-90
Positive number: 90

In this tutorials we have seen different method to convert negative number to positive number . You can learn more java coding program for interview .

Leave a Reply

Your email address will not be published. Required fields are marked *

86 − = 81