Saturday, 24 January 2015

How to Pass Parameters to a Java Method

I created a simple class called two_numbers with a method called show_greater. The method accepts two integer parameters and displays the larger:

andrew@UBUNTU:~/Java$ cat two_numbers.java
public class two_numbers
  {
  public void show_greater(int arg1, int arg2)
    {
    int greater = arg1;
    if (arg2 > arg1) greater = arg2;
    System.out.println(greater);
    }
  }
andrew@UBUNTU:~/Java$ javac two_numbers.java
andrew@UBUNTU:~/Java$


Then I created  a program called two_numbers_test. This declares an object called compare in the two_numbers class. It then calls the show_greater method three times, comparing two integers each time to see which one is bigger:

andrew@UBUNTU:~/Java$ cat two_numbers_test.java
public class two_numbers_test
  {
  public static void main(String args[])
    {
    two_numbers compare = new two_numbers();
    compare.show_greater(0,1);
    compare.show_greater(2,1);
    compare.show_greater(3,3);
    }
  }
andrew@UBUNTU:~/Java$ javac two_numbers_test.java
andrew@UBUNTU:~/Java$ java two_numbers_test
1
2
3
andrew@UBUNTU:~/Java$