/** 10/24/2018 */ public class ValueMethods /** This class shows return values from methods. * int, double, boolean * * Method overloading - writing more than one method with the same * name. This is fine as long as the signature is different (i.e. * the parameter lists differ either in length or in type.) * Composition - calling a method inside a parameter to another method call */ { public static void main(String[] args) { int sum=sum(123, 456); // assign the return value to a variable int num1=90, num2=333; System.out.println("sum of " + num1 + " and " + num2 + " is " + sum(num1,num2)); // if you are using the return value later, then its better to // put it into a variable int ans = sum(num1, num2)*1000; // call to sum(int,int) double sum2=sum(567.897, 432.12); // call to sum(double,double) System.out.println("sum of doubles: " + sum2); // calling boolean methods. // this simply prints true or false System.out.println("is " + num1 + " even? " + isEven(num1)); // put return value in a variable to use later boolean even = isEven(num1); if (even) // do whatever pgm plans on doing with even numbers System.out.println(num1 + " is even!"); // use the return value in an expression if (isValid(num1)) { System.out.println("num1 is valid " + num1); } if (!isValid(num2)) { System.out.println("num2 is NOT valid " + num2); } // Composition sum = sum(num1, sum(num1, sum(num2, 100))); System.out.println("sum is now: " + sum); } /** method sum simply adds two ints and RETURNS the sum * @param x first number to add * @param y second number to add * @return the sum of x+y */ public static int sum(int x, int y) { int sum=x+y; return sum; // return expression // alternative: return x+y; } /** method sum simply adds two doubles and RETURNS the sum * @param x first number to add * @param y second number to add * @return the sum of x+y */ public static double sum(double x, double y) { return x+y; } /** method isValid tests whether the parameter is between 1 and 100 * @param num an integer to check * @return true if num is valid, false if num is invalid */ public static boolean isValid(int num) { if (num >=1 && num<=100) return true; return false; // alternatively // return num >=1 && num<=100; } /** method isEven tests whether the parameter is even or odd * @param num an integer to check * @return true if num is even, false if num is odd */ public static boolean isEven(int num) { if (num%2 == 0) return true; return false; // alternatively // return num%2==0; } }