Java's logic concerning methods that return values and their parameters

Java methods don't require return statements to match their parameters. Why?

Consider this trivial method that takes three parameters, x, y and z. The method works when only one return parameter is used (i.e. return x, y, or z). Why wouldn't Java require return x, y, z; or something like that? I'm a Java beginner so maybe I'll learn why when we get to OOP principles. Anyway, I'm curious if there is a logic behind it or that's just Java. Thanks.

public static int someNumbers(int x, int y, int z) {

    if (y > z) {
       System.out.printf("%d is greater than %d", y, z);
    } else {
       System.out.printf("Number three is %d", z);
    }   
    return x;   
}

Answers


Parameters and Return types don't really have any relation to each other. A method may have 0 or more parameters of any arbitrary type.

public int someMethod(int x, String y, Object z) {
   //Does something
    return x * 5 - 10;
}

But it may only have 0 or 1 return values. Where 0 return values must be defined as void:

public void someMethod(int x, String y, Object z) {
   //Does something but returns nothing
}

When needing to return more than 1 value, such as 2 Integers, you could create an Object holding these values. This is kinda what defines Java as an Object Oriented Language.

class IntegerHolder{
    int firstValue;
    int secondValue;

    //This is a constructor, it creates the object.
    public IntegerHolder(int first, int second){
        firstValue = first;
        secondValue = second;
    }
}

public IntegerHolder someMethod(int x, String y, Object z) {
    return new IntegerHolder(x, x * 2);
}

I do advise to read up on some basic Java however. There are hundreds of resources around the web.


A well defined function can have only one output. It is a such a relationship between input and output that you can give multiple input but it will give only one output.

Java function definition just follow this rule.You can use some other features of java in order to get more than one result at a time. But should return on output as per the definition of function.You can also read this:

https://math.stackexchange.com/questions/271613/why-is-a-function-defined-as-having-only-one-y-value-output


Need Your Help

Why can't read data from blocks with PAGE_GUARD protection?

windows operating-system virtual-address-space readprocessmemory virtualquery

I read data from address space using ReadProcessMemory function. I try read from all blocks that have MEM_PRIVATE type. But i get error (function returns 0) when that block have PAGE_GUARD protecti...

After login, should all pages be https?

php security encryption https cryptography

This will be a bit difficult to explain but I will try my best. There is a website that has the login form on every page with username/password fields. These pages are not using SSL. After the user...