Skip to main content

How to call a method in Java

How to call a method in Java

In this post, we will learn how to call a method in Java. This is a useful “chunk” of code that you can call from anywhere else in your program, thus preventing you from needing to write out the same lines of code over and over.

By designing code this way, developers can create far more modular and portable programs and save significant time typing out code.

How to call a method in Java – the basics

To call a method in Java, you type the method’s name, followed by brackets.

For example, the following will call a method called “helloMethod()”:

helloMethod();

In order for this to work though, we first need to create our helloMethod() method. We can see what helloMethod might look like, here:

public static void helloMethod() {

    System.out.println("Hello world!");

}

This code simply prints “Hello world!” to the screen. Therefore, any time we write helloMethod(); in our code, it will show that message to the screen.

If you ever want to change the message being displayed, you will only have to change it once – rather than every single time you used it in the code.

How to create methods in Java

Let’s rewind a moment and take a closer look at the method we created. Why does it look the way it does?

To build a method, we use a number of statements to define that method. In the previous example:

  • Public – Means that the method is accessible to other classes outside of this one
  • Static – Means that the method belongs to the class and not the instance of the class
  • Void – Means that the method does not return a value

If none of that makes any sense to you, don’t worry! Most new developers will be able to use “public static void” for the majority of their methods and won’t have to worry. That said, we’ll address two of these phrases in the coming sections.

It is considered good practice to name Java methods using “camel case.” As we aren’t allowed spaces, camel case gets around this by capitalizing every word except the first one. Methods should generally be verbs (though I have bent that rule here!).

See also: An introduction to Java syntax for Android development

After we’ve named our method, we use brackets in order to add any arguments. An argument is a variable that we wish to pass from one method to another. Variables are values represented by words. Again, if that’s confusing, then just adding two closed brackets is fine.

You then open the code block using “{“. All the code that follows should be indented, and will be part of the method and will run when you call that method.

How to use arguments when calling a method in Java

As mentioned, we can place arguments inside of the brackets when defining our methods. This allows us to pass variables, and therefore values, between methods.

For example, a “String” is a type of variable that holds alphanumeric characters. We create a string by using the word “String” followed by the name.

Now, whenever we call that method, we need to add the value we want to use in the brackets.

helloClass.helloMethod("Hello there!");


public static void helloMethod(String helloMessage) {

    System.out.println(helloMessage);

  }

How to call a method from outside the class

A public method is a method that can be called from outside your class. To do this, you use the following syntax:

nameOfClass.nameOfMethod(arguments)

For example:

class Main {

  public static void main(String[] args) {

    helloClass.helloMethod();

  }

}




class helloClass {

  public static void helloMethod() {

    System.out.println("Hello world!");

  }

}

However, if we wanted to prevent this from working, we would simply replace the word “public” with the word “private”.

How to return values

Finally, we can return specific values from our methods. Let’s see how this might be used.

Let’s say we decide we want the method to provide our greeting but not display it onto the screen. Thus, we might make the method return a string. To do this, we change the word “void” for the type of variable we want to return, and we add “return value” at the end of the method.

This changes how we call a method in Java, because we can simply insert the name of the method in-line in our code, as though it were a variable:

class Main {

  public static void main(String[] args) {

    System.out.println(helloMethod());

  }


  public static String helloMethod() {

      return "Hello there!";

  } 

}

If you’re still wondering what all that “static” stuff is about, then we recommend reading up on classes and objects over at the official Java Documentation from Oracle.

Alternatively, why not check out our list of the best places to learn Java. There you will learn about objects, classes, and much more besides!



source https://www.androidauthority.com/how-to-call-a-method-in-java-1149853/

Comments

Popular posts from this blog

4 Surprising Ways Artificial Intelligence will Empower Consumers

Ever wonder what makes Siri search the items inside the iPhone and on the web by recognizing your voice? How does Google listening work? Artificial Intelligence and data science have already infused in this consumer-oriented generation, but we have not realized it yet. It has been quite a while that natural language processing, speech recognition, and gesture recognition system took over the market with their all new features, but what are the new things in AI that are yet to come? Few amazing transformations are: Retailing sector to become AI-ready Voice Recognition will change the game Search engines to become smarter Machine learning to bring revolutionary changes Recently we got to learn about a verbal spat between Elon Musk and Mark Zuckerberg over the probable risk and opportunities brought by AI . Believe it or not, but we already accustomed to Artificial Intelligence and probably waiting to witness jaw-dropping inventions. Some of AI inventions we have known till yet are: Mach

How to unhide or show folders in mx player list

In this blog post, I tell you about how to Show or Hide folders from MX player list. There are two methods to Show folder from MX Player list. Method 1: Unhide / show folders If you want to temporarily Show / Unhide hidden folder from MX Player list, then go to Settings and untick Recognize .nomedia ".  Method 2: Permanently unhide / show folder: Open memory by any file explorer and I recommend X-Plore, and open the folder that is Hidden and find the file " .nomedia ". If you didn't find it, you should first enable "Show files hidden files that starts with .(dot)". Delete the file and you just need to refresh MX Player list to take changes. Note: MX Player always hide those folders which file " .nomedia " exists.

How to use arrays in Python

Arrays in Python give you a huge amount of flexibility for storing, organizing, and accessing data. This is crucial, not least because of Python’s popularity for use in data science. But what precisely is an array? And how do you use arrays in Python? Also read: How to use dictionaries in Python Read on, and we’ll shed some light on the matter. What is an array? An array is a way to store multiple values in a single variable. That means that you can use a single “reference” in order to access your data. A list is also an example of a variable that stores multiple values, but has some slight differences. When using lists in Python, you store a series of values each with a numbered index. For example, this is how you would create a list of fruits in Python: fruits = [“apple”, “orange”, “pear”, “nectarine”] If we then say: print(fruits[3]) We will see “nectarine” appear on the screen (the first entry is stored as “0”). Also read: How to use lists in Python This is not an