-1

Can anyone please explain to me exactly what happens internally when we compile and run the below code...

class ObjTest{
    public static void main(String [] args){                    
        while(true){
            String str = new String("Hello");
        }
    }
}
Jonathan
  • 20,053
  • 6
  • 63
  • 70
Pravin
  • 160
  • 6

3 Answers3

3

Each iteration of ths infinite loop creates a new String instance.

The instance created in the previous iteration becomes eligible for garbage collection, so whether you end up with an out of memory error or not depends on whether the garbage collector frees those old instances quicker than the loop creates new ones.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

"while" execute the block statement while the condition is true.

And you are passing "true" making the condition be always true.

It will never stop

WeezHard
  • 1,982
  • 1
  • 16
  • 37
0

You have an infinite loop creating a String object. In every iteration a new object is created so old objects are available for garbage collector.

peterremec
  • 488
  • 1
  • 15
  • 46