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

LIVE Day Trading Morning Show for Tuesday!

LIVE Day Trading Morning Show for Tuesday! via YouTube https://www.youtube.com/watch?v=vgagRBXRJM0 Android Tips and Tricks working hard to get the latest and useful tips and techniques that help you to solve a problem or improve your productivity.

5 tips to Voice Speech Recognition in Android Marshmallow

Android Marshmallow landed on our Android devices. The opportunity for us to offer a small compilation of tricks to try immediately. The latest version of the Google OS starts (very gently, unhurriedly) to be offered on other devices as Nexus. You will find on Android TM, in the coming weeks, a compilation of the best tips for Android 6.0 Marshmallow. It starts slowly with a video featuring the 10 essential tips & tricks of this new version of the little green robot OS. To continue, we offer a selection of five "tricks" on the management of the battery on Android 6.0 Marshmallow. To enjoy longer your newly updated mobile. Follow the guide. then continue with 5 tips to tame the super-assistant Google Now on Tap. Here you will find 5 "tips" to manage in the best way your applications. We then discuss the quick tips to navigate more easily on this version of the Google OS. We enchanters with features focused on safety and the protection of personal data. We co...

Android Studio 4.1 – New features for devs

Android Studio 4.1 made it onto the stable channel last month, bringing a number of useful new features for Android developers. There are some interesting inclusions this time around, so read on to see what you need to know! Embedded emulator One of the most interesting updates comes to the Android emulator, which is now built right into the IDE itself. In other words, the emulator no longer opens as a separate app but rather in a tool window. This is said to “save screen real-estate” for all us peasants working on sub 4K, 42” monitors. See also:  Android Studio tutorial for beginners While this is mostly a cosmetic change, it does make the experience feel more cohesive and intuitive. It’s also easier to monitor code while the app is running. It is a great stride toward a more integrated and seamless experience. The feature is not turned on by default, however. To access it, you first need to update your preferences by going to File > Settings > Tools > Emulator ...