Java Interface
**************

The Java Interface is designed for calling Java functions from within Octave. If you want to do the reverse, and call Octave from within Java, try a library like javaOctave (http://kenai.com/projects/javaOctave) or joPas (http://jopas.sourceforge.net).

Java Interface Functions
========================

The following functions are the core of the Java Interface.  They provide a way to create a Java object, get and set its data fields, and call Java methods which return results to Octave.

 -- Built-in Function: JOBJ = javaObject (CLASSNAME)
 -- Built-in Function: JOBJ = javaObject (CLASSNAME, ARG1, ...)
     Create a Java object of class CLASSSNAME, by calling the class constructor with the arguments ARG1, ...

     The first example below creates an uninitialized object, while the second example supplies an initial argument to the constructor.

          x = javaObject ("java.lang.StringBuffer")
          x = javaObject ("java.lang.StringBuffer", "Initial string")

     javaMethod, javaArray

 -- Function File: JARY = javaArray (CLASSNAME, SZ)
 -- Function File: JARY = javaArray (CLASSNAME, M, N, ...)

     Create a Java array of size SZ with elements of class CLASSNAME.

     CLASSNAME may be a Java object representing a class or a string containing the fully qualified class name.  The size of the object may also be specified with individual integer arguments M, N, etc.

     The generated array is uninitialized.  All elements are set to null if CLASSNAME is a reference type, or to a default value (usually 0) if CLASSNAME is a primitive type.

     Sample code:

          jary = javaArray ("java.lang.String", 2, 2);
          jary(1,1) = "Hello";

     javaObject

There are many different variable types in Octave but only ones created through javaObject can use Java functions.  Before using Java with an unknown object the type can be checked with isjava.

 -- Built-in Function: isjava (X)
     Return true if X is a Java object. class, typeinfo, isa, javaObject

Once an object has been created it is natural to find out what fields the object has and to read (get) and write (set) them.

In Octave the fieldnames function for structures has been overloaded to return the fields of a Java object.  For example:

     dobj = javaObject ("java.lang.Double", pi);
     fieldnames (dobj)
     =>
     {
       [1,1] = public static final double java.lang.Double.POSITIVE_INFINITY
       [1,2] = public static final double java.lang.Double.NEGATIVE_INFINITY
       [1,3] = public static final double java.lang.Double.NaN
       [1,4] = public static final double java.lang.Double.MAX_VALUE
       [1,5] = public static final double java.lang.Double.MIN_NORMAL
       [1,6] = public static final double java.lang.Double.MIN_VALUE
       [1,7] = public static final int java.lang.Double.MAX_EXPONENT
       [1,8] = public static final int java.lang.Double.MIN_EXPONENT
       [1,9] = public static final int java.lang.Double.SIZE
       [1,10] = public static final java.lang.Class java.lang.Double.TYPE
     }

The analogy of objects with structures is carried over into reading and writing object fields.  To read a field the object is indexed with the . operator from structures.  This is the preferred method for reading fields, but Octave also provides a function interface to read fields with java_get.  An example of both styles is shown below.

     dobj = javaObject ("java.lang.Double", pi);
     dobj.MAX_VALUE
     =>  1.7977e+308
     java_get ("java.lang.Float", "MAX_VALUE")
     =>  3.4028e+38

 -- Function File: VAL = java_get (OBJ, NAME)
     Get the value of the field NAME of the Java object OBJ.

     For static fields, OBJ can be a string representing the fully qualified name of the corresponding class.

     When OBJ is a regular Java object, structure-like indexing can be used as a shortcut syntax.  For instance, the following two statements are equivalent

            java_get (x, "field1")
            x.field1

     java_set, javaMethod, javaObject

 -- Function File: OBJ = java_set (OBJ, NAME, VAL)
     Set the value of the field NAME of the Java object OBJ to VAL.

     For static fields, OBJ can be a string representing the fully qualified named of the corresponding Java class.

     When OBJ is a regular Java object, structure-like indexing can be used as a shortcut syntax.  For instance, the following two statements are equivalent

            java_set (x, "field1", val)
            x.field1 = val

     java_get, javaMethod, javaObject

To see what functions can be called with an object use methods. For example, using the previously created DOBJ:

     methods (dobj)
     =>
     Methods for class java.lang.Double:
     boolean equals(java.lang.Object)
     java.lang.String toString(double)
     java.lang.String toString()
     ...

To call a method of an object the same structure indexing operator . is used.  Octave also provides a functional interface to calling the methods of an object through javaMethod.  An example showing both styles is shown below.

     dobj = javaObject ("java.lang.Double", pi);
     dobj.equals (3)
     =>  0
     javaMethod ("equals", dobj, pi)
     =>  1

 -- Built-in Function: RET = javaMethod (METHODNAME, OBJ)
 -- Built-in Function: RET = javaMethod (METHODNAME, OBJ, ARG1, ...)
     Invoke the method METHODNAME on the Java object OBJ with the arguments ARG1, ....

     For static methods, OBJ can be a string representing the fully qualified name of the corresponding class.

     When OBJ is a regular Java object, structure-like indexing can be used as a shortcut syntax.  For instance, the two following statements are equivalent

            ret = javaMethod ("method1", x, 1.0, "a string")
            ret = x.method1 (1.0, "a string")

     javaMethod returns the result of the method invocation.

     methods, javaObject

The following three functions are used to display and modify the class path used by the Java Virtual Machine.  This is entirely separate from Octave's PATH variable and is used by the JVM to find the correct code to execute.

 -- Function File: javaclasspath ()
 -- Function File: DPATH = javaclasspath ()
 -- Function File: [DPATH, SPATH] = javaclasspath ()
 -- Function File: CLSPATH = javaclasspath (WHAT)
     Return the class path of the Java virtual machine in the form of a cell array of strings.

     If called with no inputs:

       * If no output is requested, the dynamic and static classpaths are printed to the standard output.

       * If one output value DPATH is requested, the result is the dynamic classpath.

       * If two output valuesDPATH and SPATH are requested, the first variable will contain the dynamic classpath and the second will contain the static classpath.

     If called with a single input parameter WHAT:

     "-dynamic"
          Return the dynamic classpath.

     "-static"
          Return the static classpath.

     "-all"
          Return both the static and dynamic classpath in a single cellstr.

     javaaddpath, javarmpath

 -- Function File: javaaddpath (CLSPATH)
 -- Function File: javaaddpath (CLSPATH1, ...)
     Add CLSPATH to the dynamic class path of the Java virtual machine.

     CLSPATH may either be a directory where .class files are found, or a .jar file containing Java classes.  Multiple paths may be added at once by specifying additional arguments. javarmpath, javaclasspath

 -- Function File: javarmpath (CLSPATH)
 -- Function File: javarmpath (CLSPATH1, ...)
     Remove CLSPATH from the dynamic class path of the Java virtual machine.

     CLSPATH may either be a directory where .class files are found, or a .jar file containing Java classes.  Multiple paths may be removed at once by specifying additional arguments. javaaddpath, javaclasspath

The following functions provide information and control over the interface between Octave and the Java Virtual Machine.

 -- Function File: javachk (FEATURE)
 -- Function File: javachk (FEATURE, COMPONENT)
 -- Function File: MSG = javachk (...)
     Check for the presence of the Java FEATURE in the current session and print or return an error message if it is not.

     Possible features are:

     "awt"
          Abstract Window Toolkit for GUIs.

     "desktop"
          Interactive desktop is running.

     "jvm"
          Java Virtual Machine.

     "swing"
          Swing components for lightweight GUIs.

     If FEATURE is supported and

       * no output argument is requested:

          Return an empty string

       * an output argument is requested:

          Return a struct with fields "feature" and "identifier" both empty

     If FEATURE is not supported and

       * no output argument is requested:

          Emit an error message

       * an output argument is requested:

          Return a struct with field "feature" set to FEATURE and field "identifier" set to COMPONENT

     The optional input COMPONENT will be used in place of FEATURE in any error messages for greater specificity.

     javachk determines if specific Java features are available in an Octave session.  This function is provided for scripts which may alter their behavior based on the availability of Java.  The feature "desktop" is never available as Octave has no Java-based desktop. Other features may be available if Octave was compiled with the Java Interface and Java is installed.

     usejava, error

 -- Function File: usejava (FEATURE)
     Return true if the Java element FEATURE is available.

     Possible features are:

     "awt"
          Abstract Window Toolkit for GUIs.

     "desktop"
          Interactive desktop is running.

     "jvm"
          Java Virtual Machine.

     "swing"
          Swing components for lightweight GUIs.

     usejava determines if specific Java features are available in an Octave session.  This function is provided for scripts which may alter their behavior based on the availability of Java.  The feature "desktop" always returns false as Octave has no Java-based desktop.  Other features may be available if Octave was compiled with the Java Interface and Java is installed. javachk

 -- Function File: javamem ()
 -- Function File: JMEM = javamem ()
     Show the current memory usage of the Java virtual machine (JVM) and run the garbage collector.

     When no return argument is given the info is printed to the screen. Otherwise, the output cell array JMEM contains Maximum, Total, and Free memory (in bytes).

     All Java-based routines are run in the JVM's shared memory pool, a dedicated and separate part of memory claimed by the JVM from your computer's total memory (which comprises physical RAM and virtual memory / swap space on hard disk).

     The maximum allowable memory usage can be configured using the file java.opts.  The directory where this file resides is determined by the environment variable OCTAVE_JAVA_DIR.  If unset, the directory where javaaddpath.m resides is used instead (typically OCTAVE_HOME/share/octave/OCTAVE_VERSION/m/java/).

     java.opts is a plain text file with one option per line.  The default initial memory size and default maximum memory size (which are both system dependent) can be overridden like so:

     -Xms64m

     -Xmx512m

     (in megabytes in this example). You can adapt these values to your own requirements if your system has limited available physical memory or if you get Java memory errors.

     "Total memory" is what the operating system has currently assigned to the JVM and depends on actual and active memory usage. "Free memory" is self-explanatory.  During operation of Java-based Octave functions the amount of Total and Free memory will vary, due to Java's own cleaning up and your operating system's memory management.

 -- Built-in Function: VAL = java_matrix_autoconversion ()
 -- Built-in Function: OLD_VAL = java_matrix_autoconversion (NEW_VAL)
 -- Built-in Function: java_matrix_autoconversion (NEW_VAL, "local")
     Query or set the internal variable that controls whether Java arrays are automatically converted to Octave matrices.

     The default value is false.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. java_unsigned_autoconversion, debug_java

 -- Built-in Function: VAL = java_unsigned_autoconversion ()
 -- Built-in Function: OLD_VAL = java_unsigned_autoconversion (NEW_VAL)
 -- Built-in Function: java_unsigned_autoconversion (NEW_VAL, "local")
     Query or set the internal variable that controls how integer classes are converted when java_matrix_autoconversion is enabled.

     When enabled, Java arrays of class Byte or Integer are converted to matrices of class uint8 or uint32 respectively.  The default value is true.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. java_matrix_autoconversion, debug_java

 -- Built-in Function: VAL = debug_java ()
 -- Built-in Function: OLD_VAL = debug_java (NEW_VAL)
 -- Built-in Function: debug_java (NEW_VAL, "local")
     Query or set the internal variable that determines whether extra debugging information regarding the initialization of the JVM and any Java exceptions is printed.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. java_matrix_autoconversion, java_unsigned_autoconversion

Dialog Box Functions
====================

The following functions all use the Java Interface to provide some form of dialog box.

 -- Function File: H = msgbox (MSG)
 -- Function File: H = msgbox (MSG, TITLE)
 -- Function File: H = msgbox (MSG, TITLE, ICON)
 -- Function File: H = msgbox (..., CREATEMODE)
     Display MSG using a message dialog box.

     The message may have multiple lines separated by newline characters ("\n"), or it may be a cellstr array with one element for each line.

     The optional input TITLE (character string) can be used to decorate the dialog caption.

     The optional argument ICON selects a dialog icon. It can be one of "none" (default), "error", "help", or "warn".

     The return value is always 1.

     Compatibility Note: The optional argument CREATEMODE is accepted for MATLAB compatibility, but is not implemented.

     errordlg, helpdlg, inputdlg, listdlg, questdlg, warndlg

 -- Function File: H = errordlg (MSG)
 -- Function File: H = errordlg (MSG, TITLE)
 -- Function File: H = errordlg (MSG, TITLE, CREATEMODE)
     Display MSG using an error dialog box.

     The message may have multiple lines separated by newline characters ("\n"), or it may be a cellstr array with one element for each line.

     The optional input TITLE (character string) can be used to set the dialog caption.  The default title is "Error Dialog".

     The return value is always 1.

     Compatibility Note: The optional argument CREATEMODE is accepted for MATLAB compatibility, but is not implemented.

     helpdlg, inputdlg, listdlg, msgbox, questdlg, warndlg

 -- Function File: H = helpdlg (MSG)
 -- Function File: H = helpdlg (MSG, TITLE)
     Display MSG in a help dialog box.

     The message may have multiple lines separated by newline characters ("\n"), or it may be a cellstr array with one element for each line.

     The optional input TITLE (character string) can be used to set the dialog caption.  The default title is "Help Dialog".

     The return value is always 1. errordlg, inputdlg, listdlg, msgbox, questdlg, warndlg

 -- Function File: CSTR = inputdlg (PROMPT)
 -- Function File: CSTR = inputdlg (PROMPT, TITLE)
 -- Function File: CSTR = inputdlg (PROMPT, TITLE, ROWSCOLS)
 -- Function File: CSTR = inputdlg (PROMPT, TITLE, ROWSCOLS, DEFAULTS)
     Return user input from a multi-textfield dialog box in a cell array of strings, or an empty cell array if the dialog is closed by the Cancel button.

     Inputs:

     prompt
          A cell array with strings labeling each text field.  This input is required.

     title
          String to use for the caption of the dialog.  The default is "Input Dialog".

     rowscols
          Specifies the size of the text fields and can take three forms:

           1. a scalar value which defines the number of rows used for each text field.

           2. a vector which defines the individual number of rows used for each text field.

           3. a matrix which defines the individual number of rows and columns used for each text field.  In the matrix each row describes a single text field.  The first column specifies the number of input rows to use and the second column specifies the text field width.

     defaults
          A list of default values to place in each text fields.  It must be a cell array of strings with the same size as PROMPT.

     errordlg, helpdlg, listdlg, msgbox, questdlg, warndlg

 -- Function File: [SEL, OK] = listdlg (KEY, VALUE, ...)
     Return user inputs from a list dialog box in a vector of selection indices SEL and a flag OK indicating how the user closed the dialog box.

     The value of OK is 1 if the user closed the box with the OK button, otherwise it is 0 and SEL is empty.

     The indices in SEL are 1-based.

     The arguments are specified in form of KEY, VALUE pairs. The "ListString" argument pair must be specified.

     Valid KEY and VALUE pairs are:

     "ListString"
          a cell array of strings comprising the content of the list.

     "SelectionMode"
          can be either "Single" or "Multiple" (default).

     "ListSize"
          a vector with two elements WIDTH and HEIGHT defining the size of the list field in pixels.  Default is [160 300].

     "InitialValue"
          a vector containing 1-based indices of preselected elements. Default is 1 (first item).

     "Name"
          a string to be used as the dialog caption.  Default is "".

     "PromptString"
          a cell array of strings to be displayed above the list field. Default is {}.

     "OKString"
          a string used to label the OK button.  Default is "OK".

     "CancelString"
          a string used to label the Cancel button.  Default is "Cancel".

     Example:

          [sel, ok] = listdlg ("ListString", {"An item", "another", "yet another"},
                               "SelectionMode", "Multiple");
          if (ok == 1)
            for i = 1:numel (sel)
              disp (sel(i));
            endfor
          endif

     menu, errordlg, helpdlg, inputdlg, msgbox, questdlg, warndlg

 -- Function File: BTN = questdlg (MSG)
 -- Function File: BTN = questdlg (MSG, TITLE)
 -- Function File: BTN = questdlg (MSG, TITLE, DEFAULT)
 -- Function File: BTN = questdlg (MSG, TITLE, BTN1, BTN2, DEFAULT)
 -- Function File: BTN = questdlg (MSG, TITLE, BTN1, BTN2, BTN3, DEFAULT)
     Display MSG using a question dialog box and return the caption of the activated button.

     The dialog may contain two or three buttons which will all close the dialog.

     The message may have multiple lines separated by newline characters ("\n"), or it may be a cellstr array with one element for each line.

     The optional TITLE (character string) can be used to decorate the dialog caption.

     The string DEFAULT identifies the default button, which is activated by pressing the ENTER key.  It must match one of the strings given in BTN1, BTN2, or BTN3.

     If only MSG and TITLE are specified, three buttons with the default captions "Yes", "No", and "Cancel" are used.

     If only two button captions, BTN1 and BTN2, are specified the dialog will have only these two buttons.

     errordlg, helpdlg, inputdlg, listdlg, warndlg

 -- Function File: H = warndlg (MSG)
 -- Function File: H = warndlg (MSG, TITLE)
 -- Function File: H = warndlg (MSG, TITLE, CREATEMODE)
     Display MSG using a warning dialog box.

     The message may have multiple lines separated by newline characters ("\n"), or it may be a cellstr array with one element for each line.

     The optional input TITLE (character string) can be used to set the dialog caption.  The default title is "Warning Dialog".

     The return value is always 1.

     Compatibility Note: The optional argument CREATEMODE is accepted for MATLAB compatibility, but is not implemented.

     helpdlg, inputdlg, listdlg, questdlg

FAQ - Frequently asked Questions
================================

How to distinguish between Octave and Matlab?
---------------------------------------------

Octave and MATLAB are very similar, but handle Java slightly different. Therefore it may be necessary to detect the environment and use the appropriate functions.  The following function can be used to detect the environment.  Due to the persistent variable it can be called repeatedly without a heavy performance hit.

Example:

     %%
     %% Return: true if the environment is Octave.
     %%
     function retval = isOctave
       persistent cacheval;  % speeds up repeated calls

       if isempty (cacheval)
         cacheval = (exist ("OCTAVE_VERSION", "builtin") > 0);
       end

       retval = cacheval;
     end

How to make Java classes available to Octave?
---------------------------------------------

Java finds classes by searching a CLASSPATH.  This is a list of Java archive files and/or directories containing class files.  In Octave the CLASSPATH is composed of two parts:

  * the STATIC CLASSPATH is initialized once at startup of the JVM, and

  * the DYNAMIC CLASSPATH which can be modified at runtime.

Octave searches the STATIC CLASSPATH first, then the DYNAMIC CLASSPATH.  Classes appearing in the STATIC as well as in the DYNAMIC CLASSPATH will therefore be found in the STATIC CLASSPATH and loaded from this location.  Classes which will be used frequently or must be available to all users should be added to the STATIC CLASSPATH.  The STATIC CLASSPATH is populated once from the contents of a plain text file named javaclasspath.txt (or classpath.txt historically) when the Java Virtual Machine starts.  This file contains one line for each individual classpath to be added to the STATIC CLASSPATH.  These lines can identify single class files, directories containing class files, or Java archives with complete class file hierarchies.  Comment lines starting with a # or a % character are ignored.

The search rules for the file javaclasspath.txt (or classpath.txt) are:

  * First, Octave tries to locate it in the current directory (where Octave was started from).  If such a file is found, it is read and defines the initial STATIC CLASSPATH.  Thus, it is possible to define a static classpath on a 'per Octave invocation' basis.

  * Next, Octave searches in the user's home directory.  If a file javaclasspath.txt exists here, its contents are appended to the static classpath (if any).  Thus, it is possible to build an initial static classpath on a 'per user' basis.

  * Finally, Octave looks for a next occurrence of file javaclasspath.txt in the m-files directory where Octave Java functions live.  This is where javaclasspath.m resides, usually something like OCTAVE_HOME/share/octave/OCTAVE_VERSION/m/java/.  You can find this directory by executing the command

          which javaclasspath

     If this file exists here, its contents are also appended to the static classpath.  Note that the archives and class directories defined in this last step will affect all users.

Classes which are used only by a specific script should be placed in the DYNAMIC CLASSPATH.  This portion of the classpath can be modified at runtime using the javaaddpath and javarmpath functions.

Example:

     octave> base_path = "C:/Octave/java_files";

     octave> % add two JARchives to the dynamic classpath
     octave> javaaddpath ([base_path, "/someclasses.jar"]);
     octave> javaaddpath ([base_path, "/moreclasses.jar"]);

     octave> % check the dynamic classpath
     octave> p = javaclasspath;
     octave> disp (p{1});
     C:/Octave/java_files/someclasses.jar
     octave> disp (p{2});
     C:/Octave/java_files/moreclasses.jar

     octave> % remove the first element from the classpath
     octave> javarmpath ([base_path, "/someclasses.jar"]);
     octave> p = javaclasspath;
     octave> disp (p{1});
     C:/Octave/java_files/moreclasses.jar

     octave> % provoke an error
     octave> disp (p{2});
     error: A(I): Index exceeds matrix dimension.

Another way to add files to the DYNAMIC CLASSPATH exclusively for your user account is to use the file .octaverc which is stored in your home directory.  All Octave commands in this file are executed each time you start a new instance of Octave.  The following example adds the directory octave to Octave's search path and the archive myclasses.jar in this directory to the Java search path.

     % contents of .octaverc:
     addpath ("~/octave");
     javaaddpath ("~/octave/myclasses.jar");

How to create an instance of a Java class?
------------------------------------------

The function javaObject can be used to create Java objects..

Example:

     Passenger = javaObject ("package.FirstClass", row, seat);

How can I handle memory limitations?
------------------------------------

In order to execute Java code Octave creates a Java Virtual Machine (JVM). Such a JVM allocates a fixed amount of initial memory and may expand this pool up to a fixed maximum memory limit.  The default values depend on the Java version (see javamem).  The memory pool is shared by all Java objects running in the JVM.  This strict memory limit is intended mainly to avoid that runaway applications inside web browsers or in enterprise servers can consume all memory and crash the system.  When the maximum memory limit is hit, Java code will throw exceptions so that applications will fail or behave unexpectedly.

You can specify options for the creation of the JVM inside a file named java.opts.  This is a text file where you can enter lines containing -X and -D options handed to the JVM during initialization.

The directory where the Java options file is located is specified by the environment variable OCTAVE_JAVA_DIR.  If unset the directory where javaclasspath.m resides is used instead (typically OCTAVE_HOME/share/octave/OCTAVE_VERSION/m/java/).  You can find this directory by executing

     which javaclasspath

The -X options allow you to increase the maximum amount of memory available to the JVM.  The following example allows up to 256 Megabytes to be used by adding the following line to the java.opts file:

     -Xmx256m

The maximum possible amount of memory depends on your system.  On a Windows system with 2 Gigabytes main memory you should be able to set this maximum to about 1 Gigabyte.

If your application requires a large amount of memory from the beginning, you can also specify the initial amount of memory allocated to the JVM.  Adding the following line to the java.opts file starts the JVM with 64 Megabytes of initial memory:

     -Xms64m

For more details on the available -X options of your Java Virtual Machine issue the command java -X at the operating system command prompt and consult the Java documentation.

The -D options can be used to define system properties which can then be used by Java classes inside Octave.  System properties can be retrieved by using the getProperty() methods of the java.lang.System class. The following example line defines the property MYPROPERTY and assigns it the string 12.34.

     -DMyProperty=12.34

The value of this property can then be retrieved as a string by a Java object or in Octave:

     octave> javaMethod ("getProperty", "java.lang.System", "MyProperty");
     ans = 12.34

javamem

Which TeX symbols are implemented in dialog functions?
------------------------------------------------------

The dialog functions contain a translation table for TeX like symbol codes. Thus messages and labels can be tailored to show some common mathematical symbols or Greek characters.  No further TeX formatting codes are supported. The characters are translated to their Unicode equivalent.  However, not all characters may be displayable on your system.  This depends on the font used by the Java system on your computer.

Each TeX symbol code must be terminated by a space character to make it distinguishable from the surrounding text.  Therefore the string \alpha =12.0 will produce the desired result, whereas \alpha=12.0 would produce the literal text '\ALPHA=12.0'.

errordlg, helpdlg, inputdlg, listdlg, msgbox, questdlg, warndlg