Java Class Methods With Examples

Java Class Methods With Examples


A method is a collection of set of statements, and methods are used to break a complex program into small parts- these small parts also known asprocedure, modules, or subprogram.

Methods are used to

Note -

  1.  Every method must have a return type.
  2. Java does not support nested method.
  3. Method parameters can not have default value.
  4. A method in java may or may not contain parameter.

Why we need Methods -

So if you want to perform that particular job then you can simply call the method and leave the rest to it.

For example, say you have problems in your television set. So in this case you will call the TV mechanic and rest assured that he will fix the problem. TV mechanic can be thought of as a method who has entire set of code written in him to fix any problem in television.

Same television mechanic can be called by different person.

Advantage of Methods

  • It increases re-usability of the code thus also reduce size of the code.
  • Complex problem can be modularized with the help of method.
  • In case code is written without using method, it will grow very large in size and thus would also become difficult to test, debug and maintain the code.

Class Methods are catogarised into four(4) Types -

  1. Non-Parameterized with non-Value returning.
  2. Parameterized with non-value returning.
  3. Parameterized with Value returning.
  4. Non-Parameterized with Value returning.

1. Non-Parameterized with non-Value returning

When a method does not take any argument, or parameter within parenthesis, and does not returns any value is called Non-Parameterized with non-Value returning method.

Example - Create a method that read a number from user and display code of no.

Output :

2. Parameterized with non-value returning

A method that takes a variable as argument or parameter, but does not return any value called Parameterized with non-value returning method.

Example - we will modify the previous example

Output :

3. Parameterized with value returning

A method that takes a variable as argument or parameter, but does return a value called Parameterized with value returning method.

Example -modifying in previous example -

Output :

4.Non - Parameterized with value returning

A method that does not takes any variable as argument or parameter, but does return a value called Parameterized with value returning method.

Example -

Output :