<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/a-primer-in-using-java-from-r-part-1/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://jozefhajnala.gitlab.io/r/r901-primer-java-from-r-1/"> Jozef's Rblog</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div>
<h1>Introduction</h1>
<p>This primer shall consist of two parts and its goal is to provide a walk-through of using resources developed in Java from R. It is structured as more of a “note-to-future-self” rather than a proper educational article, I however hope that some readers may still find it useful. It will also list a set of <a rel="nofollow" href="https://jozefhajnala.gitlab.io/r/r901-primer-java-from-r-1/#references" target="_blank">references</a> that I found very helpful, for which I thank the respective authors.</p>
<p>The primer is split into 2 posts:</p>
<ol>
<li>In this first one we talk about using of the rJava package to create objects, call methods and work with arrays, we examine the various ways to call Java methods and calling Java code from R directly via execution of shell commands.</li>
<li>In the second one we discuss creating and using custom .jar archives within our R scripts and packages, handling of Java exceptions from R and a quick look at performance comparison between the low and high-level interfaces provided by rJava.</li>
</ol>
<div>
<img alt="R &lt;3 Java, or maybe not?" src="https://i2.wp.com/jozefhajnala.gitlab.io/r/img/r901-01-r-java.gif?w=456&ssl=1" data-recalc-dims="1">
<p>R &lt;3Java, or maybe not?</p>
</div>
</div>
<div>
<h1>Contents</h1>
<ol>
<li><a rel="nofollow" href="https://jozefhajnala.gitlab.io/r/r901-primer-java-from-r-1/#calling-java-from-r-directly" target="_blank">Calling Java from R directly</a></li>
<li><a rel="nofollow" href="https://jozefhajnala.gitlab.io/r/r901-primer-java-from-r-1/#the-rjava-package---an-r-to-java-interface" target="_blank">The rJava package – an R to Java interface</a></li>
<li><a rel="nofollow" href="https://jozefhajnala.gitlab.io/r/r901-primer-java-from-r-1/#calling-java-methods-using-the-rjava-package" target="_blank">Calling Java methods using the rJava package</a></li>
<li><a rel="nofollow" href="https://jozefhajnala.gitlab.io/r/r901-primer-java-from-r-1/#signatures-in-jni-notation" target="_blank">Signatures in JNI notation</a></li>
<li><a rel="nofollow" href="https://jozefhajnala.gitlab.io/r/r901-primer-java-from-r-1/#references" target="_blank">References</a></li>
</ol>
</div>
<div>
<h1>Calling Java from R directly</h1>
<p>Calling Java resources from R directly can be achieved using R’s <code>system()</code> function, which invokes the specified OS command. We can either use an already compiled java class, or invoke the compilation also via a <code>system()</code> call from R. Of course for any real world practical uses, we will probably do the Java coding, compilation and jaring in a Java IDE and provide R with just the final .jar file(s), I however find it helpful to have a small example of the simplest complete case, for which even the following is sufficient. Integrating pre-prepared .jars into an R packages will be covered in detail by the second part of this primer.</p>
<p>Let us show that by writing a very silly dummy class with just 2 methods:</p>
<ul>
<li><code>main</code>, that prints “Hello World!” + an optional suffix, if provided as argument</li>
<li><code>SayMyName</code> method, that returns a string constructed from “My name is” and <code>getClass().getName()</code></li>
</ul>
<p>This <code>HelloWorldDummy.java</code> file can look as follows:</p>
<pre><code>package DummyJavaClassJustForFun;

public class HelloWorldDummy {

  public String SayMyName() {
   return(&quot;My name is &quot; + getClass().getName());
  }
  
  public static void main(String[] args) {
    String stringArg = &quot;And that is it.&quot;;
    if (args.length > 0) {
      stringArg = args[0];
    }
    System.out.println(&quot;Hello, World. &quot; + stringArg);
  }
}</code></pre>
<div>
<h2>Compilation and execution via bash commands</h2>
<p>Now that we have our dummy class ready, we can put together the commands and test them by just executing via a shell, or for RStudio fans, we can test the commands via RStudio’s cool Terminal feature. First, the compilation command, which may look something like the following, assuming that we are in the correct working directory:</p>
<pre><code>$ javac DummyJavaClassJustForFun/HelloWorldDummy.java</code></pre>
<p>Now that we have the class compiled, we can execute the <code>main</code> method, with and without the argument provided:</p>
<pre><code>$ java DummyJavaClassJustForFun/HelloWorldDummy
$ java DummyJavaClassJustForFun/HelloWorldDummy &quot;I like winter&quot;</code></pre>
<p>In case we need to compile and run with more .jars that are in folder <code>jars/</code>, we specify the folder using <code>-cp</code> (class path):</p>
<pre><code>$ javac -cp &quot;jars/*&quot; DummyJavaClassJustForFun/HelloWorldDummy.java
$ java -cp &quot;jars/*:compile/src&quot; DummyJavaClassJustForFun/HelloWorldDummy</code></pre>
</div>
<div>
<h2>Compilation and execution of Java code from R</h2>
<p>Now that we have tested our commands, we can use R to do the compilation via the <code>system</code> function. Do not forget to <code>cd</code> into the correct directory within a single system call if needed:</p>
<pre><code>system('cd data/; javac DummyJavaClassJustForFun/HelloWorldDummy.java')</code></pre>
<p>After that we can also execute the <code>main</code> method, and the <code>main</code> method with one argument specified, just like we did it outside of R, once again using <code>cd</code> to enter the proper working directory if needed:</p>
<pre><code>system('cd data/; java DummyJavaClassJustForFun/HelloWorldDummy')
system('cd data/; java DummyJavaClassJustForFun/HelloWorldDummy &quot;Also I like winter&quot;')</code></pre>
</div>
</div>
<div>
<h1>The rJava package – an R to Java interface</h1>
<p>The rJava package provides a low-level interface to Java virtual machine. It allows creation of objects, calling methods and accessing fields of the objects. It also provides functionality to include our java resources into R packages easily.</p>
<p>We can install it with the classic:</p>
<pre><code>install.packages(&quot;rJava&quot;)</code></pre>
<p>Note the system requirement Java JDK 1.2 or higher and for JRI/REngine JDK 1.4 or higher. After attaching the package, we also need to initialize a Java Virtual Machine (JVM):</p>
<pre><code>## Attach rJava and Init a JVM
library(rJava)
.jinit()</code></pre>
<p>In case of issues with attaching the package using <code>library</code>, one can refer to <a rel="nofollow" href="https://stackoverflow.com/questions/37735108/r-error-onload-failed-in-loadnamespace-for-rjava" target="_blank">this helpful StackOverflow thread</a>.</p>
<div>
<h2>Creating Java objects with rJava</h2>
<p>We will now very quickly go through the basic uses of the package. The <code>.jnew</code> function is used to create a new Java object. Note that the <code>class</code> argument requires a fully qualified class name in Java Native Interface notation.</p>
<pre><code># Creating a new object of java.lang class String
sHello &lt;- .jnew(class = &quot;java/lang/String&quot;, &quot;Hello World!&quot;)
# Creating a new object of java.lang class Integer
iOne &lt;- .jnew(class = &quot;java/lang/Integer&quot;, &quot;1&quot;)</code></pre>
</div>
<div>
<h2>Working with arrays via rJava</h2>
<pre><code># Creating new arrays
iArray &lt;- .jarray(1L:2L)
.jevalArray(iArray)</code></pre>
<pre><code>## [1] 1 2</code></pre>
<pre><code># Using a list of 2 and lapply
# Integer Matrix int[2][2]
iMatrix &lt;- .jarray(list(iArray, iArray), contents.class = &quot;[I&quot;)
lapply(iMatrix, .jevalArray)</code></pre>
<pre><code>## [[1]]
## [1] 1 2
## 
## [[2]]
## [1] 1 2</code></pre>
<pre><code># Integer Matrix int[2][2]
square &lt;- array(1:4, dim = c(2, 2))
square</code></pre>
<pre><code>##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4</code></pre>
<pre><code># Using dispatch = TRUE to create the array 
# Using simplify = TRUE to return a nice R array
dSquare &lt;- .jarray(square, dispatch = TRUE)
.jevalArray(dSquare, simplify = TRUE)</code></pre>
<pre><code>##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4</code></pre>
<pre><code># Integer Tesseract int[2][2][2][2]
tesseract &lt;- array(1L:16L, dim = c(2, 2, 2, 2))
tesseract</code></pre>
<pre><code>## , , 1, 1
## 
##      [,1] [,2]
## [1,]    1    3
## [2,]    2    4
## 
## , , 2, 1
## 
##      [,1] [,2]
## [1,]    5    7
## [2,]    6    8
## 
## , , 1, 2
## 
##      [,1] [,2]
## [1,]    9   11
## [2,]   10   12
## 
## , , 2, 2
## 
##      [,1] [,2]
## [1,]   13   15
## [2,]   14   16</code></pre>
<pre><code># Use dispatch = TRUE to create the array 
# Use simplify = TRUE to return a nice R array
# Interestingly, this seems weird
dTesseract &lt;- .jarray(tesseract, dispatch = TRUE)
.jevalArray(dTesseract, simplify = TRUE)</code></pre>
<pre><code>## , , 1, 1
## 
##      [,1] [,2]
## [1,]    1    0
## [2,]    0    0
## 
## , , 2, 1
## 
##      [,1] [,2]
## [1,]    0    0
## [2,]    0    8
## 
## , , 1, 2
## 
##      [,1] [,2]
## [1,]    9    0
## [2,]    0    0
## 
## , , 2, 2
## 
##      [,1] [,2]
## [1,]    0    0
## [2,]    0   16</code></pre>
</div>
</div>
<div>
<h1>Calling Java methods using the rJava package</h1>
<p>rJava provides two levels of API:</p>
<ul>
<li>fast, but inflexible low-level JNI-API in the form of the <code>.jcall</code> function</li>
<li>convenient (at the cost of performance) high-level reflection API based on the <code>$</code> operator.</li>
</ul>
<p>In practice, there are three ways available to us from the rJava package enabling us to call Java methods, each of them with their positives and negatives.</p>
<div>
<h2>The low-level way – <code>.jcall()</code></h2>
<p><code>.jcall(obj, returnSig = &quot;V&quot;, method, ...)</code> calls a Java method with the supplied arguments the “low-level” way. A few important notes regarding the usage, for more refer to the R help on .jcall:</p>
<ul>
<li>requires exact match of argument and return types, doesn’t perform any lookup in the reflection tables</li>
<li>passing sub-classes of the classes present in the method definition requires explicit casting using <code>.jcast</code></li>
<li>passing null arguments needs a proper class specification with <code>.jnull</code></li>
<li>vector of length 1 corresponding to a native Java type is considered a scalar, use <code>.jarray</code> to pass a vector as array for safety</li>
</ul>
<pre><code># Calling a Java method length on the object low-level way
.jcall(sHello, returnSig = &quot;I&quot;, &quot;length&quot;)</code></pre>
<pre><code>## [1] 12</code></pre>
<pre><code># Also we must be careful with the data types:

# This works
.jcall(sHello, returnSig = &quot;C&quot;, &quot;charAt&quot;, 5L)</code></pre>
<pre><code>## [1] 32</code></pre>
<pre><code># This does not
.jcall(sHello, returnSig = &quot;C&quot;, &quot;charAt&quot;, 5)</code></pre>
<pre><code>## Error in .jcall(sHello, returnSig = &quot;C&quot;, &quot;charAt&quot;, 5): method charAt with signature (D)C not found</code></pre>
</div>
<div>
<h2>The high-level way – <code>J()</code></h2>
<p><code>J(class, method, ...)</code> is the high level API for accessing Java, it is slower than <code>.jnew</code> or <code>.jcall</code> since it has to use reflection to find the most suitable method.</p>
<ul>
<li>to call a method, the <code>method</code> argument must be present as a character vector of length 1</li>
<li>if <code>method</code> is missing, <code>J</code> creates a class name reference</li>
</ul>
<pre><code># Calling a Java method length on the object high-level way
J(sHello, &quot;length&quot;)</code></pre>
<pre><code>## [1] 12</code></pre>
<pre><code># Also, the high-level will not help here this way
J(sHello, &quot;charAt&quot;, 5L)</code></pre>
<pre><code>## Error in .jcall(o, &quot;I&quot;, &quot;intValue&quot;): method intValue with signature ()I not found</code></pre>
<pre><code>J(sHello, &quot;charAt&quot;, 5)</code></pre>
<pre><code>## Error in .jcall(&quot;RJavaTools&quot;, &quot;Ljava/lang/Object;&quot;, &quot;invokeMethod&quot;, cl, : java.lang.NoSuchMethodException: No suitable method for the given parameters</code></pre>
</div>
<div>
<h2>The high-level way with convenience – <code>$</code></h2>
<p>Closely connected to the <code>J</code> function, the <code>$</code> operator for <code>jobjRef</code> Java object references provides convenience access to object attributes and calling Java methods by implementing relevant methods for the completion generator for R.</p>
<ul>
<li><code>$</code> returns either the value of the attribute or calls a method, depending on which name matches first</li>
<li><code>$&lt;-</code> assigns a value to the corresponding Java attribute</li>
</ul>
<pre><code># And via the $ operator
sHello$length()</code></pre>
<pre><code>## [1] 12</code></pre>
<pre><code># But these still do not work
sHello$charAt(5L)</code></pre>
<pre><code>## Error in .jcall(o, &quot;I&quot;, &quot;intValue&quot;): method intValue with signature ()I not found</code></pre>
<pre><code>sHello$charAt(5)</code></pre>
<pre><code>## Error in .jcall(&quot;RJavaTools&quot;, &quot;Ljava/lang/Object;&quot;, &quot;invokeMethod&quot;, cl, : java.lang.NoSuchMethodException: No suitable method for the given parameters</code></pre>
</div>
<div>
<h2>Examining methods and fields</h2>
<p><code>.DollarNames</code> returns all fields and methods associated with the object. Method names are followed by <code>(</code> or <code>()</code> depending on arity:</p>
<pre><code># vector of all fields and methods associated with sHello
.DollarNames(sHello)</code></pre>
<pre><code>##  [1] &quot;CASE_INSENSITIVE_ORDER&quot; &quot;equals(&quot;               
##  [3] &quot;toString()&quot;             &quot;hashCode()&quot;            
##  [5] &quot;compareTo(&quot;             &quot;compareTo(&quot;            
##  [7] &quot;indexOf(&quot;               &quot;indexOf(&quot;              
##  [9] &quot;indexOf(&quot;               &quot;indexOf(&quot;              
## [11] &quot;valueOf(&quot;               &quot;valueOf(&quot;              
## [13] &quot;valueOf(&quot;               &quot;valueOf(&quot;              
## [15] &quot;valueOf(&quot;               &quot;valueOf(&quot;              
## [17] &quot;valueOf(&quot;               &quot;valueOf(&quot;              
## [19] &quot;valueOf(&quot;               &quot;length()&quot;              
## [21] &quot;isEmpty()&quot;              &quot;charAt(&quot;               
## [23] &quot;codePointAt(&quot;           &quot;codePointBefore(&quot;      
## [25] &quot;codePointCount(&quot;        &quot;offsetByCodePoints(&quot;   
## [27] &quot;getChars(&quot;              &quot;getBytes()&quot;            
## [29] &quot;getBytes(&quot;              &quot;getBytes(&quot;             
## [31] &quot;getBytes(&quot;              &quot;contentEquals(&quot;        
## [33] &quot;contentEquals(&quot;         &quot;equalsIgnoreCase(&quot;     
## [35] &quot;compareToIgnoreCase(&quot;   &quot;regionMatches(&quot;        
## [37] &quot;regionMatches(&quot;         &quot;startsWith(&quot;           
## [39] &quot;startsWith(&quot;            &quot;endsWith(&quot;             
## [41] &quot;lastIndexOf(&quot;           &quot;lastIndexOf(&quot;          
## [43] &quot;lastIndexOf(&quot;           &quot;lastIndexOf(&quot;          
## [45] &quot;substring(&quot;             &quot;substring(&quot;            
## [47] &quot;subSequence(&quot;           &quot;concat(&quot;               
## [49] &quot;replace(&quot;               &quot;replace(&quot;              
## [51] &quot;matches(&quot;               &quot;contains(&quot;             
## [53] &quot;replaceFirst(&quot;          &quot;replaceAll(&quot;           
## [55] &quot;split(&quot;                 &quot;split(&quot;                
## [57] &quot;join(&quot;                  &quot;join(&quot;                 
## [59] &quot;toLowerCase(&quot;           &quot;toLowerCase()&quot;         
## [61] &quot;toUpperCase()&quot;          &quot;toUpperCase(&quot;          
## [63] &quot;trim()&quot;                 &quot;toCharArray()&quot;         
## [65] &quot;format(&quot;                &quot;format(&quot;               
## [67] &quot;copyValueOf(&quot;           &quot;copyValueOf(&quot;          
## [69] &quot;intern()&quot;               &quot;wait(&quot;                 
## [71] &quot;wait(&quot;                  &quot;wait()&quot;                
## [73] &quot;getClass()&quot;             &quot;notify()&quot;              
## [75] &quot;notifyAll()&quot;            &quot;chars()&quot;               
## [77] &quot;codePoints()&quot;</code></pre>
</div>
</div>
<div>
<h1>Signatures in JNI notation</h1>
<table>
<thead>
<tr>
<th>Java Type</th>
<th>Signature</th>
</tr>
</thead>
<tbody>
<tr>
<td>boolean</td>
<td>Z</td>
</tr>
<tr>
<td>byte</td>
<td>B</td>
</tr>
<tr>
<td>char</td>
<td>C</td>
</tr>
<tr>
<td>short</td>
<td>S</td>
</tr>
<tr>
<td>int</td>
<td>I</td>
</tr>
<tr>
<td>long</td>
<td>J</td>
</tr>
<tr>
<td>float</td>
<td>F</td>
</tr>
<tr>
<td>double</td>
<td>D</td>
</tr>
<tr>
<td>type[]</td>
<td>[ type</td>
</tr>
<tr>
<td>method type</td>
<td>( arg-types ) ret-type</td>
</tr>
<tr>
<td>fully-qualified-class</td>
<td>Lfully-qualified-class ;</td>
</tr>
</tbody>
</table>
<blockquote>
<h4>In the fully-qualified-class row of the table above note the</h4>
<ul>
<li><code>L</code> prefix</li>
<li><code>;</code> suffix</li>
</ul>
</blockquote>
<blockquote>
<h4>For example</h4>
<ul>
<li>the Java method: <code>long f (int n, String s, int[] arr);</code></li>
<li>has type signature: <code>(ILjava/lang/String;[I)J</code></li>
</ul>
</blockquote>
</div>
<div>
<h1>References</h1>
<ol>
<li><a rel="nofollow" href="https://www.rforge.net/rJava/" target="_blank">rJava basic crashcourse</a> – at the rJava site on rforge, scroll down to the Documentation section</li>
<li><a rel="nofollow" href="https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html#wp276" target="_blank">The JNI Type Signatures</a> – at Oracle JNI specs</li>
<li><a rel="nofollow" href="https://cran.r-project.org/web/packages/rJava/rJava.pdf" target="_blank">rJava documentation</a> on CRAN</li>
<li><a rel="nofollow" href="https://darrenjw.wordpress.com/2011/01/01/calling-java-code-from-r/" target="_blank">Calling Java code from R</a> by prof. Darren Wilkinson</li>
<li><a rel="nofollow" href="https://en.wikipedia.org/wiki/Java_Native_Interface#Mapping_types" target="_blank">Mapping of types between Java (JNI) and native code</a></li>
<li><a rel="nofollow" href="https://stackoverflow.com/questions/37735108/r-error-onload-failed-in-loadnamespace-for-rjava" target="_blank">Fixing issues with loading rJava</a></li>
</ol>
<h2>Did you find the article helpful or interesting? Help others find it by sharing</h2>
<div></div>
</div>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://jozefhajnala.gitlab.io/r/r901-primer-java-from-r-1/"> Jozef's Rblog</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/zqYl61N0zX0" height="1"></a></div>