Search code examples
javastringexpressionnashorn

Difference between return String from a method and string variable


I have this below piece of code,

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

public class Test {

    public static void main(String[] args) throws Exception {
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");
        Test ctrl = new Test();
        String[] arr = {"1==1"};
        String eer = "1==1";
        engine.put("hi", ctrl);
        System.out.println(engine.eval(arr[0])); //true
        System.out.println(engine.eval(eer)); //true
        System.out.println(engine.eval("hi.values()")); //prints 1==1
    }

    public String values() {
        return "1==1";
    }
}

I can understand the last sout statement is enclosed in double quotes hence it prints the value as it is.

How can i make the statement to evaluate the expression as like other string variables?

EDIT

In java if i add ,

String result = ctrl.values(); //returns 1==1
System.out.println(engine.eval(result));//true

I tried same on javascript

var result = myfun();
function myfun(){
return "1!=1";
}

if(result){
window.alert("yes"); // This came even when condition is false
}

Solution

  • How can i make the statement to evaluate the expression as like other string variables?

    Why not engine.eval() twice?

    System.out.println(engine.eval(engine.eval("hi.values()")));
    

    In java if i add , [some code that does something] I tried same on javascript [some identical-looking code that does a different thing]

    There's no implicit call to eval in JavaScript. This means that result holds the non-empty string 1!=1, which becomes true in an if-statement.