Methods in Java
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.
The structure of methods in Java
How to call a method?
methodName();
A method sample
public class Main {
public static void methodName() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
methodName();
}
}
public static void methodName() { }
void means that this method does not have a return value.
Parameters and Arguments
static void myMethod(String name, int age)
Java return
Write a Java method that prompts the user to enter two double numbers and then returns their average.
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
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)