≡ Menu

What is a method in Java?

What is a method in Java? Well, we’ve already touched on what a method is in the Java hello world post, but I want to get more in depth on the power of methods (or functions). So first off, you’ve never heard me say the word “function” before, so before I talk about methods, allow me to start with an explanation of what a function is. In Java, methods and functions are really the same thing.  This topic is best described in this stackoverflow post.  So, for the sake of argument, I’ll just use the term method from now on.  So, for example, a method in Java could look like this:

public Integer addTheseTwoNumbers1 (Integer firstNumber, Integer secondNumber)
{
  return firstNumber + secondNumber;
}

Now, this method is a little different than the ones we looked at back in the Hello World post.  There are two main things that are different. The first thing is the code public Integer addTheseTwoNumbers1, you see how we’ve put the word Integer next to the public keyword. This indicates that this block of code will return (or “spit out”) an Integer value. The second thing that indicates that this block of code is different, is the fact that it has a return statement. When you specify return you’re saying that this block of code will be returning (or “sending back”) whatever is to the right of it. So how about we see what that same block of code would look like if it was a method that didn’t return anything:

public void addTheseTwoNumbers2 (Integer firstNumber, Integer secondNumber)
{
  firstNumber + secondNumber;
}

Can you spot the differences? First, there’s no code saying public Integer, now it says public void. The void modifier indicates that this block of code won’t be returning anything. The second thing to notice, is that there’s no more return keyword in the method.

So, what is a method in Java?  Well, a method is that a piece of code that could perform some operations, then return something back to whatever happened to “call” the method. Or, a method will perform some operations, without needing to return anything when it’s done, the flow of code will just continue back from whatever called the method.  Either way, a method will execute some block of useful code that can be called repeatedly from anywhere in your program (so long as it’s declared public).

To illustrate how the code flow could differ between method calls, let’s take a look at this program:

public class myProgram
{
	public static void main(String[] args)
	{
          //---------------------------------------------//
	  // here's our method call that returns a value //
	  Integer resultOfAddition = addTheseTwoNumbers1(5, 24);
          //---------------------------------------------//
	  System.out.println(resultOfAddition);
 
          //----------------------------------------------------//
	  // here's our method call that doesn't return a value //
	  addTheseTwoNumbers2(3, 13);
          //----------------------------------------------------//
	}
 
	public static Integer addTheseTwoNumbers1 (Integer firstNumber, Integer secondNumber)
	{
	  return firstNumber + secondNumber;
	}
 
        public static void addTheseTwoNumbers2 (Integer firstNumber, Integer secondNumber)
        {
          Integer addedValue = firstNumber + secondNumber;
        }
}

If you were to copy/paste this code into your IDE (Spring STS), and run it, you’ll see the following output:

29

This may or may not surprise you. If I were to look at this for the first time, I’d probably guess that you would see 29 and then 16. I would guess this because I see addTheseTwoNumbers1(5, 24) and addTheseTwoNumbers2(3, 13). So naturally, 5 + 24 = 29 and 3 + 13 = 16. So why didn’t we see these two numbers as the output? Well that’s because for one of the calls we used a return statement and for the other we didn’t. Since one method returns a value, we can then use that value and display it in our console (by using System.out.println()). Whereas with the second method, we don’t have a value being returned, so all that happens is that the two numbers are added together, and then we exit the method and the code continues to flow without invoking the System.out.println() code.

So why don’t we just always use methods that return values? They seem more useful, because they give us something that we can work with. Well, that’s just because a method that returned a value was more useful to use with this particular example. There are times when you don’t need something returned, like for example, if you created a method to send an email to someone:

  public void sendEmail(String contactAddress)
  {
    String emailContents = "this is a test email.";
    Email.send(contactAddress, emailContents);
  }

You see? We don’t want anything back, we just want to have the code send the email and go about its business. Okay, so I hope I’ve helped answer the question “What is a method in Java?” and that you understand everything entirely. But, if you don’t, just leave a comment below and I’ll answer your questions. Better yet, sign up for my mailing list, and I’ll let you know when I post new content so you’ll always be in the loop.

 

Don't code another minute until you have these tools.
Get this 1-page PDF that outlines the top 7 Tools that Java Professionals use every day.

{ 44 comments… add one }

  • Nikos Maravitsas July 15, 2012, 6:10 pm

    Hi Trevor ,

    Great blog! Is there an email address I can contact you in private?

  • Juliana Zunk July 16, 2012, 2:23 pm

    would be great if we could read your blog posts everyday. congrats for the hard work.

  • Daisy July 17, 2012, 9:20 am

    good one keep posting more…

  • Mrigank ved July 18, 2012, 4:05 am

    Oh This is fantastic explanation.

    Amount of Knowledge does not matter , what matter is how explain it to any body.

    • Trevor Page July 18, 2012, 9:42 am

      Yes that’s exactly what I’m going for, there are plenty of places on the web to get in depth explanations on these coding topics, but most of them are very difficult to follow.

      Thanks for the comment

  • Anjali Kadam July 22, 2012, 6:44 am

    thanks alot for posting ur tutorials ….these are very useful and interesting ….a grand salute to ur job…..these are really very helpful!

  • sergey July 29, 2012, 2:18 pm

    “If you were to copy/paste this code into your IDE (Spring STS), and run it, you’ll see the following output:
    29″

    Syntax isn’t correct – methods addTheseTwoNumbers1 and addTheseTwoNumbers2 are not static, so they cannot be invoked from static void main :)

    • Trevor Page July 29, 2012, 4:17 pm

      Nice catch, I’ll update my example. Clearly I should do a lesson on the static keyword next!

  • Tejus August 9, 2012, 8:12 am

    Hey! Great initiative, I’m going thru all your posts in order to learn Java :)

    I already know C++, studied it in the school level for two years. So a couple of things confuse me….in Java do you always need to declare the main() function inside a Class? I ask because in C++, the only time we use classes is when we need to declare Objects of that class and use them elsewhere. Also, the main() function was never inside a Class definition, rather it was at the end of the program, after any other functions that are required. In fact if at all the main() function was declared BEFORE some other function (let’s say x()), and the function x() was called in main(), it would result in an error as x() wasn’t declared yet. But I ran the code in the post just to see, and it compiled and ran without a problem. That’s great, but feels a bit odd…

    So I hope that after reading your future posts all these doubts will be cleared :)

    PS: The C++ I learnt was actually following a very old standard, where “void main()” was still allowed and namespaces weren’t requred. I think newer compilers require you to give a non-void return type for main() nowadays? So maybe whatever else I have said is outdated too, no clue :P

    • Trevor Page August 9, 2012, 8:23 am

      There should really be only one main function in your entire project, not one per class file.

      The main method is really only used when you want to create an executable (or runnable) Java project. In my world, I use Java to create web applications, and those types of applications don’t use the main method at all. I just use it here because it’s easy for people first learning to run their examples and get quick feedback from the console.

      Also, the position of your declared methods (whether it be a main or otherwise) doesn’t matter in Java. You can put it at the top or the bottom without compile errors.

      Sounds like I should write a post about this to make it crystal clear to everyone :)

      Thanks for your comments Tejus!

  • Tejus August 9, 2012, 8:21 am

    Oh and one more thing. When I pasted the above code, the IDE placed a lightbulb and exclamation mark on the side of the line where addedValue has been initialized and given a value inside addTheseTwoNumbers2() (that’s called a dynamic initialization right?). When I click on the lightbulb it gives me a couple of suggestions like declaring that variable outside the function and then assigning the required value (firstNumber + secondNumber) to it inside etc…why does it do that? Is it because the scope of the “addedValue” variable is only within addTheseTwoNumbers2()? Or is it because that variable addedValue hasn’t been used anywhere else after it’s declaration?

  • Scott Baietti August 14, 2012, 11:43 am

    I am really new. I tried copying this code into my hello world program just to see if it worked and I had errors. Can I not insert this new method to the end of my existing code?

    One such error is “The operator + is undefined for the argument type(s) java.lang.Integer, java.lang.Integer” The other “The method addTheseTwoNumbers2(Integer, Integer) in the type HelloWorld is not applicable for the arguments (int, int).”

    What do these mean?

    • Trevor Page August 14, 2012, 8:31 pm

      I’m not exactly sure what the particular issue is there, and it’ll be tough to know without actually being in front of your computer screen… but one thing that critical is that your Class name has to match the actual filename of your “.Java” file. Other than that, it will likely be the syntax of the code that will cause you the most headaches. Make sure you have the right syntax for a method declaration, as addTheseTwoNumbers2(Integer, Integer) is not proper syntax ;)

      • Scott Baietti August 15, 2012, 12:29 pm

        Here is my full code. Do you see any syntax errors? I copied it straight from your example into my original hello world program.
        ——————————————————-
        // code removed for sake of brevity

        • Trevor Page August 16, 2012, 6:29 am

          Hey Scott,

          I copy pasted your code into my environment and it ran fine. So if you think you may have some compilation errors, I’d suggest verifying that by doing the following:

          In Spring STS, click on the Window menu -> Show View -> Other
          Then type in Problems
          Select the Problems view that appears

          This will open a “Problems” view in your Spring STS IDE. In this view you’ll be able to see if you do have any compiler errors. Also, a good thing to check is that you have “Build Automatically” running. This is found here:

          Project menu -> Build Automatically (just make sure there’s a checkmark on it).

          Let me know if that helps to track down any errors you may have.

  • Terry Sawyer September 3, 2012, 8:30 pm

    Hi! I just wanted to ask if you ever have any issues with hackers?
    My last blog (wordpress) was hacked and I ended up losing many months of
    hard work due to no backup. Do you have any methods
    to stop hackers?

    • Trevor Page September 3, 2012, 8:38 pm

      Yep,
      There are plugins that help with security and backups of your wordpress data. A Google search should bring up a bunch, then you just find the one that has the best ratings!

  • faiqa September 24, 2012, 1:47 pm

    i face this problem when i tried to compile the above code in ide.. Exception in thread “main” java.lang.Error: Unresolved compilation problem:

    at com.myProgram.myProgram.main(myProgram.java:4)

    • Trevor Page September 24, 2012, 2:46 pm

      This means that you have incorrect code that doesn’t even compile. Usually your IDE will show the problem by underlining the line of code (or piece of code) in red. If you’re using the SpringSource Tool Suite (STS) then you’ll be able to hover over the code underlined in red and find out what the problem is.

      My first guess is that you may not have specified a package at the very top of your code… if you have done so, then I can’t yet help until I see your code. If you like, you could email me a screenshot at info@howtoprogramwithjava.com!

      • faiqa September 25, 2012, 9:21 am

        yesterday i sent you a email but you did not reply me back..

        • Trevor Page September 25, 2012, 9:24 am

          I received a bunch of emails that I’m still parsing through and replying to, I’ll check yours right now :)

  • milo November 18, 2012, 9:19 am

    good method

  • Taofeek Hammed December 9, 2012, 4:57 pm

    i am a beginner in java programming technology. i thank u for the effort u ar making to simplify the mystries in java. pls explain constructors, Object class, and their uses. thank u and God bless u.

  • Robyn Hurst February 13, 2013, 12:27 am

    Is this the point I should completely understand the content before continuing?

    • Trevor Page February 13, 2013, 6:04 pm

      Not sure I understand your question Robyn. If there are topics that you’ve already read about that still don’t make sense, then I would tread carefully with continuing. All of these tutorials were sort of designed to build on each other. Feel free to ask questions here or in the Java Video Tutorials forums if you’re stuck :)

  • Xrychxrych February 20, 2013, 9:35 am

    Thanks Sir. I just got to this page. It’s really helpful. Please could you direct me to a full page where I could find all these powerful explanations from you?

  • Scionet February 26, 2013, 12:08 am

    In methods, what is the difference in declaring :

    Public static Integer
    Public Integer

    Is there also a,
    Public int

    Thank you.

    • Trevor Page February 26, 2013, 12:31 pm

      The difference between a static method and a non-static method can be found in this article, or this podcast episode.

      One important thing to note is that Java is case sensitive, so when you declare a method, you need to use lower case:

      public static Integer method ()
      {
        // static method that returns an Integer object
      }
      
      public Integer method ()
      {
        // non-static method that returns an Integer object
      }
      
      public int method()
      {
        // non static method that returns a primitive int
      }
      

      So to answer your last question, yes you can create a public int method as well… that’s just a difference of using a primitive variable vs an Object wrapper. If you’re interested in reading about that, check out this article or this podcast :)

      Hope that helps you out!

  • Merry Ann June 14, 2013, 1:00 am

    Hi Trevor!

    Very nice blog. I am so lucky i found this. Would you mind if will ask your email add, so i can contact you faster in I have questions? :) Thanks a lot.

  • Akash October 25, 2013, 6:59 am

    Very well Explained .. its easy to understand ..
    thanks for shareing :)

  • Erickson May 14, 2014, 1:45 am

    Hi Trevor,

    I like your explanation, and am very happy for the hard work you put in. Could you please give me your email address so I could contact you.. Thanks very much..GOD Bless..

    • Trevor Page May 14, 2014, 10:56 am

      Hi Erickson,

      If you have a specific question, then by all means ask it here in the public comments area… this way everyone will be able to see it and get the benefit of my answers.

      If you require ongoing support, then I would suggest you join Coders’ Campus, this is a private group of programmers dedicated to helping each other out (and I also pop my head in there and answer questions).

  • Anonymous June 28, 2014, 10:46 pm

    Although I have a prior experience in visual basic, I don’t understand, you suddenly gone too technical.
    In visual basic I just declare variables and start writing my program, no such things called methods, static, void, return… Etc
    Please simplify this, I’m totally confused!!!

    • Trevor Page July 3, 2014, 8:06 am

      In visual basic I believe you have functions and procedures… these can both be created in java as a method… either a method that returns a value (i.e. function) or a method that doesn’t return anything (i.e. procedure)

  • Nelson July 9, 2014, 11:01 pm

    Excellent, but where does the Email come from? The part where you call the send method.

    • Trevor Page July 10, 2014, 12:55 pm

      Good observation… in this case I’m assuming that there’s an Object that’s already been created called Email which has a method called send()

  • Tardzenyuy July 17, 2014, 6:16 pm

    more grease to your elbows SIR!!!!

  • Tardzenyuy July 19, 2014, 3:20 am

    Hi! Trevor I was expecting to see something like header files cuz am just from studying c++ where its all about header files…please kindly enlighten me on how to locate header files in Java coding
    Thanks alot

  • roopsa December 8, 2014, 2:09 pm

    Does the ‘sendEmail’ method require the main method every time for it’s execution? Previously you had mentioned that you did not use the main method at all. How is it possible to execute an explicitly defined method if not called by main. Unless if there was some other method in java that we don’t know of.

    • Trevor Page December 9, 2014, 9:35 am

      The “main” method in Java is required if you want to make a runnable Java application. It’s not required to explicitly use the “main” method when doing Java programming, as you can also create runnable “test” methods (via the @Test) annotation… but under the hood, those methods will invoke a “main” method as well.

      So the short answer to your question is, yes, the “sendEmail” method will require a main method for its execution.

Leave a Comment

Powered by sweet Captcha