# 10.4 Higher Order Functions in Java

**Higher Order Function:** A function that treats another function as data.

* e.g. takes a function as input.
* Example in Python:&#x20;

```python
def tenX(x):
   return 10*x
 
def do_twice(f, x):
   return f(f(x))
 
print(do_twice(tenX, 2))
```

### Higher Order Functions in Java 7

Old School (Java 7 and earlier)

* Fundamental issue: Memory boxes (variables) cannot contain pointers to functions.
  * use an interface instead:

```java
public interface IntUnaryFunction {
	int apply(int x);
}

public class TenX implements IntUnaryFunction {
	public int apply(int x) {
   		return 10 * x;
	}
}
```

This code above is the same as the Python code:

```python
def tenX(x):
    return 10*x
```

Now, to finish the rest of the Python code in Java:

<pre class="language-java"><code class="lang-java">public interface IntUnaryFunction {
	int apply(int x);
}

public class TenX implements IntUnaryFunction {
	public int apply(int x) {
   		return 10 * x;
	}
}

<strong>public class HoFDemo {
</strong>	public static int do_twice(IntUnaryFunction f, int x) {
   		return f.apply(f.apply(x));
	}
	
	public static void main(String[] args) {
   		System.out.println(do_twice(new TenX(), 2));
	}
}
</code></pre>

This code above is equivalent to the Python code provided earlier.
