Methods/ Functions in JAVA

Properties of an object are represented through or by variables.

Behaviours of an Object is represented by methods. Methods are the collection of statements which can be called in your program in order to perform some task like println() is called when we want to print something on the display.

These methods contain a bunch of statements or instructions, this instruction may or may not accept the values/ parameters from the program’s variable, and this instruction may or may not return some value to the program.

According to the return type and accept parameter, it can be divided into four types:

  1. Methods which do not accept parameters and do not return any value.
  2. Methods which accept parameters but do not return value.
  3. Methods which accept parameters and return value
  4. Methods which do not accept parameters but return value.
Syntax of Method: 
             access_modifier return_type method_Name( parameter if any ){
             // statements/ instructions
             return value if any according to return_type
             }

Here

Access modifiers are used to set access levels for classes, variables, methods, and constructors. The four access levels are −

  • Visible to the package, the default. No modifiers are needed.
  • Visible to the class only (private).
  • Visible to the world (public).
  • Visible to the package and all subclasses (protected).

Return type that returns some value can be any type like int, float string etc.

Parameters can be one or more and can have a type of int, char, float etc.

Example:
public int sum(int a, int b) {
     int c=0;
     c=a+b;
 return c
}
Note: is no return_type is there for method then void is used.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: