Win a copy of The Business Blockchain this week in the Cloud forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

infinite loop throws error, why?

 
Jason Attin
Ranch Hand
Posts: 232
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI guys apparently this code throws an error, out of memory to be precise

But I don't understand why
 
Henry Wong
author
Marshal
Pie
Posts: 22085
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Well, you are adding the same string to the array list, an infinite number of times.  Granted all the strings are the same string objects, but a potential infinitely number of string references do take up real memory space.

Henry
 
Narayana Bojja
Ranch Hand
Posts: 130
4
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jason Attin,



Here, while loop condition is  true. It never ends because while loop condition never becomes false. Within while loop , you are adding string object to ArrayList object. It means adding string object to ArrayList object never ends. At certain time, There won't be memory to add object  then JVM will throw OutOfMemoryError



The above piece of code can't catch OutOfMemoryError. Because OutOfMemoryError and RuntimeException are not related (IS-A) in any way. So JVM terminates the program execution and throws OutOfMemoryError.

Note : We should not catch Errors because Errors are unrecoverable. If You catch there won't be any compile time error.

Hope it helps !
 
Jason Attin
Ranch Hand
Posts: 232
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right, thanks guys, it's clearer now :-)!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic