How to escape special characters in java?

Often times, we encountered some special characters or arbitrary text placed in an HTML tag that resulting an invalid HTML output. The special characters often needs to be altered or escape to ensure the resulting HTML is still valid.

Special characters as follow
1) < 2) >
3) ”
4) ‘
5) \
6) &

Here i want to introduce a handy-ready java library call StringEscapeUtils which included in commons-lang.jar library, and used to escape special characters in Java.

P.S Please download the commons-lang.jar library in

Here is the source code to demonstrate how to escape special characters with StringEscapeUtils class.

import org.apache.commons.lang.StringEscapeUtils;
public class testEscapeHTML{
	public static void main(String args[]){
		String testStr = "< > \" &";
		System.out.println("Original : " + testStr);
		System.out.println("Escaped : " + StringEscapeUtils.escapeHtml(testStr));


Original : < > " &
Escaped : &lt; &gt; &quot; &amp;


Tags :

About the Author

Founder of and, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.


  • Swati Rohilla

    This is the BEST example. It helped me alot. Thanks alot. Big thanks to you.