Calling Custom Clojure Functions from Java

Calling Clojure APIs from Java is discussed in my first tutorial. This tutorial explores calling your own Clojure functions from Java. A common use case for this is when you write a JavaFX UI and want to have the controller code written in Clojure.

Our first example explains how to call a simple Clojure function that takes no arguments and returns no values. (Technically, all Clojure fuctions return values, but that doesn’t mean we care about all values Clojure functions return.)

(ns java-clj-interop.core)

(defn hello-world
  "Yeah. You guessed it. This prints 'Hello World!'"
  (println "Hello World!"))

Continue reading “Calling Custom Clojure Functions from Java”

Calling Clojure Functions from Java

Mixing Clojure functions and Java methods usually happens when pure Clojure applications need to interact with Java libraries. However, sometimes you have Clojure functions receiving events from a Java program. This is often the case when you have a Java program with a JavaFX, Java Swing, or Java AWT GUI, but you want all the controller logic written in Clojure. It certainly is  possible to write Clojure code calling Java libraries to create a decent UI, but doing so would be clunky at best.

It is also possible that you have a legacy Java application that you want to write Clojure plugins for. This is easily accomplished by calling Clojure functions from any appropriate place in the Java code. You can call directly into uncompiled Clojure scripts. To call Clojure scripts, you just need to know the right classes for loading your code.

Continue reading “Calling Clojure Functions from Java”

Java pass-by-reference and pass-by-value

The question often arises, “Does Java pass-by-reference or does it pass-by-value?” meaning when an argument is passed to a method in Java, is it the memory address of the variable given to the method, or the value of the variable that is passed to the method. What happens when you change the values of the arguments passed to a method?

Without getting into discussions about the virtues of functional programming versus traditional object oriented programming, let’s answer the pass-by-reference or pass-by-value question.

Java uses pass-by-value. This gets a little confusing with objects, but we’ll stick to primitives for the moment. Java passes copies of variable values to methods. When passing primitives to methods, such as ints and bytes, any changes to the values of the method arguments are only of local scope to the method.

Continue reading “Java pass-by-reference and pass-by-value”