Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Björn Norén
Björn Norén
9,569 Points

Why this result?

Hi! when I multiply these two numbers:

  • a) 300 * 1000 * 1000 * 1000
  • b) 300.0 * 1000 * 1000 * 1000 ... I get the results:
  • a) -647710720
  • b) 3.0E11

Could someone explain WHY I get these results, and what datatype they are? Are both a) & b) defualted to a double? Is a) equal to 300000000000 in anyway or is it just a random number, and if so why -647710720?

  • Please note that I know I should use "long" when printing it, I just want to understand the results. I do not wonder WHAT I should do, I wonder WHY the results are what they are.
  • I apologise for asking the same question again because I have written this in the forum before, but I didn't get my question answered when I emphasized what I really wondered. I use cmd.exe

Here's the code:

public class Test
{
    public static void main (String[] args)
    {   
        System.out.println(300 * 1000 * 1000 * 1000);
        System.out.println(300.0 * 1000 * 1000 * 1000);
    }
}

Thanks dear community!

2 Answers

Antonio Rodrigues
Antonio Rodrigues
2,306 Points

I belive that its because of the way java handles overflow of integer type. That is, the types have a maximum and mininum values, depending on the amout of bits they use to store the values. An integer uses 32. What happens when you try to assing a number that uses more than that?

Your first command is multiplying integer values and the operation returns an integer that's bigger than the maximum integer value. It then goes back to the minimum value an integer can handle and up.

When you change it to 300.0, it reads that as an double operation and returns a double, where the result fits, and you get the real number (converted to notation using the Euler constant, because it's so big).

Anvar Zeynalzade
Anvar Zeynalzade
3,569 Points

In the first line, you have printed, the type of numbers defaulted to an int. And int datatype in Java can range from -2 147 483 648 to 2 147 483 647. As the result of multiplied numbers exceeds 2 147 483 647 the out had been converted to -647 710 720. In Java when the value of int overfills valid range it counts from the very beginning of the range. So 300 000 000 000 divided by 2 147 483 648 leaves a remainder of -647710720.