·  JAVA – Syntax – Terms – Methods


- Info:

  - This tutorial shows how to use methods.


- Additional Tutorials:

  - Methods – Parameters Scope


- What are functions for:

  - Functions are used to avoid to copy-paste block of code that needs to be executed numeros times.

  - Using functions, every time you need to execute that block of code you can simply:

    - call that function by it's name,

    - give it input parameters to work on if it expects any,

    - receive it's return variable if it gives any.


- Specifics:

  - Java function can only exist inside a class, and general term for such function is a method.

  - Java function can't have another function inside it, in other words function nesting is not supported.

  - Java function can only have single return variable.

    To return more then one value you can return collection, like HasMap, or some custom made Object.

  - Values of function parameters are copied into local variables which are visible only inside the function.

    Changes to these local variables have no affect on the values of variables used as parameters.

  - Keyword void before function name indicates that function returns no value.

  - If function returns some Primitive Type or Object, it's name must be placed before function name.

  - Keyword return must be used if function returns some value.

  - Function parameters are defined after function name inside round brackets.

    For each parameter you must define it's type and name.

    Each function has fixed number of parameters, they all have to be given in function call and can't have default values.


- Create & Call:

  - This example shows how to create and call methods with or without parameters or return values.

  - Create JAVA Console Application Test.java



    public class Test {


      public static void main(String[] args) { 


        int    ret      = returnValue  ();     System.out.println(ret     );

        String text     = noParameters ();     System.out.println(text    );

        float  division = parameters   (10,2); System.out.println(division);



      public static void   noReturnValue(){

        System.out.println("This function doesn't return any value.");



      public static int    returnValue  (){

        System.out.print("This function returns int Primitive Type:  ");

        return 10;



      public static String noParameters (){

        System.out.print("This function expects no input parameters. Returns constant String:  ");

        return "Hello";



      public static float  parameters(int p1, int p2){

        System.out.print("This function expects two parameters: "+p1+"/"+p2+"=");

        return p1/p2;