7

Can I assign an operator symbol to a variable and use that variable for a conditional check?

char operator= '>';
int val1=10;
int val2=24;
if(val2 operator val1){

    /* some code*/

}

Why cant I use the operator variable inside conditions?

Blender
  • 289,723
  • 53
  • 439
  • 496
sri_sankl
  • 223
  • 4
  • 13

5 Answers5

1

Hey Thats not supported I think this will make sense to me.

The compiler reads in the operator when it builds your app. It has no way of knowing what the operator would be so it cant build correclty which I found in http://www.daniweb.com/software-development/csharp/threads/266385/c-using-operator-as-a-variable-in-calculations

They are talking in the context of C#, but I feel same thing makes sense here as well.

You cannot directly do that, but there are work arounds:

http://www.coderanch.com/t/568212/java/java/arithmetic-operations-operator-stored-variables

If thats really required, we have to use eval sort of thing in our code. I just tried this sample code.

package dumb;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class OperatorAsVariable
{
    public static void main( String args[] ) throws ScriptException
    {
        String test = "+";
        System.out.println( 1 + test + 2 );
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName( "js" );
        System.out.println( engine.eval( 1 + test + 2 ) );
    }

}

Courtesy : Is there an eval() function in Java?

Community
  • 1
  • 1
LPD
  • 2,833
  • 2
  • 29
  • 48
  • So you're dropping into Javascript to evaluate the expression.... – Jim Garrison Jan 19 '13 at 07:58
  • I just said it as a workaround which I also learnt just now while trying to find alternate ways. Never expected a negative vote for that. – LPD Jan 19 '13 at 07:59
0

Method arguments in Java must be expressions. And a operator is not an expression. This is not possible in Java.

a better way is pass objects(enums) that represents those operators

example:

public enum Operator{
    GREATHERTHAN(">") {
        @Override public double apply(double x1, double x2) {
            return x1 > x2;
        }
    },LEESTHAN{
        @Override public double apply(double x1, double x2) {
           return x1 < x2;
        }
    }
}
0

No, you can't do it that way in Java.

To define a binary relation dynamically you need to represent the relation as an object, with a two-argument method to do the check:

if (binaryRelation.areRelated(a,b))
{
    // Do something
}

Depending on your needs the standard Comparator interface may or may not be suitable.

starblue
  • 55,348
  • 14
  • 97
  • 151
-1

Take a look at the Comparator or Comparable interfaces and how they are used. Then define your own interface which takes two arguments and returns a boolean, and provide different implementations for them (this is OOP).

Another way would be to wait for Java 8 which will have lambda expressions.

-1

Code written in any programming language needs to be converted to Assembly Language. When this happens, every code statement written in High Level language gets translated to instruction / set of instructions in Middle Level equivalent i.e. JAVA code will get translated to Machine Specific instructions in Assembly Language.

Here addition operation in following statement,

int a = a + 10;

May get converted to

ADD A 1010;

And when we try to access a variables value, it may get converted to READ instruction.

So, when you try to use '>' in a variable,

char operator= '>';
int val1=10;
int val2=24;
if(val2 operator val1){

/* some code*/

}

The if statement,

if(val2 operator val1) 

will convert to an invalid instruction. Instead of generating an equivalent for comparison of two values, it will READ 'operator' variable.

This will obviously, lead to wrong interpretation.

Hence, doing such thing is not allowed.

Every compiler(java , gcc etc ) may behave differently but the target is same. If you read Complier / Compilation / Execution more, you will know more. These are some links:

http://www.coderanch.com/t/559258/java/java/java-codes-converted-assembly-JVM

Do programming language compilers first translate to assembly or directly to machine code?

Steps for Compilation of A C program.

http://www.herongyang.com/Computer-History/C-Program-Compilation-and-Execution-Process.html

Community
  • 1
  • 1
Learn More
  • 1,535
  • 4
  • 29
  • 51
  • Why voted down ? Let me know the reason or correct me if I am wrong. – Learn More Jan 19 '13 at 08:38
  • *"Any programming language"* is probably why. Languages with functions like `eval()` can just drop the operator into a string and execute the code. – Blender Jan 19 '13 at 08:45
  • [http://en.wikipedia.org/wiki/Eval](http://en.wikipedia.org/wiki/Eval) *Theory*: *_In theoretical computer science, a careful distinction is commonly made between eval and apply. Eval is understood to be the step of converting a quoted string into a callable function and its arguments, whereas apply is the actual call of the function with a given set of arguments._* So when Eval is called, there is again a set of translation is going on. – Learn More Jan 19 '13 at 08:58
  • how you can add "||" "==" ? –  Aug 13 '15 at 16:54