Methods in Java
Hello readers, in today’s topic, we will discuss methods in Java. These are fundamental concepts that must be remembered before writing a Java program. Before these, we also discussed Decision making & Loop Control in Java 2022, if you don’t know Hurry up Now! Previously we also described briefly various topics of Java such as Operator in Java, Data types of Java, Difference between C++ & Java, and many more which are really helpful for your better understanding. So without wasting time let’s dive into our topic:
Methods in Java
A method is a set of code or some statement that only runs when it is called by the programmer.
You can directly pass data to the method, which is known as the parameters of a method.
Methods are used to perform many actions, the method is also known as functions.
Why do we use methods?
We use a method to reuse the developer coding time and make it easy for the developer. It means we have to define or write the code at once and use it at various times. Sometimes our program is bigger in size and we want to separate the logic of the main method from other methods.
Syntax of Method:-
A method in Java must be declared/written within a class. The way of defining a method is it declares the name of the method followed by two parentheses (). Because java is an object-oriented programming language we need to write the method inside some class.
Syntax: –
datatype/return type method_name(){ //body of the method; //statement; //code; }
Example:-
public class main{ static void sum(int a, int b){ int c = a+b; return c; } } In the above progra
- In the above program here sum() is the name of the method.
- In sum(int a, int b) int a and int b are the parameters of the method.
- And static means that the method belongs to the main class and not an object of the Main class.
- void means here in this method it does not have any return value.
Calling a Method
In Java a method is called by creating an object of the class in which the method is present is followed by the method call.
Oraltadala obj = new Oraltadala(); //object creation obj.sum(a, b); //Method call through the object
A method can also be called multiple times. The value from the method call (a & b) is copied to the a & b of the function sum(). Thus even if we modify the values a and b inside the method, the values in the main method will not change.
What are methods in Java for example?
A Java method is a collection of statements or code that are grouped together to perform an operation. When you call the System. out. println() method, for example, the system actually executes several statements in order to display a message on the console.
2 thoughts on “Method in java”