Ticker

6/recent/ticker-posts

JAVA - Methods, Static methods | Non-Static methods

Java Methods

Methods contains group of statements 

A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name 

It increase the readability and reusability of code 

In java we call functions has methods, because hear the methods can be written only inside class but not outside the class like in C++ 

Methods are used to tell the behaviour of the object

Syntax 

<return type><method name>(arguments) 

        // Body of method 
        //return keyword with returning value 

Example 

int add() 

    return 5+6; 

In the above example the add() method returns 11, which of type int 
void drink() 

        System.out.println("Drinking water.....!"); 

In the above example the drink() method will not return anything so the return type is void. 

Note: 

If we specify any return type while declaring than that method should return that type value. 

The return statement should be present at the last. In the séance the return statement should be logically the last line in the method block 

If the return type is void means we need not to specify the return statement at the last. Compiler itself is going to write the return statement. If at all if you need to specify means do has below.(an empty return statement) 

void drink() 

        System.out.println("Drinking water.....!"); 

        return; 

The method can have empty return statement, if the return type of the method is void. But that return statement should not even return 0(zero) , ‘ ’(space) or null  Advantage of methods is code reusability 

There are two types of methods 

  • Static methods 
  • Non-Static methods 

Static methods : These methods a declared using the static key word  Static method can be accessed directly by just using the class name. From static methods we can’t accesses non static members directly 

Non-static methods: These methods are declared without static keyword. Non-static methods can accesses static members directly 

Non-static members are called by creating the instance of the class or by using the object reference of the class

ALSO SEARCH:

"static and non static methods in java"

"static method in java"

"non static method cannot be referenced from a static context"

"non static method in java with example"

"how to access non static variable in static method java"

"static and non static members in java"

"static and non static in java example"

"non static method example"