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}