Methods

Void Methods

  • A method that executes some action, but does not return anything
    • These are similar to functions in other languages
  • What are methods?
    • A collection of statements that perform a specific action that can be called as many times throughout the code
  • Syntax of a void method
  public static /datatype/ methodName (/parameter/){
    //statements
  }
  • Examples
  //this method will draw out the letter K.
  public static void k(){
  System.out.println("* *");
  System.out.println("* *");
  System.out.println("**");
  System.out.println("* *");
  System.out.println("* * ");
  System.out.println();
  }

Calling a Void Method

  • To call a void method, you simply go to the main method and write the method name followed by a set of parentheses.
  public static void main (String [] args){
    methodName();
  }
  • Example
  //this would call three methods: k, a, & r
  public static void main (String [] args){
    k(); 
    a();
    r();
  }

Non-Void Methods

  • Methods with return values
  • What are return values?
    • values that are returned to the main method after being calculated/manipulated in a custom method
    • return types can be primitive or reference
    • The main differences between non-void and void is how you call the method
  public static int findMax(int n1, int n2){
      //statements
      //return statement **should be very last!
  }
  • return types and parameters do not have to match

    Calling a Non-Void Method

  public static void main (String [] args){
      int var = methodName();
      System.out.println(var);
  }
  • ^^You must have a return statement at the end of your method^^