Methods in Java

it’s useful to think that method is a separate program
  1. Method overview.
  2. Method arguments.
  3. Method return type.

Method overview

A method is a block of code that can be executed when it’s called by its name. The methods are actions in the program. Also, it’s useful to think that method is a separate program that has input, process, and output.

in Main.java
public static void printHello() {
System.out.println("Hello!");
}

Method arguments

The method argument is the way we pass our input data to our method. In our first example, the printHello() method didn’t have arguments. So when using it, we didn’t have to pass any data.

in Main.java
  • We have to predefine our argument data type. In our case, we have one String argument. As you can see, when we use our method we actually pass the String value. It will not compile if we pass different data types, for example int.
  • We used our method three times in the above program. And we have three different outputs. When used our method as printHello("John"); program printed Hello John so the argument name will take a value "John". When it’s called as printHello("Alex") on line 7 it will print Hello Alex because we gave a different value to our method. So that’s how we pass data into our methods via method arguments.
  • There is no limit to the number of arguments. Good practice to keep it up to 3 or max 4 arguments for a method. If you need to pass more data you can use Array or pass them as Object. We will learn about them the future articles.
in Main.java
Does not compile
in Main.java

Method return type

As we discussed a bit, methods can return some data back. So far we have been using only void methods. They just perform actions and do not return any data back.

in Main.java
  • If you specify that method returns something then it must return. Code will not compile if you are not returning a promising data type.
  • To return something we use return keyword. It’s important to remember that after returning, our program will exit from the method. You cannot have other statements after the return statement unless the return statement is under some condition.
  • We need to return the exact type that we specified as the method return type.
in Main.java
  • We can use our method that returns something and assign the return value to the same variable type.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store