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

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
kaps78
Posts: 1
Joined: Sun Nov 15, 2015 9:49 pm
Contact:

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

Post 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!

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post by admin »

The reasoning is correct. The NPE is not because of str+null. It is because of str.concat because str is null.

misko71
Posts: 1
Joined: Tue Mar 27, 2018 2:51 am
Contact:

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

Post 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 ?

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.

Dreamweaver
Posts: 32
Joined: Mon Dec 29, 2014 4:14 pm
Contact:

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

Post 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

Post Reply

Who is online

Users browsing this forum: No registered users and 13 guests