Java class methods



Introducing Methods in Java Class : Class Concept in Java

  1. In Java Class , We can add user defined method.
  2. Method is equivalent to Functions in C/C++ Programming.

Methods in Java Programming - Syntax of Method in Java

Syntax : Methods in Java Classes

return_type method_name ( arg1 , arg2 , arg3 )
  1. return_type is nothing but the value to be returned to an calling method.
  2. method_name is an name of method that we are going to call through any method.
  3. arg1,arg2,arg3 are the different parameters that we are going to pass to a method.

Return Type of Method :

  1. Method can return any type of value.
  2. Method can return any Primitive data type
int sum (int num1,unt num2);
  1. Method can return Object of Class Type.
Rectangle sum (int num1,unt num2);
  1. Method sometimes may not return value.
void sum (int num1,unt num2);

Method Name :

  1. Method name must be valid identifier.
  2. All Variable naming rules are applicable for writing Method Name.

Parameter List :

  1. Method can accept any number of parameters.
  2. Method can accept any data type as parameter.
  3. Method can accept Object as Parameter
  4. Method can accept no Parameter.
  5. Parameters are separated by Comma.
  6. Parameter must have Data Type

Live Example : Introducing Method in Java Class

class Rectangle {
  double length;
  double breadth;

  void setLength(int len)
  {
  length = len;
  }
}

class RectangleDemo {
  public static void main(String args[]) {

  Rectangle r1 = new Rectangle();

  r1.length = 10;
  System.out.println("Before Function Length : " + r1.length);

  r1.setLength(20);
  System.out.println("After Function Length : " + r1.length);

  }
}

Output :

C:Priteshjava>java RectangleDemo
Before Function Length : 10.0
After Function Length : 20.0

Explanation :

Calling a Method :

  1. r1” is an Object of Type Rectangle.
  2. We are calling method “setLength()” by writing –
Object_Name [DOT] Method_Name ( Parameter List ) ;
  1. Function call is always followed by Semicolon.

Method Definition :

  1. Method Definition contain the actual body of the method.
  2. Method can take parameters and can return a value.

Calling Methods in Java Programming Class Concept