Let us first understand what 'methods' are:
Def: 'Methods' are pieces of code that take some input, and may return an output.
Remember how in the Hello World program in chapter-3 we declared the 'main' method?
Let us break it down. The general syntax to declare a method is as follows:
access-modifier static return-type name(input)
1. In the previous chapter, we have already seen what access-modifiers are for.
2. 'static' is something that we will discuss later on.
3. return-type: This is the datatype of the output that the function returns.
4. input: what? you don't know what input means?
So now let us see an example:
This is a simple method that takes two integers as input, and displays the sum as output.
To run this piece of code, right-click on the compiled class, and click on 'void sum(...)'.
Now, this method does DISPLAY an output, but it does not 'return' it. This is why it's return-type has been given as 'void'.
In order to RETURN an output from this method, replace the print statement with the following code:
return c;
Now can you figure out what the return-type of the method would be?
That's right. It would be 'int', as the variable that we're returning(c) is of the datatype 'int'.
So change the return-type of the method to 'int', and try running it again.
No comments:
Post a Comment