I’m trying to write a Java program that uses Mathematica code, but when I compile it, a window appears asking for MathLink. I enter

c:\\program files\\wolfram research\\mathematica\\9.0\\mathkernel.exe

but this causes an exception to occur. I don’t understand what the problem is. Here is the code I am using:

import com.wolfram.jlink.*;

public class SampleProgram {

public static void main(String[] argv) {

KernelLink ml = null;

try {

ml = MathLinkFactory.createKernelLink(argv);

} catch (MathLinkException e) {

System.out.println(“Fatal error opening link: ” + e.getMessage());

return;

}

try {

// Get rid of the initial InputNamePacket the kernel will send

// when it is launched.

ml.discardAnswer();

ml.evaluate(“<

// step–no need to call waitForAnswer.

String strResult = ml.evaluateToOutputForm(“4+4”, 0);

System.out.println(“4 + 4 = ” + strResult);

} catch (MathLinkException e) {

System.out.println(“MathLinkException occurred: ” + e.getMessage());

} finally {

ml.close();

}

}

}

My objective is to use Mathematica in java to calculate the maximum of a function. I don’t know how to do that, and the documentation on the net is few.

=================

=================

1 Answer

1

=================

That code is the SampleProgram.java example from J/Link. At the top of that very file, there is a long comment that explains exactly how to launch it. Also in the ReadMe.html file that sits right next to it. To wit:

java -cp .;..\..\JLink.jar SampleProgram -linkmode launch -linkname “c:/program files/wolfram research/mathematica/9.0/mathkernel.exe”

That dialog box you are seeing is not asking for the path to the Mathematica kernel, but rather a name of a “listening” MathLink, which is for a type of connection when you are not directly launching Mathematica from your Java program.

As for using Mathematica to maximize a function, first make sure you know how to do it in a standard Mathematica session. Once you know exactly what you need to enter in Mathematica to perform your computation, send the exact same expression from Java. SampleProgram.java shows several different ways to send expressions to Mathematica and read the results.