java - Unary operator within main and static method -
i have following 2 codes, , in process of knowing how unary operation works within sop, , main method. let me know how values of "i" calculated within main, , when gets within static method.
any detail background operation of things appreciated, need build logic me understand other related codes well.
thanks in advance help.
class r { static int test( int i) { return i--; } public static void main (string[] args) { int i=0; system.out.println(test(i++)); system.out.println(i); = 0; system.out.println(test(i--)); system.out.println(test(i)); } }
result:
0 1 0 -1
second 1 :
class s { static int test( int i) { return ++i; } public static void main (string[] args) { int i=0; system.out.println(test(i++)); system.out.println(i); = 0; system.out.println(test(i--)); system.out.println(test(i)); } }
result:
1 1 1 0
the key understanding programs behavior remember primitive types java uses call value instead of call reference.
thus name i
in test
function not reference same value referenced name i
in main
function.
by example
public static void main (string[] args) { int i=0; system.out.println(test(i++));
what's happening here is:
i's value increased
i++
1next
test
method called old value of i,test (0)
the return vale of
test (0)
printed stdout.
to determine return value of test (0)
take closer @ test
method:
static int test( int i) { return i--; }
what happens here is:
the value passed in referenced name
i
decreasedi--
the old value of returned
as value of 0
passed in resulting return value 0
, value gets printed by:
system.out.println(test(i++));
in main method. next line:
system.out.println(i);
will print value named i
in main stdout. copy of value of i
got passed test
method old value still unchanged. number 1
printed stdout.
now it's you
having shown example how trace program flow first 2 results of code using same pattern should able explain other results yourself.
Comments
Post a Comment