The other mathematical shorthand operators which Java provides are the += (a = a + number), *=, and so on.
The complete list of operators can be obtained from here.
Answer from npinti on Stack Overflowoperators - Java math operations shorthand? - Stack Overflow
Is it possible to pass arithmetic operators to a method in java? - Stack Overflow
Using math operator + in system.out.println
What are Unary, Binary, and Ternary operators in Java?
Videos
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));
Method arguments in Java must be expressions. An operator by itself is not an expression. This is not possible in Java.
You can, of course, pass objects (maybe enum constants) that represents those operators, and act accordingly, but you can't pass the operators themselves as parameters.
Additional tips
Since you're just starting Java, it's best to ingrain these informations early on to ease your future development.
- Method names starts with lowercase:
calculateinstead ofCalculate - Variable names starts with lowercase:
operatorinstead ofOperator Doubleis a reference type, the box for primitive typedouble.- Effective Java 2nd Edition, Item 49: Prefer primitive types to boxed primitives
- Don't
return "error...". Instead,throw new IllegalArgumentException("Invalid operator");
See also
- Java Language Guide/Autoboxing
- Java Lessons/Exceptions
- Coding Conventions/Naming
- Unfortunate typo in this document: How is this statement making sense? (Sun’s naming convention for Java variables)
Following calculates correctly:
System.out.println(2+2); //4
The following will calculate correctly too:
System.out.println("The result is " + 2*2 ); //The result is 4But then why would this not calculate?
System.out.println("The result is " + 2+2 ); //The result is 22How can I calculate 2+2 directly and display along with the string to get the output The result is 4?