How do exponents work in Java calculations?

Could anyone explain why the following Java code:

System.out.println(100 * (1 - 10^(-10/10)));

prints “800” instead of the expected result of 90?

When I use a calculator, I get the correct value. How should I properly handle java exponents to get the right calculation?

Alright, the main issue here is how Java interprets 10^(-10/10). In Java, the ^ operator doesn’t mean exponentiation—it’s actually bitwise XOR! That’s why your expression doesn’t behave as expected.

To fix this, Java provides Math.pow(), which correctly computes exponents:

System.out.println(100 * (1 - Math.pow(10, (-10.0 / 10)))); This will give you the correct result because Math.pow(base, exponent) actually performs exponentiation. Always remember—^ is NOT power in Java!

Math.pow() is the way to go. But if you need higher precision (for example, when working with financial calculations), you should use BigDecimal instead. Floating-point arithmetic can introduce rounding errors, so for precise calculations, this is a better choice:

import java.math.BigDecimal;
import java.math.RoundingMode;

public class ExponentExample {
    public static void main(String[] args) {
        BigDecimal base = new BigDecimal("10");
        BigDecimal exponent = new BigDecimal("-1"); // -10/10 simplifies to -1
        BigDecimal result = BigDecimal.ONE.subtract(base.pow(exponent.intValue(), MathContext.DECIMAL128));

        BigDecimal finalResult = result.multiply(new BigDecimal("100"));
        System.out.println(finalResult);
    }
}

This approach avoids floating-point inaccuracies and ensures precise results. If your use case involves money or precise decimal values, BigDecimal is the way to go.

But let’s say you don’t want to use Math.pow() (e.g., for learning purposes or custom logic). You can implement your own exponentiation method using a simple loop:

public class Exponentiation {
    public static double customPow(double base, int exp) {
        double result = 1.0;
        boolean negativeExp = exp < 0;
        exp = Math.abs(exp);

        for (int i = 0; i < exp; i++) {
            result *= base;
        }

        return negativeExp ? 1.0 / result : result;
    }

    public static void main(String[] args) {
        double value = 100 * (1 - customPow(10, -1));
        System.out.println(value);
    }
}

This method manually computes the exponentiation, handling negative exponents properly. While Math.pow() is more efficient, implementing it yourself gives more control, especially if you want to optimize for specific cases.