Ask a Teacher

what are methods in java ? explain with the help of an example.

Java programs have methods that have a name and contain a set of statements or instructions. In this lesson, we'll learn how the Java programming language uses methods and the rules and syntax we need to employ when using them.

In the Java programming language, a method is a section of the program that contains a set of instructions or code. In a Java program, similar to a cake recipe, a method has a set of instructions. When the method is called, the set of instructions within the method is executed.

  1. public int addNumbers(int x, int y) {
  2.  int z = 0;
  3.  z = x + y;
  4.  System.out.println(z);
  5.  return z;
  6. }

Here, the name of the method is addNumbers. When the method addNumbers is called, the code within the method is executed, and the variable z is printed.

comments powered by Disqus