Learn Method In Java

Sharing is healthy !!

Hey guys!! Today we are going to learn method in java.

In this post we will see what is a method and how to use a method in java.

Learn Method In Java: what is a method?

A method is a piece of code which executes some logic. Method is wrapped with a name and can be called whenever required.

Learn Method In Java: how to use a method?

First of all for your information, main is also a method which every java program has.

public static void main(String[] args) {
 
}

In java method, name should not be “main”. Because there should be only one main method in any java program. But other than main and reserved name in java you can define any name to a method.

So, first of all let’s see what is the basic syntax of a method.

public static void first_Method()
{
 
}

In the above syntax first of all we have access specifier “public”. Public keyword tells java that it’s accessible anywhere inside your class. Then static, return value “void”(returns nothing) which is the part of method and then comes the name of the method first_Method(). In these brackets we can pass some parameters but for simplicity i just want to leave them empty. They can be left empty or you can pass parameters. And then in curly braces comes your statements. So this is the simplest kind of method.

Also Read –¬†String toCharArray Method Java Program

Now we can call first_Method() in main method. Here you don’t need to execute or print anything you can just call above method as it is, like this,

public class String_Method {

public static void main(String[] args) {
 
first_Method();

}
 
public static void first_Method()
{
System.out.println("Hello Flower Brackets!!");
}

}

Output:

Learn Method In Java

If you notice we are not directly printing in our main method. But we are calling the function with a function name and then it prints “Hello Flower Brackets!!”. The biggest advantage of using first_Method() function or method is, it will make your code really readable, concise, understandable and make your code look good. You can call a method ‘n’ number of times inside a main method without rewriting the same code.

So the thumb rule is whenever you have the code which you want write again and again then you may wrap it inside a method and this will help you to reduce the lines of code which you write. Method name should be logical so that it’s understandable and then any person who’s reading your code will be able to understand your code.

conclusion:

So this is the basic form of method in java. There are other kinds of methods like method which take arguments, method which returns value which will be covered¬†in the next post. Please stay tuned to our blog “Flower Brackets”.

Sharing is healthy !!

Leave a Reply

Your email address will not be published.