80 likes | 225 Views
Creating Methods . v oid and return method . Methods . Object oriented programming concepts Classes objects properties (field data) method Why create methods: Reuse code main reason Nothing in main method can be reused in another class.
E N D
Creating Methods void and return method
Methods Object oriented programming concepts • Classes • objects properties (field data) method Why create methods: Reuse code main reason Nothing in main method can be reused in another class. Class methods can be reused by creating an object of that class to call its methods or if it is a static method using the Class name to call its methods.
Components of a method • Modifiers—such as public, private, • The return type—the data type of the value returned by the method, or void if the method does not return a value. • The method name—the rules for field names apply to method names as well, but the convention is a little different. • The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses. • The method body, enclosed between braces—the method's code, including the declaration of local variables, goes here.
Two types of methods • Void method: doesn’t return anything. It just completes a task or a command //create method to first and last index characters Visibility return type methodname parameter info public void findFirstAndLast(String s) { } String first = s.substring(0,1); String last = s.substring(s.length()-1); System.out.println(“first “ + first + “ last “ + last);
Two types of methods return method • The method will return information from a particular data type //create method to find first and last char Visibility return type methodnameparam. info public StringfindFirstAndLastChar(String s) { } String first = s.substring(0,1); String last = s.substring(s.length()-1); return “first “ + first + “ last “ + last;
Printing with methods void method will not return any information. Just perform task You will need to either create a return method that will return the information or put a system.out.print statement inside the method. Return method will return information from data type. When called it must be placed in a System.out.print statement to print information.
Object of class call its methods public static void main(String[]args) { StringExamplese = new StringExample(); se.findFirstAndLast( "Luella High School“) ; System.out.println(se.findFirstAndLastChar("Luella High School“)); }
Object of class call its methods with dot operator Class: StringExample Methods in class: void findFirstAndLast(String s) String findFirstAndLastChar(String s) Formal parameter public static void main(String[]args) { StringExamplese = new StringExample(); se.findFirstAndLast("Luella High School"); System.out.println(se.findFirstAndLastChar("Luella High School")); } actual parameter