Calling Mathematica from Java

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());

try {
// Get rid of the initial InputNamePacket the kernel will send
// when it is launched.


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


That code is the 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. shows several different ways to send expressions to Mathematica and read the results.