CS151 lecture notes, Fall 1999 Week 3, Wednesday For Friday please read 4.1 through 4.7 Void methods continued ---------------------- Methods that take arguments: public static void printTwice (String phil) { System.out.println (phil); System.out.println (phil); } public static void main (String[] args) { printTwice ("Don't make me say this twice!"); } The expression you provide when you invoke the method is called the argument. The name the method uses to refer to the incoming information is called the parameter. Analogy: when you take a VCR in to get repaired, the repair person puts a tag on it with a number. You as the client don't know or care what the number is, and the repair person doesn't care what you call your VCR. Nevertheless, the two are so closely-related that it is easy to confuse them, and they are sometimes used interchangably. The important differences are: 1) An argument can be any kind of expression, as long as it has the right type. 2) The parameter is just a name that is used by the method. The usual rules apply regarding variable names. 3) When you provide an argument, you don't have to specify the type. Java can figure it out because Java can always figure out the type of an expression. 4) When you name a parameter, you have to specify the type. Parameter lists look something like variable declarations. VERY COMMON ERROR: String s = "bamboo"; printTwice (String bamboo); // WRONG More than one parameter ----------------------- So far, all the methods we have looked at have taken either zero or one parameters, so we have not had a chance to see a parameter list. public static void printTime (int hour, int minute, int second) { System.out.println (hour + ":" + minute + ":" + second); } The list of parameters is similar to a variable declaration, in the sense that the types come before the names. One difference is that you can create multiple variables with the same type: int x, y, z; But you have to give the types of all the parameters separately. int hour, int minute, int second Of course, not all the parameters have to have the same type: public static void printDate (String day, int date, String month) { } Matching arguments and parameters --------------------------------- When you invoke a method, you have to provide arguments that match the method's parameters in type and number (and order). If you get it wrong, the error message can be confusing. Modulus operator ---------------- Operator that works on integers, denoted by % Yields the remainder when the operands are divided. 7%3 = 1 Checking for divisibility... if x%y = 0, then x is divisible by y. Extracting digits: x%10 yields the rightmost digit of x if x were written as a base 10 number. x%100 yields the two rightmost digits.