zambonideen
zambonideen

Reputation: 1

Confused about the input arguments line when writing Java functions

public class AbsoluteValue {
    public static int absolute(int n) {
        if ( n >= 0){
            return n;
        }else {
            n = n * -1;
            return n;
        }
    }
    public static void main(String[] args) {
        StdOut.println("Enter the integer that you want the absolute value for: ");
        int number = StdIn.readInt();
        StdOut.println("The absolute value of " + number + " is " + absolute(number));
    }
}

Hello, I am just learning about writing functions, and my teacher is not doing a great job explaining. The goal of this program is to take the absolute value of the inputted number, and it works just fine using the "StdIn, StdOut" library I have.

My confusion comes from how the heck it works. So in the main function, I am asking to enter an integer, it reads that integer and stores it into the variable "number." Then my print statement calls the absolute() function and passes the number argument. My confusion comes from how this all gets translated and what the argument line in public static int absolute(int n) means. Why did I need to pass "int n" there? How did the "n" variable, transform into my "number" variable?

My guess is that whatever argument I pass when I call the absolute() gets moved into the argument line for that method?

Upvotes: 0

Views: 36

Answers (2)

user14387228
user14387228

Reputation: 381

This part

public static int absolute(int n) { … }

says we have a method, called 'absolute', which takes an integer argument, and returns an integer value.

Within the body of 'absolute', where the actual computation is done, the integer argument is referred to by the name 'n'.

All of this is just a definition of a procedure. It does not execute just by being defined.

This

    absolute(number)

is a 'call' to 'absolute' - we are requesting an execution of the method. We supply a value (from 'number') to be used as the value of the formal argument which 'absolute' knows as 'n'.

You can look at it as if 'n' is assigned the value of the expression 'number' immediately prior to 'absolute' being entered.

After 'absolute' is done, the return value is then used in your print call -- which is another method execution that proceeds in a similar manner.

Upvotes: 1

Jose Ludian
Jose Ludian

Reputation: 1

You're right, the int value that you use as argument for the method absolute() will be the value to be processed inside the method.

Upvotes: 0

Related Questions