DOC PREVIEW
UNC-Chapel Hill COMP 14 - LECTURE NOTES

This preview shows page 1-2-16-17-18-34-35 out of 35 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 35 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 35 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 35 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 35 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 35 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 35 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 35 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 35 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

COMP 14 Introduction to ProgrammingAnatomy of a ClassWriting a classWhy Use Methods?MethodsMethod as a Black BoxControl FlowExample: Rectangle.javaUsing Methods What You Need To KnowMethod DeclarationMethod HeaderReturn ValueValue-Returning MethodsValue-Returning Methods UsesReturn TypeThe return StatementUsing returnSlide 18Void MethodsSlide 20The main MethodMethod BodyExample: Largest.javaParametersSlide 25Parameters Primitive Data Type VariablesSlide 27Parameters Reference VariablesPrimitive Data TypesData ScopeData Scope ExampleOverloading MethodsSlide 33Overloaded Methods println ExampleTo doThe UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian IlieCOMP 14Introduction to ProgrammingAdrian IlieJuly 8, 2005The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie2Anatomy of a ClassA class contains data declarations and method declarationsint width;int length;Data declarationsMethod declarations(operations)The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie3Writing a classpublic class Rectangle{// data membersprivate int width;private int length;// methodspublic double computeArea()…public static void main()…}The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie4Why Use Methods?•To divide complex programs into manageable pieces•Abstraction♦provide an operation to be performed on an object (ex: computeArea)•Code Re-use♦write a small piece of code that can be used (called) multiple times (saves typing)The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie5Methods•Pre-defined methods♦provided by Java standard library♦we've used these before♦Math class (Math.pow, Math.sqrt, ...)♦Integer class (Integer.parseInt, ...)•User-defined methods♦you write theseThe UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie6Method as a Black BoxMETHODInput parametersInternal data membersof the classReturn value•A method can use input parameters and internal data members of the class•It may modify the value of internal data members•It may also return a valueThe UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie7Control Flow•Program control flow♦execution always begins with the first statement in the method main♦other methods execute only when called•Method control flow♦when a method is invoked, the flow of control jumps to the method and the computer executes its code♦when complete, the flow of control returns to the place where the method was called and the computer continues executing code•Test this with the debugger!The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie8Example: Rectangle.javaThe UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie9Using MethodsWhat You Need To Know1. Name of the method2. Number of parameters3. Data type of each parameter4. Data type of value computed (returned) by the method5. The code required to accomplish the taskThe UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie10Method Declaration•Specifies the code that will be executed when the method is invoked (or called)•Located inside a class definition•Contains♦method header♦method bodyThe UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie11Method Headerpublic static int countCharInWord (char ch, String word)methodnamereturntypeformal parameter listThe parameter list specifies the typeand name of each parameterThe name of a parameter in the methoddeclaration is called a formal parameterA method declaration begins with a method headervisibilitymodifiersThe UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie12Return Value•Value-returning methods♦The method returns the result of some operations♦Like mathematical functions♦Return one single value•Void methods♦Perform operations but return no valueThe UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie13Value-Returning Methods•Think mathematical functionf(x) = 2x + 5 f(x, y) = 2x + yf(1) = 7 f(1, 5) = 7f(2) = 9 f(2, 3) = 7f(3) = 11 f(3, 1) = 7•Can have multiple arguments (parameters)•Only one result of the functionThe UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie14Value-Returning MethodsUses•Save the value for future calculation•Use the value in a calculation•Print the valuex = Math.pow (y, 2);z = a + Math.pow (y, 2) + x;System.out.println (Math.pow (y, 2));The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie15int number = countCharInWord ('e', "Heels");2Return Type•Indicates the type of value that the method evaluates to:♦primitive data type♦class name♦void  reserved word indicating that nothing is returned•When a value is returned, the method call is replaced with the returned valueThe UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie16The return Statement•Tells the computer to "return" back to where the call was originally made.•Specifies the value that will be returnedreturn expression;•The data type of expression must match the method's return type•Methods with return types of void usually don't (but can) have a return statement•Value-returning methods must have at least one return statementThe UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie17Using returnpublic static double larger (double x, double y){ double max; if(x >= y) max = x; else max = y; return max;}public static double larger (double x, double y){ if(x >= y) return x; else return y;}These are equivalentmethods.The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie18Example: Rectangle.java•Add computePerimeter( )The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie19Void Methods•Do not return a value•Have a return type of void•Similar in structure to value-returning methods•Call to method is always a stand-alone statement•Can use return statement to exit method earlyThe UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie20Example: Rectangle.java•Add printPerimeter( )The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie21The main MethodThe main method looks just like all other methodspublic static void main (String[] args)modifiers returntypemethodnameparameterlistThe UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie22Method BodyThe method header is followed by the method bodypublic static int countCharInWord (char ch, String word){int count = 0;for (int i = 0; i<word.length(); i++) {if (word.charAt(i) == ch) {count++;}} return count;}The return expression must beconsistent with the return typech and word are local dataThey are created each time the method


View Full Document

UNC-Chapel Hill COMP 14 - LECTURE NOTES

Download LECTURE NOTES
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view LECTURE NOTES and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view LECTURE NOTES 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?