1 of 14

Methods in Java

2 of 14

What is a method?

A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions.

Why use methods? To reuse code: define the code once, and use it many times.

3 of 14

The structure of methods in Java

4 of 14

How to call a method?

methodName();

5 of 14

A method sample

public class Main {

public static void methodName() {

System.out.println("I just got executed!");

}

public static void main(String[] args) {

methodName();

}

}

6 of 14

public static void methodName() { }

void means that this method does not have a return value.

7 of 14

Parameters and Arguments

  • Information can be passed to methods as a parameter.
  • Parameters act as variables inside the method.

static void myMethod(String name, int age)

8 of 14

9 of 14

Java return

10 of 14

11 of 14

Write a Java method that prompts the user to enter two double numbers and then returns their average.

12 of 14

Write a Java method that creates and returns a password based on the user's input, specifically the first two letters of their name concatenated with their age: (nameVariable.substring(0,2)--> first 2 letters

Name = Erhan

Age = 41

Password = Er41

13 of 14

14 of 14

Java Method Overloading

With method overloading, multiple methods can have the same name with different parameters:

plusMethodInt(int x, int y)

plusMethodDouble(double x, double y)

plusMethodDouble(double x, double y, int z)