General form of functions

Edit on Github instead

The general form of any Java function looks like:

<visibility> <returnType> <functionName> (<type parameterName>, <type parameterName> ...){
}

Here's a a more concrete example:

public int addTwo(int favNumber){
    return favNumber + 2;
}

Which could be used like this:

int myNum = 4;
newNum = addTwo(myNum);         // Now, newNum = 6

Let's go through each piece of the general form:

<visibility>

Tells us which objects can call, or use, this method. It can be one of the following keywords:

  • public: all objects can call this method
  • protected: all objects in this class or its subclasses can access this method
  • private: only objects in this class can access the method

Visibility is optional. If you don't specify it, Java defaults to packaged private, meaning it's visible to all classes in the same package

<returnType>

Tells us what type this method will give back. It can be:

  • void
  • int
  • double
  • boolean
  • String
  • Object
  • Or any custom object that you define

<functionName>

What we're calling this function. You can use whatever you like, though it's convention (and helpful to people who might read your code) to choose a verb that describes what the method does.

<parameterList>

A comma-separated list of the parameters the method will use, e.g. int favNum or boolean willRain.

Suggest changes

Related links

URL Topic Source