CS151 lecture notes, Fall 1999 Week 3, Monday Reading: Chapter 3 What happens when you invoke a method? ------------------------------------- 1) the argument(s) get evaluated 2) the arguments get "passed" to the named method 3) the method might do something (like print) 4) the method might "return" a value 5) the returned value gets used as part of a larger expression, or maybe assigned to a variable Arguments and expressions ------------------------- 1) Arguments can be any expression (as long as it has the right type) 2) Method invocations can be used as part of an expression. Therefore: 3) A method invocation can be used as part of an argument for another method. Example: Math.sqrt (Math.log (23.0)); System.out.println (Math.cos (angle)); void methods ------------ What about this: x = System.out.println ("hello"); Doesn't work because println doesn't return anything. It's a "void method" -- no return value. void is a Java keyword used to identify void methods. Can you name another void method? Creating your own void methods ------------------------------ One of the uses for methods is to hide the details of something complicated or ugly. For example, printing a newLine public static void newLine () { System.out.println (""); } 1) public static is still black magic 2) void identifies void methods 3) newLine is the name of the method 4) () means that this method requires no arguments you invoke it like this: newLine (); 5) the body of the method contains statements, just like in main flow of execution ----------------- method invocations are like a detour in the flow of execution one method can invoke another; like a detour within a detour! public static void threeLine () { newLine (); newLine (); newLine (); } Show path of execution on the slide. Benefits of using methods (so far) ---------------------------------- 1) clarity 2) conciseness Take-home quiz -------------- For next time: modify the example in order to print the phrase "cs115 makes my head hurt" 256 times, using the minimum number of statements (a statement is anything that ends in a semi-colon). Next time: methods that require arguments!