Import Java. util. arraylist; <br/> Import Java. util. list; </P> <p> // http://www.jtraining.com/blogs/string-and-memory-leaks-in-java.html <br/> // http://www.javablogging.com/string-and-memory-leaks/ <br/> public class teststringoutofmemoryerror {</P> <p> Public static void main (string [] ARGs) throws exception {<br/> testwithoutofmemoryerror (); <br/> // testwithoutoutofmemoryerror (); <br/> system. out. println (" Haha! "); <Br/>}</P> <p> Public static void testwithoutofmemoryerror () {<br/> List <string> List = new arraylist <string> (); <br/> for (INT I = 0; I <10000; I ++) {<br/> list. add (getstringwithoutofmemoryerror (); <br/>}</P> <p> Public static void testwithoutoutofmemoryerror () {<br/> List <string> List = new arraylist <string> (); <br/> for (INT I = 0; I <10000; I ++) {<br/> list. add (getstringwithoutoutofmemoryerror (); <br/>}</P> <p> Public static string getstringwithoutofmemoryerror () {<br/> stringbuffer sb = new stringbuffer (); <br/> Sb. append (system. currenttimemillis (); <br/> for (INT I = 0; I <10000; I ++) {<br/> Sb. append ("1234567890"); <br/>}< br/> string S = sb. tostring (); <br/> return S. substring (0, 13); <br/>}</P> <p> Public static string getstringwithoutoutofmemoryerror () {<br/> stringbuffer sb = new stringbuffer (); <br/> Sb. append (system. currenttimemillis (); <br/> for (INT I = 0; I <10000; I ++) {<br/> Sb. append ("1234567890"); <br/>}< br/> string S = sb. tostring (); <br/> return new string (S. substring (0, 13); <br/>}< br/>}