If you want to treat something like 1/3
directly as Java code, this will always be evaluated one way or another in Java and treated like one of the primitive numerical types (e.g. double
, depending on which types you use).
If you wanted to keep 1/3
as a fraction, you would need to have a library to model it as a fraction. Essentially, you're looking at a tool capable of doing symbolic maths in Java. You might not need a very powerful one (e.g. you might not need something capable of differentiation), but it will at least need to be able to represent fractions, and presumably do some basic operations and simplifications with them (I guess that's what you're after).
Apache Commons Maths (Fractions section) should be of interest. You might also be interested in some of the libraries referenced in this question: https://stackoverflow.com/q/2574949/372643
Unfortunately, Java doesn't allow for operator overloading, so writing mathematical code in Java can be quite tedious. In general, you'll have to input your mathematical expressions as text and expect the library to model the expression with its own classes more or less transparently, or you'll have to use methods on objects like add
, mult
, ...
If you have a lot of math to do in a Java environment, it might be worth investigating what other languages that run on the JVM have to offer, such as Jython or Scala.