Enhance Content
33 Inserting Code in Text
Glenn Bergen
Option 1: Using the <pre> tag
Here’s a first option, using the <pre> tag and formatted as a block quote. This tag applies a monospace font and keeps the line breaks exactly as written. A horizontal scroll bar will be added when there are longer lines:
// This program demonstrates variables, literal constants, and data types. public class Main { public static void main(String[] args) { int i; double d; String s; boolean b; i = 1234567890; d = 1.23456789012345; s = "string"; b = true; System.out.println("Integer i = " + i); System.out.println("Double d = " + d); System.out.println("String s = " + s); System.out.println("Boolean b = " + b); } }
Option 2: Using a text box
In this case, the text with the <pre> tag is included in a shaded text box without the block quote format:
// This program demonstrates variables, literal constants, and data types. public class Main { public static void main(String[] args) { int i; double d; String s; boolean b; i = 1234567890; d = 1.23456789012345; s = "string"; b = true; System.out.println("Integer i = " + i); System.out.println("Double d = " + d); System.out.println("String s = " + s); System.out.println("Boolean b = " + b); } }
Option 3: Inserting code within a paragraph using a <code> tag
If you want to note a smaller piece of code within a paragraph, use the <code> tag. For instance, System.out.println("Integer i = " + i);
can be highlighted like this. In this case, <code> just applies the monospace font; text colour has been adjusted separately.