MATLAB Answers

Tobias Elmøe

Cannot call java class from Matlab

Asked by Tobias Elmøe
on 2 May 2012

Hi all. I have a peculiar problem. I am trying to use a java class in Matlab. I have made a very simple java Hello World example:

public class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.

After compiling (using jdk1.7.0_04 - the 64 bit version), I use the javaaddpath to direct Matlab to the custom class folder, in my case 'c:\temp\javaclass\' so I write:


I then try to create an object

Hello = HelloWorldApp()  

but I get the error

Undefined function or variable 'HelloWorldApp'.

I have spent hours now trying to figure it out, I've read the tutorial sevaral times, I have tried looking for answers at Mathworks Answers, but nothing has helped so far. Can anyone point out the reason for my failure?




1 Answer

Answer by Oleg Komarov
on 2 May 2012

I tried your example but I added the path manually to $matlabroot\toolbox\local\classpath.txt (on a new line simply add):


Then start MATLAB and check the path with javaclasspath.

Finally call HelloWorldApp

Warning: A Java exception occurred trying to load the HelloWorldApp class:
Java exception occurred:
java.lang.UnsupportedClassVersionError: HelloWorldApp : Unsupported major.minor
version 51.0
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClass(Unknown Source)
	at Source)
	at Source)
	at$000(Unknown Source)
	at$ Source)
	at Method)
	at Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClassInternal(Unknown Source)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Unknown Source)


Problem solved: it was a wrong version of the jdk (1.7.0_04). After installing version 1.6.0_31 and compiling again, I was able to add the java object, after adding invoking the javaaddpath command first.

Hurray for totally obscurred (non)error messages. That cost me 3 hours of frustration.

This technical note shows how to use the latest java version:

Indeed, MATLAB uses a 1.6.x version of Java, so you need to use some 1.6.x as well (as you did 1.6.0_31).

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!