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

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

Method arguments

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

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.

--

--

--

Software Developer, Java Instructor https://www.techleadacademy.io/

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

weekly.tf #19–0.13 released

WHY CODING IS A GREAT CAREER OPTION

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
Beknazar

Beknazar

Software Developer, Java Instructor https://www.techleadacademy.io/

More from Medium

Unit Testing in Java

OOPs in Java

Dates In Java