Functions
Defining and calling functions
In Java, a function is called a method. You can define a method by specifying its name, return type, and parameters. Here's an example:
In the above example, we define a method called add
that takes two integer parameters x
and y
, and returns their sum. We call the add
method in the main
method, passing in the arguments 1 and 2. The add
method returns the sum of the two arguments, which we assign to the sum
variable. We then print the value of sum
to the console.
Parameters and return values
Methods in Java can have zero or more parameters, and can return a value or be void (i.e. not return anything). Here's an example of a method with no parameters and no return value:
In the above example, we define a method called sayHello
that takes no parameters and returns nothing (i.e. void). We call the sayHello
method in the main
method, which prints "Hello!" to the console.
Here's an example of a method with multiple parameters and a return value:
In the above example, we define a method called max
that takes two integer parameters x
and y
, and returns the larger of the two values. We call the max
method in the main
method, passing in the arguments 3 and 7. The max
method compares the two arguments and returns the larger value, which we assign to the result
variable. We then print the value of result
to the console.
Function overloading
In Java, you can define multiple methods with the same name but different parameter types or numbers. This is called function overloading. Here's an example:
In the above example, we define two methods called add
with different parameter types (integers and doubles). We call the add
method with integer arguments in the first call, and with double arguments in the second call. The Java compiler selects the appropriate method based on the argument types, allowing us to use the same method name for different types of calculations.
That's an overview of functions (methods) in Java, including defining and calling methods, parameters and return values, and function overloading. Functions are a fundamental building block of Java programming, allowing you to write reusable code and break up complex programs into smaller, more manageable pieces.
Last updated