Question

If I want to write a program that deals almost exclusively with, say, base 8 math, is there a way to change the source code or JVM to perform all calculations with this radix without having to explicitly change it on every integer reference?

For example, instead of...

private static final int RADIX = 8;

// ... then, elsewhere ...

System.out.println(Integer.toString(3 + 7, RADIX));

... I could just do ...

System.out.println(3 + 7);

... and have it print the same result of 12? Is there some environment variable or in-code setting I can apply? Or is this simply not possible?

This may seem arcane or a "why in the world would you want to do this" scenario, but if you can imagine having to perform a large number of non-trivial calculations under a different base, then you can see how it would become extremely tedious extremely fast to have to keep manually converting numbers to the appropriate radix.

Was it helpful?

Solution

No, there is no feature like that.

A number is a number no matter what base you're talking about, the radix only comes in when converting to/from strings. If you have to do this all of the time, then create some utility methods that do the work, and always call them. Alternatively, write your own Integer-like class that handles the fromString/toString bit.

public final class OctalInteger extends Number implements Comparable<OctalInteger> {
    // Basically a copy of Integer.java, but changes the methods dealing with Strings

}

OTHER TIPS

No.

Also, why would you want that? Imagine how many pieces of code you would break that run in the same JVM - no one coding libraries would expect the default radix to suddenly change.

Your use of a constant is the right way to go.

You can't change default radix. But you can easily write your own print and println procedures which would print integers in octal base.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top