JavaSE method

Write Methods

  • What is a method like?


Element Value in nap() example Required?
Access modifier public no
Optional specifier final no
Return type void yes
Method name nap yes
Parameter list (int minutes) yes(can be empty)
Optional exception list throws InterruptedException no
Method body { // take a nap } yes(can be empty braces)
  • Access Modifier
    • public
    • private
    • protected
    • default(Package Private)
      • there is no keyword for default
      • in Java, only in switch statement and interfaces, you could find default this key word
  • Optional specifier
    • static
    • abstract
    • final
    • synchronized
    • native
      when interacting with code written in another language such as C++
    • strictfp
      used for making floating-point calculations portable
  • Return type
    a method must have a return type; once return type is defined, return a value must be remembered.

    String example(int a){
    if (a == 4)
    return " ";
  • Method name
    Method name follow the same rules as we define identifier
    $, _, letter, digit, first three can be the first position of the name

  • Parameter list
  • Optional exception list
    public void zeroExceptions() {}
    public void oneException() throws IllegalArgumentException {}
    public void twoException() throws IllegalArgumentException, InterruptedException {}
  • Method body
    public void walk2; // DOES NOT COMPILE