permaculture playing cards*
The moose likes Beginning Java and the fly likes please explain what happens in this code? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "please explain what happens in this code?" Watch "please explain what happens in this code?" New topic
Author

please explain what happens in this code?

shoeb sayyed
Ranch Hand

Joined: Mar 14, 2010
Posts: 48


Thanks,
Shoeb
Matt Cartwright
Ranch Hand

Joined: Aug 25, 2008
Posts: 149

Hi Shoeb,
are you familiar with the concept of operators in programming languages?
Alpesh Rathod
Ranch Hand

Joined: Jan 06, 2009
Posts: 41
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.




Thanks,
Alps
shoeb sayyed
Ranch Hand

Joined: Mar 14, 2010
Posts: 48
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

Joined: Aug 16, 2005
Posts: 14114
    
  16

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
shoeb sayyed
Ranch Hand

Joined: Mar 14, 2010
Posts: 48
thanks Jasper,

I got it, and i wrote the comment by mistake as ZERO
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38472
    
  23
You have some interesting questions which people may ignore if you don't tell us what the thread is about.
shoeb sayyed
Ranch Hand

Joined: Mar 14, 2010
Posts: 48
I will see to it the next time i post Campbell...

Thanks anyways
 
Don't get me started about those stupid light bulbs.
 
subject: please explain what happens in this code?