Methods
click here for complete presentation on static methods What is a method?
Idea of a method
Method StuctureaccessModifier returnType methodName(parameters) Access ModifierAccess modifiers are either public, private, protected, or default
Return TypeMethods can return primitives (int, double, boolean, char) ,objects, or void
Simple method exampleGiven two integers, find the bigger: public int max(int a, int b)
if( a > b )
return a; else return b; } Why Object Reference Methods
Proper syntax for calling a static method gives first the reference variable (of the instance of class) , a dot, the name of the method, then the arguments ObjectReferenceVariable.nameMethod(arg1, arg2, arg3); ExamplesString s1 = new String("Hello"); Random gen = new Randon(); Simple static method exampleGiven two integers, find the smaller: public static int min(int a, int b)
if( a < b )
return a; else return b; } Why Static
Proper syntax for calling a static method gives first the name of the class the method is in, a dot, the name of the method, then the arguments ClassName.MethodName(arg1, arg2, arg3); Examplesint num = Math.abs(-3); // num is equal to 3 |
Scanner ClassCredit: A Slides are modified with permission from Barry Wittman at Elizabethtown College |
|