methods and returning values

this code comes from my textbook and i don't follow the explanation of it.

in the sub method for example, the variable num gets divided by two, but as far as i can see num has no value, whereas i see the number variable has the value of 25.

can anyone help me with the basics here?

thanks

publicclass ReturnValue

{

publicstaticvoid main(String[] args)

{

int number = 25;

System.out.println(number+" is " +sub(number) );

if( sub2(number) )

System.out.println(number+" is above 10");

}

publicstatic String sub(int num)

{

return (num % 2 == 0) ?"even" :"odd";

}

publicstaticboolean sub2(int num)

{

return (num >10) ?true :false;

}

}

Output

25 is odd

25 is above 10

[1730 byte] By [mark_8206a] at [2007-11-26 18:01:38]
# 1

When one of those methods is called, the "num" variable pops into existence, and is assigned to the value given as an argument to the method.

Note that it's assigned the value of the argument. That means that the value of number -- 25 in this case -- is copied into the "num" variable. So if one of those methods change the value of "num", then the value of the variable "number" is unchanged.

paulcwa at 2007-7-9 5:31:16 > top of Java-index,Java Essentials,New To Java...
# 2
thanksso if there was another variable int x = 22;i could let the sub method deal with that too?System.out.println(number+ " is " +sub(x) );is that correct?
mark_8206a at 2007-7-9 5:31:16 > top of Java-index,Java Essentials,New To Java...
# 3
sorry i meantSystem.out.println(x+ " is " +sub(x) );
mark_8206a at 2007-7-9 5:31:16 > top of Java-index,Java Essentials,New To Java...
# 4

> thanks

> so if there was another variable int x = 22;

> i could let the sub method deal with that too?

> System.out.println(number+ " is " +sub(x) );

>

> is that correct?

Yes, except for that little typo, that is perfectly correct; isn't parameter

passing cute? ;-) You can also pass literal values or entire expressions

if you want:int x= 42;

sub(x/2);

sub2(21);

// etc. etc. etc.

kind regards,

Jos

JosAHa at 2007-7-9 5:31:16 > top of Java-index,Java Essentials,New To Java...