Domanda

I thought long and Long class are more or less same thing. I saw this link

When I displayed Long.MAX_VALUE it displayed 9223372036854775807. But when I was doing multiplication of 1000000*1000000 which is 10^12 ; it gave overflow.

I was using long data type to store value...and while debugging it had value -727379968 after multiplication

Where am I making mistake or I am totally dumb?


Update: This was my code, and I got my mistake as specified in answer.
 
 for (;;)
    ppltn[i] = Integer.parseInt(tk.nextToken());

for (int i = 0; i < noc; i++) //sum is of long type sum = sum + min * ppltn[i]; //min and ppltn are of integer type
È stato utile?

Soluzione

The expression

1000000 * 1000000;

is integer multiplication as both operands are integers. Therefore you are limited by the max value of an integer.

You need to do long multiplication

1000000L * 1000000 /* L if you want it*/;

where at least one operand is a long and the other gets promoted to a long (if it isn't already).

Altri suggerimenti

In Java, ^ doesn't mean "power". It is a bitwise XOR operator.

therefore 10^6 means 10 XOR 6 instead 10 * 10 * 10 * 10 * 10 * 10


it is hard to guess without seeing your code.

However my guess is you are doing somehting like

long l = 1000000 * 10000000;

If so, here is the problem.

literal 1000000 is in fact an int instead of long, and therefore, 1000000 * 10000000 is doing a int multiplication and it got overflow (max of int is something around 2,xxx,xxx,xxx). The "overflowed" value is then cast to a long. Which give you the "strange" result.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top