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

public static void printHello() {

Method arguments

  • 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.
Does not compile

Method return type

  • 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.
  • We can use our method that returns something and assign the return value to the same variable type.




Software Developer, Java Instructor

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Simple Phyton Codes : Palindrome Checker

Accelerate building Integrations with AWS IoT and myDevices Cayenne

Web Scraping and Automated Downloads with Python’s Beautiful Soup Package

Project update: Coin Distraction

Kent C. Dodds on How to Build Better Website with Remix

Clone of Zoom Car Website using EJS #19–0.13 released


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


Software Developer, Java Instructor

More from Medium

Unit Testing in Java

OOPs in Java

Dates In Java