# How to use example code (of any language) and reference it?

How to use Java or any code in LaTeX and refer it in my document?

-

Here is an example using the listings package. You use the label option to specify the label, and then refer to it using the usual \ref:

## Notes:

• Requires two runs to resolve the reference. In the first run you will see ??, and in the second this will get replaced with the actual listing number.

## Code:

\documentclass{article}
\usepackage{filecontents}
\usepackage{listings}

\begin{filecontents*}{foo.java}
public int nextInt(int n) {
if (n<=0)
throw new IllegalArgumentException("n must be positive");

if ((n & -n) == n)  // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);

int bits, val;
do {
bits = next(31);
val = bits % n;
} while(bits - val + (n-1) < 0);
return val;
}
\end{filecontents*}

\lstdefinestyle{MyListStyle} {
numbers=left,
numberstyle=\small,
language=Java
}
\begin{document}
\lstinputlisting[
style=MyListStyle,
linerange={2-6},
firstnumber=2,
caption={Partial Listing},
label={lst: partial}
]{foo.java}

As can be seen from Listings~\ref{lst: partial} we see that...
\end{document}

-
A nice addition to this would be to also explain how one refers to lines within a listing (use the escapechar or mathescape listings options; in the listing itself escape to LaTex and place a \label commands in the respective line). –  Daniel Mar 8 '12 at 16:29
@Daniel: I think it is better to use the line number instead. Otherwise you have to alter the actual code snippet that you are referring to. –  Peter Grill Mar 8 '12 at 16:52
Right, didn't notice on first sight that you are using \lstinputlisting. –  Daniel Mar 8 '12 at 20:00
I am just getting ?? what ever times i run the script..Am i missing anything? –  volatNumbers Mar 9 '12 at 8:23