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?
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.
Yes, you can assign the value of variable inside if.
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 .
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With