What is a Method?

  • Function or sub-code that is associated with a class in object-oriented programming
  • Can contain a set of codes that performs an action
  • It can also take an input and return an output based on the user

Creating a Method

  • A method is created within a class
  • It is defined with the name, followed by ()
  • An example of a Java pre-defined method is System.out.println()

Example Code

public class Main {
    static void ExampleMethod(){ // ExampleMethod is the name of the method; static means that the method belongs to the Main class and not an object
        System.out.println("Hi!");
    }
}

Calling a Method

  • With Java, you can call a method by writing the method's name and then having (); after it

Example Code

public class Main {
    static void ExampleMethod() {
      System.out.println("Hello AP CSA!");
    }
  
    public static void main(String[] args) {
      ExampleMethod();
    }
  }
  
  // Outputs "I just got executed!"

Hacks

  • Fill in the missing code:

static void myMethod() { System.out.println("I just got executed"); } public static void main(String[] args) { __; }

  • Describe what the Method does: public String myMethod(String s,int i){ String r = ''; for(int j = 0; j < s.length(); j++) {
      r += (char)(s.charAt(j)+i);
    
    } return r; }