TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


import java

I want to display some java result


Where printMyString() is for example:

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


share|improve this question

migrated from stackoverflow.com Mar 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
up vote 9 down vote accepted

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:



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



My first code.


int addTwoNumbers(int a, int b) {
   return a + b;
System.out.println(addTwoNumbers(10, 20));


My second code.


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


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

I like ducks!

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. :)

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.