Reputation: 65
There are 2 variables and I need to sum them. But instead using the + sign I'd like to change it for a String.
double var1 = 1;
double var2 = 2;
String sign = "+";
double variable3 = var1 sign var2;
I'd like to sum them using the "sign" instead, But i don't know if there's a way to do this.
Upvotes: 0
Views: 39
Reputation: 6693
Java doesn't allow "Operator overloading", see this SO post for some info.
But, you can use a method to handle the sign
like this:
double handleOperation(String sign, double int1, double int2)
{
if(sign.equals("+")) {
return int1 + int2;
}
else if(sign.equals("-")) {
return int1 - int2;
}
// others
return 0;
}
double var1 = 1;
double var2 = 2;
String sign = "+";
double variable3 = handleOperation(sign, var1, var2);
Upvotes: 1
Reputation: 95
In Java you can't override operators like in C++. You can override only methods.
Upvotes: 1