How do I call a simple "Hello World" Java program in MATLAB?

15 views (last 30 days)
I have a simple Java program, and I would like to know how to call it in MATLAB.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 2 Sep 2022
Edited: MathWorks Support Team on 20 Oct 2022
Here is an example. This assumes you already have knowledge of Java.
The following is a Java program:
public class HelloWorld {
public static void main( String args[] )
{
System.out.println( "Hello World!" );
}
}
To call this program in MATLAB:
0. Make sure you have the version of JRE/JDK on your system that is supported with your version of MATLAB. You can get this version by executing this on the MATLAB command prompt:
>> version -java
1. Outside of MATLAB: use Java to compile this class, so you have file HelloWorld.class
2. Locate the classpath.txt file for the MATLAB installation. The location of this file can be found by typing the following command in MATLAB command window:
which classpath.txt
3. Open the 'classpath.txt' with a text editor as Administrator. Add the full path for the directory with the HelloWorld.class to the end of the 'classpath.txt' file as a single line and save the file.
4. Restart MATLAB.
5. In MATLAB: to create an object of class HelloWorld, type:
o = HelloWorld
6. In MATLAB: to execute main() of object o, type:
javaMethod('main', o, '')
Alternately one may also add the directory in which the class files are to the dynamic path. Use the JAVAADDPATH command to add the directory (which contains the HelloWorld.class file) to JAVA's dynamic classpath. This also obviates the need to restart MATLAB. Once this is done the code can be invoked as follows:
o = HelloWorld;
javaMethod('main', o);
For more information on calling Java class from MATLAB, see chapter 3 of the "External Interfaces" documentation. This documentation can be accessed from the following URL:

More Answers (0)

Categories

Find more on Java Package Integration in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!