Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign an operator symbol to a variable and use that variable for conditional check [duplicate]

Tags:

java

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?

like image 571
sri_sankl Avatar asked Jan 19 '13 07:01

sri_sankl


People also ask

How do you assign an operator to a variable?

The assignment ( = ) operator is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables.

Can you assign a variable in an if statement?

Yes, you can assign the value of variable inside if.

Can we declare a variable in if statement in Java?

Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available only from its declaration down to the end of the braces in which it is declared. This region of the program text where the variable is valid is called its scope .

What is the question mark operator in Java?

Conditional Expression Almost every operator has either one or two operands. This is the only operator in Java with three operands. This is called the conditional expression or the question mark-colon operator. The two expressions, exprtrue, exprfalse should evaluate to the same type.


1 Answers

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?

like image 166
LPD Avatar answered Sep 20 '22 13:09

LPD