• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

Java - Variable = all negative ??

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.
I don't think there's a way to do this without first checking to see if the number itself is positive. (I'm not familiar w/ all of the Java standard libs, though.) If there is, it's probably some sort of bitwise trickery involving the two's complement representation of the number.

Instead, you'll need to do something like the following:
Code:
int var1 = 5;

int var2 = var1;                // var2 is now 5
if(var2 > 0) { var2 = -var2; }  // var2 is now -5

// or, using the ternary operator:
int var3 = (var1 > 0) ? -var1 : var1;   // var3 is now -5

That last example uses the ternary operator which can be a nice shorthand when you have a simple if/else and want to assign from it. It can also turn code into an unreadable mess if you aren't careful with it.
 
Last edited:
I'm not quite catching what you mean by "all negative numbers"? Do you mean the variable would have multiple values?
 
If you take the negative of the square root of the square of the variable it will always be negative, no matter if the original number is positve or not. This way you don't need to do a comparison either.

So x = -sqrt(x^2)

(not sure how this would be written in java, plus I am not sure on the entire situation)
 
I don't think there's a way to do this without first checking to see if the number itself is positive. (I'm not familiar w/ all of the Java standard libs, though.) If there is, it's probably some sort of bitwise trickery involving the two's complement representation of the number.
*Edit* I was way off about the two's complement notation. It's tricky to make it negative using that method.
 
Last edited:
If you take the negative of the square root of the square of the variable it will always be negative, no matter if the original number is positve or not. This way you don't need to do a comparison either.

So x = -sqrt(x^2)

(not sure how this would be written in java, plus I am not sure on the entire situation)

In Java this would be x = -Math.sqrt(Math.pow(x,2)).

However, I highly recommend against doing this as there will be issues with floating point accuracy since sqrt is an approximated computation. If you are only dealing with recommend using any technique where you do not move from the Integer domain to floating point, it isn't necessary and will cause issues. Many of the posts above will work.
 
Back