• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Easy question regarding long data types...

 
Nick Garcia
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Java Ranch,

So, I think this would typically be an easy problem to solve. I can't seem to figure out what I'm doing wrong, though. An easier way to show how I feel is with this emoticon:

I am practicing with some loops. All of them work except for the last one. My main goal is to output the values of the square-root of 2 (might be wording this wrong, but basically I want: 1, 2, 4, 8, 16, 32, 64, etc) until the value can no longer fit inside of a long data type. I recall hearing the maximum value of a long is 9223372036854775808, but for some reason compiling in cmd (as well as in eclipse and TextPad) tells me it's out of range. Oddly enough, it says it's out of range for an int, even though I'm trying to declare it as a long.

Am I declaring this incorrectly? Am I just completely insane and currently living in an alternate error-filled compiling universe?

Any help would be appreciated!



And most of all, thank you for your time!!
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are two problems with what you are doing.

First you are doing this:
long loopControl4 = 1, comparison = 9223372036854775808;
The number constant to the right of the equal sign is an integer, by default, which is why you get the compilation error saying the value doesn't fit into an integer. You have to qualify the constant with an 'L' at the end so Java knows you want a long constant instead of an integer constant:
long loopControl4 = 1, comparison = 9223372036854775808L;
Then, you still get an error saying that 9223372036854775808L is too large to fit into a long, because it is. The largest positive value for long is 9223372036854775807L, you were off by 1.
 
Tony Docherty
Bartender
Posts: 2988
59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want the largest long value, rather than hard coding a value use the constant Long.MAX_VALUE. It avoids potential typographical errors.
 
Nick Garcia
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brilliant. Thank you both for your help!! My program now works just fine. =) Thanks a ton!

-Nick
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic