Functions/ Methods in Java

Functions/ Methods in Java

What are java functions/methods?

A function is a block of code which only runs when it is called.

To reuse code: define the once and use it many times

General Syntax:

public class Main {
    static void nameOfMethod() {
    // code
  }
}

public class Main{ access-modifier return-type method() { // code return statement; } }

method() - name of calling function return-type - A statement that causes the program control to transfer back to the caller of a method. A return type may be a primitive type like int, flaot or void type(returns nothing)

Note: These are the few important things to understand about returning the values;

The type of data returned by a method must be compatible with the return type specified by the method for example if return type of some method is boolean, we can not return an integer

The variable receiving the value returned by a method must also be compatible with the return type specified for the method.

=> Pass by value: example 1:

main() {
   name = a 
   greet(name);
}
static void greet(naam) {
    print(naam);
}
primitive data type like int, short, char, byte etc.(just pass value)
object of reference: passing value of reference variable

example1:

psvm() {
    a = 10;
    b =20;
    swap(a, b);
}
swap(num1, num2) {
    temp = num1;
    num1 = num2;
    num2 = temp;
}

Scopes:

  • function scope: Variables declared inside a method/function scope(means inside the method) can't be accessed outside the method.
  • block scope: Variables initialized outside the block can be updated inside the block
  • loop scope: Variables declared inside loop are having loop scope.
  • shadowing: Shadowing is the practice in Java is the practice of using variables in overlapping scopes with the same name where the variable in low-level scope overrides the variable of high-level scope.
  • Method/Function overloading: This happens when two functions have the same name. This is allowed having different arguments with same method name.

For a more detailed introduction to java programming, I would surely encourage you to check out this wonderful toturial Functions/Methods in Java by Kunal Kushwaha

Feel free to connect with me on github and Linkedin, thank you.