How do methods work in java
These are optional, method may contain zero parameters. Here is the source code of the above defined method called min. For using a method, it should be called. There are two ways in which a method is called i. The process of method calling is simple.
When a program invokes a method, the program control gets transferred to the called method. The methods returning void is considered as call to a statement. The void keyword allows us to create methods which do not return a value. Here, in the following example we're considering a void method methodRankPoints. This method is a void method, which does not return any value. Call to a void method must be a statement i. It is a Java statement which ends with a semicolon as shown in the following example.
While working under calling process, arguments is to be passed. These should be in the same order as their respective parameters in the method specification. Parameters can be passed by value or by reference.
Notice the line,. Here, we have called the method by passing two arguments num1 and num2. Since the method is returning some value, we have stored the value in the result variable. Note : The method is not static.
Hence, we are calling the method using the object of the class. A Java method may or may not return a value to the function call. We use the return statement to return any value. For example,. Here, we are returning the variable sum. Since the return type of the function is int. The sum variable should be of int type. Otherwise, it will generate an error. In the above program, we have created a method named square. The method takes a number as its parameter and returns the square of the number.
Here, we have mentioned the return type of the method as int. Hence, the method should always return an integer value. Note : If the method does not return any value, we use the void keyword as the return type of the method. A method parameter is a value accepted by the method. As mentioned earlier, a method can also have any number of parameters.
If a method is created with parameters, we need to pass the corresponding values while calling the method. Here, the parameter of the method is int. Hence, if we pass any other data type instead of int , the compiler will throw an error. It is because Java is a strongly typed language. Insert the missing part to call myMethod from main.
We just launched W3Schools videos. Get certified by completing a course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:. Report Error. The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.
All rights reserved. Hide TOC. Classes and Objects. Passing Information to a Method or a Constructor. Summary of Creating and Using Classes and Objects.