Minimal working example on how to use Listings in LaTeX

In case you want to show code snippets in your LaTeX document, you can use the “listings” package. The following is a (minimal) working example on how to use the listings package.
% Step 1: Load package
% Step 2: Set required options
% You can set them also inline for each given lstlisting
\title{Minimal Working Example}
\subtitle{Using Listings}
\section{A Chapter}
In Listing \ref{lst:example}, you find a simple “Hello World” program in Java.
% Step 3: Create listing and set local options
% (This can be also an external input file using
% \lstinputlisting{})
\begin{lstlisting}[label={lst:example}, caption={Java Hello World Example}]
public class HelloWorld {
public static void main(String[] args){
System.out.println("Hello World");
% Step 4: Create list of listings (optional)
Now you have to build the PDF file using the following steps (this example works in Debian jessie and the texlive suite). The filename is “listings.tex”.
$> pdflatex listings.tex
$> pdflatex listings.tex
The pdflatex command has to be executed twice, as in the first run, the references in the text are recognized and ordered, whereas in the second run the references are finalized. Then, you end up with a file “listings.pdf” which can be found here: Listings Example.
There are many options for setting up the listings especially for using colors, typesetting, defining new languages etc.
See for a complete list of options and examples.