I don't think exception will be thrown as the str+" "+ind expression would not result in a null value and thus a valid string literal "null 0" will be passed in this method call str.concat(str+" "+ind);
And yes, System.out.println(str); in the printData method will result in the NullPointerException. So, the option you have mentioned is correct but the reasoning that you have provided is wrong. Please let me know your comments. Thanks!
About Question enthuware.ocajp.i.v8.2.1443 :
Moderator: admin
-
- Posts: 1
- Joined: Sun Nov 15, 2015 9:49 pm
- Contact:
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v8.2.1443 :
The reasoning is correct. The NPE is not because of str+null. It is because of str.concat because str is null.
-
- Posts: 1
- Joined: Tue Mar 27, 2018 2:51 am
- Contact:
Re: About Question enthuware.ocajp.i.v8.2.1443 :
I can not understand this behavior.
When you access array member inside initData() >> NPE
I changed main() method as follows:
OrderTest ot = new OrderTest();
String[] arr = new String[2];
System.out.println(arr[0] += "str");
System.out.println(arr[0] = arr[0].concat("xxx"));
System.out.println(arr[0]);
When you access same array member inside main() it works normally. Why ?
When you access array member inside initData() >> NPE
I changed main() method as follows:
OrderTest ot = new OrderTest();
String[] arr = new String[2];
System.out.println(arr[0] += "str");
System.out.println(arr[0] = arr[0].concat("xxx"));
System.out.println(arr[0]);
When you access same array member inside main() it works normally. Why ?
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v8.2.1443 :
Because this is not the same code as given in the question. There is no String with value "str" in the code given in the question.
-
- Posts: 32
- Joined: Mon Dec 29, 2014 4:14 pm
- Contact:
Re: About Question enthuware.ocajp.i.v8.2.1443 :
I thing the NPE is because of concate() method.
I try without concate() and is compile&execute well
Of course String is imutable so the output is:
I try without concate() and is compile&execute well
Code: Select all
public void initData(String[] arr){
int ind = 0;
for(String str : arr){
str = str + ind;
ind++;
}
}
Code: Select all
null
null
Who is online
Users browsing this forum: No registered users and 13 guests