Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

please explain what happens in this code?

 
shoeb sayyed
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Matt Cartwright
Ranch Hand
Posts: 152
Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shoeb,
are you familiar with the concept of operators in programming languages?
 
Alpesh Rathod
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The value 2 in stored in val variable and not zero

And the operation val+ = 3 is val = val +3 which result in val = 5

The end result of i is 2.



 
shoeb sayyed
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey thanks

actually initially i have put 0 in it

i got it

but just tel me when val+=3;
i=new Integer(val); // here the value of i is 5, right

but as the method doesn't return anything so the value of i would remain 2 right
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15495
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's look at this step by step and let's begin on line 13.

Line 13: You create a new Integer object with the value 2.
Line 17: You call the method add3 with i.
Line 5: You create a new local variable named val with the value of i, which is 2 (not zero, as you write in the comment!).
Line 7: x += y is the same as x = x + y. So this is val = val + 3, so that val has the value 5 now.
Line 8: You make i refer to a new Integer object with the value 5.

Note that the i inside the add3 method is NOT the same i as in the main method - variables are passed by value in Java. Line 8 has no effect, because the i of the add3 method is immediately thrown away. The output of the program will be 2, the original value of i in the main method.
 
shoeb sayyed
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Jasper,

I got it, and i wrote the comment by mistake as ZERO
 
Campbell Ritchie
Sheriff
Pie
Posts: 50277
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have some interesting questions which people may ignore if you don't tell us what the thread is about.
 
shoeb sayyed
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I will see to it the next time i post Campbell...

Thanks anyways
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic