0

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.

user2342558
  • 5,567
  • 5
  • 33
  • 54
Everaldo
  • 57
  • 8
  • Java doesn't support operator overloading. Have a look for more information here https://stackoverflow.com/questions/2865526/which-programming-languages-other-than-c-support-operator-overloading – user1717259 Oct 24 '19 at 15:53

2 Answers2

1

In Java you can't override operators like in C++. You can override only methods.

DzianisH
  • 77
  • 2
1

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);
user2342558
  • 5,567
  • 5
  • 33
  • 54