# Include java code to display text in latex

is it possible to do something like the following in texlipse?

\documentclass{article}
\usepackage{listings}
\begin{document}

\section{Title}
import java
\subsection{Subtitle}

I want to display some java result

\begin{lstlisting}
printMyString()
\end{lstlisting}
\end{document}


Where printMyString() is for example:

public String printMyString() {
return "Hello World";
}


thanks!

-

## migrated from stackoverflow.comMar 4 '13 at 13:37

This question came from our site for professional and enthusiast programmers.

What should the output look like? Do you want the string printMyString() to be replaced by the entire procedure, or just "Hello World"? listings does provide \lstinputlistings which can input from a file and you can specify a linerange. Alternatively, there's a literate replacement that you could use. – Werner Mar 1 '13 at 16:15
I want only Hello World to be displayed, thanks – Franky Mar 1 '13 at 16:19
@Franky: That would require a TeX engine with a build-in JVM; such a beast doesn't exist yet. The best you can do is have TeX execute other programs and use their output (\write18) or use LuaTeX and it's build-in Lua interpreter. – Martin Schröder Mar 2 '13 at 10:40

Although I'm not a fan of on-the-fly computation inside a document, here's a possible solution using BeanShell:

BeanShell is a small, free, embeddable Java source interpreter with object scripting language features, written in Java. BeanShell dynamically executes standard Java syntax and extends it with common scripting conveniences such as loose types, commands, and method closures like those in Perl and JavaScript.

There we go.

paulo@alexandria Sandbox\$ ls
bsh.jar        test.tex


My humble code:

\documentclass{article}

\usepackage{fancyvrb}

\makeatletter
\newcommand{\calljava}{\ttfamily\@@input|"java -cp bsh.jar bsh.Interpreter tmp.bsh"}
\makeatother

\newenvironment{java}
{\VerbatimOut{tmp.bsh}}
{\endVerbatimOut\calljava}

\begin{document}

My first code.

\vspace{2em}

\begin{java}
int addTwoNumbers(int a, int b) {
return a + b;
}
\end{java}

\vspace{2em}

My second code.

\vspace{2em}

\begin{java}
for (int i = 1; i <= 10; i++) {
System.out.println("I like ducks!\\par");
}
\end{java}

\end{document}


Running with pdflatex --shell-escape test.tex:

The idea is quite simple: get the body of the java environment and add it to a temporary file named tmp.bsh, run the interpreter from bsh.jar passing the temporary file to be executed, and capture the output.

My good friend egreg mentioned that this code doesn't work with xetex or luatex, unless we write another auxiliary file and input it. Let's stick with pdflatex for a while then. :)

Hope it helps. :)

-