Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817
Moderator: admin
-
JaredTse
- Posts: 20
- Joined: Sat Apr 23, 2016 2:52 pm
-
Contact:
Post
by JaredTse »
Can somone please tell me why the following snippet prints
=> 200
=> 100
instead of
=> 200
=> 300
Where am i missing the point ?
Code: Select all
class FieldScope2 {
public int testA = 100;
public void methodA(){
testA =+ 100;
}
}
public class FieldScope extends FieldScope2 {
public int testA = 200;
public void methodA(){
testA =+ 100;
}
public static void main(String [] argv ){
FieldScope fieldScope = new FieldScope();
System.out.println( fieldScope.testA ); // => 200 ok
fieldScope.methodA();
System.out.println( fieldScope.testA ); // => 300 Expected
}
}
-
admin
- Site Admin
- Posts: 10036
- Joined: Fri Sep 10, 2010 9:26 pm
-
Contact:
Post
by admin »
Before one can try to explain the issue to you, you need to first explain why do you expect 300 to be printed?
-Paul.
If you like our products and services, please help us by posting your
review here.
-
JaredTse
- Posts: 20
- Joined: Sat Apr 23, 2016 2:52 pm
-
Contact:
Post
by JaredTse »
1, Well fieldScope is an object reference of type FieldScope and is pointing to FieldScope;
2, Now when I do fieldScope.testA i get back 200 , since the object reference is of type FieldScope, and it uses its own field testA,
3, Again the methodA increment the field by 100, fieldScope. now I would expect to see 300, but instead I get 100.
Thats my logic.
-
JaredTse
- Posts: 20
- Joined: Sat Apr 23, 2016 2:52 pm
-
Contact:
Post
by JaredTse »
It worked, it was a a bug I have introduced whilst incrementing the number by 100.
instead of += I have used =+, which I assume is doing deduction or I am not sure.
Maybe someone can shade light as to why this is the case.
-
limaia
- Posts: 1
- Joined: Fri May 06, 2016 8:59 am
-
Contact:
Post
by limaia »
JaredTse wrote:It worked, it was a a bug I have introduced whilst incrementing the number by 100.
instead of += I have used =+, which I assume is doing deduction or I am not sure.
Maybe someone can shade light as to why this is the case.
int i =0;
- i += 2 is equivalent to i = i +2
- i =+ 2 is equivalent to i = (+2) that is equivalent to i=2
Users browsing this forum: No registered users and 46 guests