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

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

Moderator: admin

Post Reply
kushalkk
Posts: 1
Joined: Mon Mar 21, 2016 9:13 pm
Contact:

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

Post by kushalkk »

I can't understand the logic behind this question.

String str1 = "one"; String str2 = "two";
System.out.println( str1.equals(str1=str2) );

=> false

as before method is called , str1 is evaluated to "two".
and so shouldn't it be , "two".equals("two");

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

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

Post by admin »

Before str1 is assigned str2, str1's old value has already been used to determine the object on which equals has to be invoke. That is why it will be "one".equals("two"). Had it been ( (str1=str2).equals(str1), the result would have been different.

HTH,
Paul.
If you like our products and services, please help us by posting your review here.

uvsmtid
Posts: 6
Joined: Sat Jun 18, 2016 2:11 am
Contact:

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

Post by uvsmtid »

It was a surprise answer for me too.
Why would reference be evaluated first (before arguments to the method)?
Optimistic optimization (if it has to be eventually evaluated, let's do it first - maybe it is even null to fail fast)?

Nevertheless, quote from specification:
"At run time, method invocation requires five steps. First, a target reference may be computed."
https://docs.oracle.com/javase/specs/jl ... ls-15.12.4

uvsmtid
Posts: 6
Joined: Sat Jun 18, 2016 2:11 am
Contact:

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

Post by uvsmtid »

Actually, everything is simple (then in my previous post) if you think that
the target reference is evaluated first because it is the first (implicit) argument in a function call.

Post Reply

Who is online

Users browsing this forum: No registered users and 45 guests