[Java] Java method

1 minute read

Introduction

Hi, I was spammed in my last post on the array.

method

・Methods are parts or game skills (classes are like statuses *to my sense). *If you do not write it inside the {} (block) of the class, it will not work**. ・When you use the method to do the same process, you can call it without writing the same process.

  • Easy to view and manage the code.

kane.java


public static void method name () {
 Processing to be performed;
}

kane.java


class Main{
   public static void main(String[]args) {
    banana(); //() is required.
   }

   public static void banana() {
    System.out.println("yellow");
   }
}

・What is the return value? The value (data) returned from the called method to the calling method is called return value or return value.

public static void main(String[] args) { }

  • If a java program is executed, it automatically starts from the main method. **.
  • The main method gives instructions to each method, and each supported method executes individual processing.

・If you don’t forget to write it, now it’s K.

argument

· Something like additional information to give to the method.

  • When calling a method, the value can be passed from the caller. ・The value can be used in the method passed by it.

In order to define the method that can receive the argument, specify the variable (formal argument (Karihikisu)) that will be the box for receiving the argument in the method definition part and specify the dummy argument in () of public static void banana(). specify. Like the variable definition, the dummy argument must specify the data type.

kane.java


class Main{
   public static void main(String[]args) {
    banana("red");
   }

   public static void banana(String color) {// Specify the data type
    System.out.println("The color of this banana is "+ color + ".");
   }
}

() is required even if there is no information to be handed over, so be sure to enter it.

・When passing multiple arguments

kane.java


class Main{
   public static void main(String[]args) {
    banana("Philippines", 5);
   }

   public static void banana(String origin, int year) {
    System.out.println("This banana is" + origin + "productive" + year + "year.");
   }
}

Execution result
This banana is from Philippines for 5 years. // it's rotten

Return value

Overload

Tags:

Updated: