Methods, Variable and Block

A method is something like a subprogram, which when invoked returns a value. In other words, a method is a collection of words or commands that joined to perform a function. Once this function or task is completed, it sends a result back to the caller.

It can even complete an operation without returning a value, and allows us to use the same code without actually having to type the entire code again and again. Methods are also known as instance members.


Syntax :-

[Modifiers]  return_type  Method_name ( Arguments1, array2---)
{
      ---
}
class can contain two types of methods:
  • Instance methods
  • Static method

  • Example:

    Instance Method vs Static Method

    Instance method Static method
    • When you define a method inside a class without a static keyword, it is called the instance method or the non-static method
    • When you define a method with static keyword then it is called the static method
    • Instance methods must be called by you explicitly. You can call using reference variables which contain the object.
      For example: (Hello h=new Hello())
    • Static methods must be called by you explicitly. You can call using the following methods:
      1. With classname
      2. With reference variable without initialisation. For example: A a=null;.
      3. With reference variable which contains object

There are two types of variables, local and global. Read the following to get more details about them.

Global Variables:

  • Global variables are initialised automatically
  • It is defined outside of method
  • A static keyword can be applied to global variable
  • Its scope is across class and can be used anywhere


Local Variables:

  • Variables declared inside method or constructor or any block are called local variables

  • The scope of the local variable is within the method or constructor or block where it is defined

  • Memory will be allocated for the local variable whenever the enclosing block gets executed

  • Local variable is not equivalent to instance variable

  • Local variables cannot be static

  • Local variables cannot be referenced with class name or reference variable

  • Local variables will not be initialised by the JVM automatically, like instance and static variable

  • If you use local variables without initialising, you get compile time errors like ‘variable x might not have been initialised’.

  • Local variables can be final, primitive or reference

  • Block defined inside a method or block or constructor is called a local block
  • A local block will be executed whenever the enclosing methods or constructor or block is executed
  • Local blocks are not equivalent to instance block
  • Local blocks cannot be static
  • You can write local blocks inside a method or constructor or block, and it can be nested

Example