R is a popular programming language. It is mostly sought out for data and statistical analysis as well as for machine learning. It provides various libraries which render an environment favorable to those mentioned above. Furthermore, it is harnessed by many quantitative analysts as it has proven to be handy when it comes to data cleansing and importing.
R is a core functional programming language, although object-oriented programming does exist within R, to put it plainly, it is not at the same level as other languages such as Java. It is also not as efficient due to the fact it is an interpreted language. Hence it is more computationally economical to run Java code in R.
R offers a package known as rJava
, this package allows us to run java code within our R file. In other words, this library provides a bridge between R and Java, enabling us to access Java fields from R.
j_obj <- .jnew(class , arg)
class
: This is the type of the object, for instance, string, integer, double, etc.
arg
: This is the argument for the object.
The .jnew
method returns the object of class
type.
Let's look at the code below:
library(rJava).jinit()str_val <- .jnew(class="java.lang.String" , "Hello World").jstrVal(str_val)int_val <- .jnew(class = "java.lang.Integer", "1").jstrVal(int_val)
Line 1: We import the rJava
package.
Line 2: We initialize the Java virtual machine.
Line 4: We create a java object of the type java.lang.String
. The value of that string is Hello World.
And we store the instance of the object created into str_val
.
Line 5: We display the value of str_val
to console as a string.
Line 7: We create a Java object of type java.lang.Integer
. The value of that string is Hello World
. And we store the instance of the object created into int_val
.
Line 8: We display the value of int_val
to console as a string.
Free Resources