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

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...

Energy Android TV Play turns your TV into a Smart TV

ENERGY SISTEM Android Energy TV Play, you have a smart TV with Android operating system allows you to convert any traditional TV has announced the launch of a new product. Energy Android TV Play can be connected to the TV to enjoy f the size of a flash drive, a smart phone, a tablet and a computer unconsolidated is a lightweight device. System 1.6 GHz, DDR3 1GB of RAM and a dual-core processor can be expanded using external USB devices, which is the internal memory of 8 GB. It also integrates WiFi and a USB port for connecting external devices. One of its outstanding features, it is easily connected to the TV screen by screen cast application to display the contents of any terminal, making any phone or tablet is synchronized with iOS or Android. All ENERGY SISTEM products one click In addition, through streaming media service applications, images, video or other multimedia content, and game play is the ability to share. With integrated WiFi, the device you want from t...

How to run Python apps on any platform

Credit: Adam Sinicki / Android Authority Want to know how to run Python? It sounds simple, but it can actually be tricky to figure this out. In this post, we’ll discuss how to test your Python code, as well as how to run Python in other contexts: online for example, or as a packaged app. Sometimes, the thing holding you back from learning to code can be extremely simple. I remember wanting to learn to program when I was younger – or learning to take what I’d learned from BASIC on the ZX Spectrum and apply that to a modern environment. My problem? I didn’t know “where” to program. Once I understood C# or Java, where would I enter the code and how would I run it? And whenever I asked someone, they would look at me blankly. What kind of a question is that? Thing is, I had never needed an IDE or an interpreter before. Machines like the ZX Spectrum and Tatung Einstein (any other Einstein users out there?) simply booted up with a prompt to code into! Many people have a similar iss...