/ W3SCHOOLS

W3schools - Method

이 페이지는 다음에 대한 공부 기록입니다
Lecture에서 배웠던 내용을 복습하며 작성했습니다

찾으시는 정보가 있으시다면
주제별reference를 이용하시거나
우측 상단에 있는 검색기능을 이용해주세요

Java Methods

Is a block of code which only runs when it is called

Can pass data, known as parameters, into a method

Be used to perform certain actions, known as functions

Why use method? To reuse code

Create method

Must be declared within a class

It is defined with the name of the method, followed by parentheses

public class Main{
  static void myMethod(){
    codeblock
  }
}

static

  • means that the method belongs to the Main class

void

  • means that this method does not have a return value

myMethod

  • name of method

Call method

Write the method’s name followed by two parentheses and semicolon

Can also be called multiple time

Java method parameters

Information can be passed to methods as parameter

parameters act as variables inside the method

parameters are specified after the method name, inside the parentheses

Can add as many parameters as you want, just separate them with a comma

when a parameter is passed to the method, it is called an argument

when multiple parameters

  • the method call must have the same number of arguments as there are parameters and the arguments must be passed in the same order

Return

“void” keyword indicates that the method should not return a value

if you want the method to return a value, use a primitive data type(int char…) instead of void and use the “return” keyword inside the method

static int myMethod(int x) {
  return 5 + x;
}

Method overloading

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

int myMethod(int x)
double myMethod(float x)
float myMethod(double x, double y)

Scope

In java, variable are only accessible inside the region they are created

method scope

  • variables declared directly inside a method are available anywhere in the method

block scope

  • variables declared inside blocks of code are only accessible by the code

  • between the curly braces, which follows the line in which the variable was declared

  • it can belong to an if, while, or for statement.
  • In the case of for statements

    • variables declared in the statement itself are also available inside the block’s scope

Recursion

Is the technique of making a function call itself.

public class Main{
  public static void main(String[] args){
    int result = sum(5, 10);
    System.out.println(result);
  }
  public static int sum(int start, int end){
    if(end > start){
      return end + sum(start, end  1);
    }else {
      return end;
    }
  }
}