Creating Methods in Java

In JavaScript, we created functions; in Java, everything is object-oriented, so we'll be creating methods. A method is just a function that's part of a class or object. As an example, I'll create a method now named adder that will add two integers and return their sum.

To start, I'll need two numbers to add, and I'll let the user enter them as command-line arguments. I can read those arguments from the array passed to the main method, which I name args, and store them in integers value1 and value2, like this:

public class ch10_13 
{
    public static void main(String[] args)
    {
        int value1 = Integer.parseInt(args[0]);
        int value2 = Integer.parseInt(args[1]);
    .
    .
    .
}

Now I display those values, pass them to the adder method, ...

Get Real World XML now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.