Methods in Java-how to call a method in java

Introducing Method

In java programming language classes usually consist of two things instance variable and methods.

What is a method in java                                                                 

A method is the block of statements that performs a special task.

Using methods we can avoid rewriting the same code over and over in a sane program.

The method increases the efficiency and reduces the complexity of the program. 

Method Definition in Java

following is the Java method syntax:

Write a program to demonstrate the method in the class

Result

Creating a method in java

to create a method we have to give a method heading and method body.

As you can already see here

How to call a method in java

In the above program, you can see how the method area is called in main().

Object.methodName(parameter list);

is used to call methods from another/same class.

A static method can be called with a Class name or with the object.

ClassName.methodName(parameter list);

Parameterized(overloaded) Method

Write a program to demonstrate the parameterized method in the class.

How to call a method in java
Fig: How to call a method in java

Output

Program to call methods in java Method call with and without agrument and with and without return type

Output

Java Program to pass a object to a method

Student.java

StudentDemo.java contains main method and updateStudent method

Output

Passing array as argument in java method

Output

How to call a void method in java

A void method is a method without a return type. Here public void hello() is a void method it is not returning any value.

To call a void method we follow these steps

  1. Create object of class
  2. call the method with object name

How to call a static method in java

to call the static method we can use the following method

  1. Using object as above program does
  2. Using ClassName.methodName as below program

Instance method java

A method associated with the object is known as an instance method.

In the above example hello() is declared as public void hello() this method is an instance method of the class. This is called using the object of the class.

Method vs function java

Method and functions both are pieces of code that is called by name[ref]. For more details see here

How to call main method in java

In java main is a starting method and its syntax is public static void main(String [] args).

public means it can be accessed from any were.

static means this method can be accessed with class. It can be invoked without using the object of the class.

void – this method doesn’t return any value

main – function name.

The main method is automatically get called by JVM where we run our program.

how to call a method in java from another class

Read More

Method Overloading in Java