Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass arithmetic operators to a method in java?

Right now I'm going to have to write a method that looks like this:

public String Calculate(String operator, double operand1, double operand2) {          if (operator.equals("+"))         {             return String.valueOf(operand1 + operand2);         }         else if (operator.equals("-"))         {             return String.valueOf(operand1 - operand2);         }         else if (operator.equals("*"))         {             return String.valueOf(operand1 * operand2);         }         else         {             return "error...";         } } 

It would be nice if I could write the code more like this:

public String Calculate(String Operator, Double Operand1, Double Operand2) {        return String.valueOf(Operand1 Operator Operand2); } 

So Operator would replace the Arithmetic Operators (+, -, *, /...)

Does anyone know if something like this is possible in java?

like image 583
James T Avatar asked May 25 '10 06:05

James T


People also ask

Which can be operands of arithmetic operators in Java?

The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean types, but you can use them on char types, since the char type in Java is, essentially, a subset of int. In Java, you need to be aware of the type of the result of a binary (two-argument) arithmetic operator.

Is operator a method in Java?

Java does not support Operator Overloading. The only option you have is define methods like add() , subtract() , multiply() , etc, and write the logic there, and invoke them for particular operation. You can have a look at BigInteger class to get an idea of how you can define methods to support various operations.


Video Answer


1 Answers

No, you can't do that in Java. The compiler needs to know what your operator is doing. What you could do instead is an enum:

public enum Operator {     ADDITION("+") {         @Override public double apply(double x1, double x2) {             return x1 + x2;         }     },     SUBTRACTION("-") {         @Override public double apply(double x1, double x2) {             return x1 - x2;         }     };     // You'd include other operators too...      private final String text;      private Operator(String text) {         this.text = text;     }      // Yes, enums *can* have abstract methods. This code compiles...     public abstract double apply(double x1, double x2);      @Override public String toString() {         return text;     } } 

You can then write a method like this:

public String calculate(Operator op, double x1, double x2) {     return String.valueOf(op.apply(x1, x2)); } 

And call it like this:

String foo = calculate(Operator.ADDITION, 3.5, 2); // Or just String bar = String.valueOf(Operator.ADDITION.apply(3.5, 2)); 
like image 110
Jon Skeet Avatar answered Sep 21 '22 23:09

Jon Skeet