# Thread: Java - Variable = all negative ??

1. ## Java - Variable = all negative ??

is there a simple asignment statement to make a variable all negative numbers

2. 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.

3. I'm not quite catching what you mean by "all negative numbers"? Do you mean the variable would have multiple values?

4. 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)

5. 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.

6. abs(variable) * -1;

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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•