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:

enter image description here


  • 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.



 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;

\lstdefinestyle{MyListStyle} {
    caption={Partial Listing},
    label={lst: partial}

As can be seen from Listings~\ref{lst: partial} we see that...
  • 1
    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
  • 1
    @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
  • 1
    I am just getting ?? what ever times i run the script..Am i missing anything? – volatNumbers Mar 9 '12 at 8:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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