Difference between for and forEach

Check below two constructs :

char[] arr1 = new char[]{'1','2'};
  for (char x : arr1) {
  arr1 = null;

char[] arr = new char[]{'3','4'};
  for (int i = 0; i < arr.length; i++) {
  char x = arr[i];
  arr = null;

Both code compiles, but if you run them, you will find that the first loop terminates normally, while the second loop will throw a NullPointerException.

Output :

Exception in thread “main” java.lang.NullPointerException
at test.process.ThreadTestMain.main(ThreadTestMain.java:27)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s