Chapter5_2-Methods

Methodnameargs page 12 dr s gannouni dr a touir

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: must declare a variable of the same type of the return value. • The caller assigns the return value to the variable: variableName = instanceVariable.methodName(args); Page 12 Dr. S. GANNOUNI & Dr. A. TOUIR Introduction to OOP The return keyword • The method's return type is declared in its method declaration. • The return statement is used within the body of the method to return the value. • Any method declared void doesn't return a value. • It does not need to contain a return statement. • It may use a return statement to branch out of a control flow block and exit the method. The return statement is simply used like this: return; • Return a value from a such method, will cause a compiler error. • Any method that is not declared void: • must contain a return statement with a corresponding return value, like this: – return returnValue; • The data type of the return value must match the method's declared return type. • you can't return an integer value from a method declared to return a boolean. Page 13 Dr. S. GANNOUNI & Dr. A. TOUIR Introduction to OOP Example of a Method with Return value public class Student { // Attributes private String studentName; private int midTerm1, midTerm2, lab, final ; // Methods public int computeTotalMarks() { int value = mid1 + mid2 + lab + final; return value; } } public class TestStudent { public static void main (String args) { Student st = new Student(); int total; … total = st.computeTotalMarks(); System.out.println(total); } } Page 14 Dr. S. GANNOUNI & Dr. A. TOUIR Introduction to OOP Template for Methods with Return value public class ClassName { // Attributes ... // Methods ... public returnType methodName(…) { returnType variableName; // 1 - calculate the value to return // 2 - assign the value to vari...
View Full Document

Ask a homework question - tutors are online