Page 1 of 1

About Question enthuware.ocajp.i.v8.2.1443 :

Posted: Thu Nov 19, 2015 3:14 pm
by kaps78
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!

Re: About Question enthuware.ocajp.i.v8.2.1443 :

Posted: Thu Nov 19, 2015 8:35 pm
by admin
The reasoning is correct. The NPE is not because of str+null. It is because of str.concat because str is null.

Re: About Question enthuware.ocajp.i.v8.2.1443 :

Posted: Tue Mar 27, 2018 3:00 am
by misko71
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 ?

Re: About Question enthuware.ocajp.i.v8.2.1443 :

Posted: Tue Mar 27, 2018 5:44 am
by admin
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.

Re: About Question enthuware.ocajp.i.v8.2.1443 :

Posted: Sun Jul 19, 2020 12:14 pm
by Dreamweaver
I thing the NPE is because of concate() method.

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++;
        }
    }
Of course String is imutable so the output is:

Code: Select all

null
null