Static MethodsAbout methodsWhy methods?Defining a static methodReturning a result from a methodReturning no result from a methodNon-static methodsThe EndJan 14, 2019Static MethodsAbout methodsA method is a named group of declarations and statementsYou execute those declarations and statements by calling the methodWhen you call the method, you can give it parameters (information, such as numbers, going into the method)A method typically has a return value (a single piece of information coming out of the method)Declarationsand statementsparameterparameterparameterreturn valueWhy methods?Methods help you break up a complex problem into simpler subproblems, which you can solve separatelyMethods can use other methods, but should not depend on the “inner workings” of those other methods--just what they do, not how they do itMethods allow you to give names to parts of your computation, thus making your program more readableReadability is essential in good programmingProper choice of method names is importantVerbs are usually best, since methods “do something”If you have anything the least bit complicated to compute, you should write (and debug) it in only one placeThis is an application of the DRY principle (“Don’t Repeat Yourself)Methods are very good for putting code in only one placeDefining a static methodA static method has the syntax: static return-type method-name ( parameters ) { method-variables code}Example: static boolean isAdult(int age) { int magicAge = 21; return age >= magicAge;}Example: static double average(int a, int b) { return (a + b) / 2.0;}Returning a result from a methodIf a method is to return a result, it must specify the type of the result:static boolean isAdult ( …You must use a return statement to exit the method with a result of the correct type:return age >= magicAge;Returning no result from a methodThe keyword void is used to indicate that a method doesn’t return a valueThe return statement must not specify a valueExample:static void printAge(String name, int age) { System.out.println(name + " is " + age + " years old."); return;}There are two ways to return from a void method:Execute a return statementReach the closing brace of the methodNon-static methodsThis slide set only talks about static methodsMost methods in a Java program will not be staticHowever, before we can talk about what it means to be static, we have to introduce classes and methodsSo, more to come...The
View Full Document