"Java" (External Evaluation System)

Details

  • Java Version 9.0 and higher is supported.
  • Java is a popular general-purpose programming language.
  • Java does not require configuration to use with ExternalEvaluate.

ExternalEvaluate Usage

  • ExternalEvaluate["Java",code] executes the code string in a Java REPL and returns the results as a Wolfram Language expression.

Data Types

  • The following Java built-in types are supported, exactly as they are in J/Link:
  • byte, char, short, longIntegerinteger
    float, doubleRealreal-valued number
    booleanTrue|FalseBoolean values
    StringStringsequence of character values
    ArrayListarray of vaules
    BigDecimalRealarbitrary-precision real number
    BigIntegerIntegerarbitrary-sized integer
    nullNullnull value
    objectJavaObjectarbitrary Java objects
    Exprexpressionarbitrary Wolfram Language expressions

Usage Notes

Examples

open allclose all

Basic Examples  (5)

Evaluate 2+2 in Java and return the result:

Call a Java method:

Arrays are returned as lists:

Objects that have no natural representation are returned as JavaObject expressions, just as in J/Link:

Type > and select Java from the drop-down menu to get a code cell that uses ExternalEvaluate to evaluate:

java.util.Arrays.stream(new int[]{1,2,3}).map(num -> num*num).toArray()

Scope  (2)

You can define a Java method without wrapping it in a full class definition. Note that such method definitions are always public and static so you can drop the "public static" prefix:

String removeVowels(String s) { return s.replaceAll("[aeiou]", ""); }

Method definitions return an ExternalFunction object that you can call:

Define an entire class:

public class Node { private String data; private Node next; public Node(String data) { this.data = data; next = null; } public String getData() { return data; } public void setData(String data) { this.data = data; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } }

Class definitions return J/Link JavaClass expressions that you can use directly in J/Link:

You can also call your new class directly from ExternalEvaluate:

new Node("foo")