Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code print two negative numbers? [duplicate]

Tags:

java

int a = Integer.MIN_VALUE;
int b = -a;
System.out.println("a = "+a + " | b = "+b);

Result :

a = -2147483648 | b = -2147483648

I was expecting b to be a positive number.

like image 296
aviad Avatar asked May 15 '17 16:05

aviad


People also ask

Can you have a negative double in Java?

One of the tricky parts of this question is that Java has multiple data types to support numbers like byte, short, char, int, long, float, and double, out of those all are signed except char, which can not represent negative numbers.

Can double take negative values?

On all machines, variables of the float, double, and long double data types can store positive or negative numbers.

How do you store negative numbers in an array?

Method 1 (Simple : O(n2)): The idea is to use two nested loop. For each element arr[i], find negative of arr[i] from index i + 1 to n – 1 and store it in another array. For output, print negative positive value of the stored element.

Can Java int have negative values?

A number of the "int" type in Java can range from -2,147,483,648 up to 2,147,483,647.


1 Answers

Changing the sign of Integer.MIN_VALUE produces an overflow; you're seeing the result of that.

like image 50
Andres Avatar answered Oct 07 '22 05:10

Andres