Difference between for and forEach

Check below two constructs :

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

char[] arr = new char[]{'3','4'};
  for (int i = 0; i < arr.length; i++) {
  char x = arr[i];
  System.out.println(x);
  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 :
1
2
3

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

Advertisements

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