290 likes | 403 Views
Subroutines, Variables, and Parameters. Week 6. Subroutine / method. Break up a complex task into many small pieces: subroutine. A subroutine consists of the instructions for carrying out a certain task, grouped together and given a name.
E N D
Subroutine / method • Break up a complex task into many small pieces: subroutine. • A subroutine consists of the instructions for carrying out a certain task, grouped together and given a name. • A subroutine can be reused at different places in the program. • A subroutine can be used inside another subroutine.
Subroutine / method • Every subroutine in Java must be defined insidea class. • A subroutine that is a member of a class is often called a method.
Method definition ⟨modifiers ⟩ ⟨return-type ⟩ ⟨subroutine-name ⟩ ( ⟨parameter-list ⟩ ) { ⟨statements⟩ } <modifiers> : public / private / protected / static / no keywords <return-type> : int / double / String / some class type / void/ … <parameter-list> : empty / one or more declarations of the form <type> <parameter-name> • public static voidmain(String[] args)
Methods • The subroutine/method doesn’t actually get executed until it is called. • main() is usually called by the operating system. It is the starting point for each program. Your program won’t be executed if it doesn’t have a main() method. • main() method does not belong to any class even it must be put in a class. It belongs to your Operating System.
Public method call from the same class How to call methods implemented in the same class? Directly call that method. public class PublicInClassCall{ public void print2Screen(){ System.out.println(“Hello World.”); } public double addition(double x, int y){ return x+y; } public double callMethod(){ double z = addition(3.0, 5); //call method addition in the same class //InClassCall System.out.println(“Z is: ”+z); // Z is 8.0 return z; // return the value of z. The type of z must be consistent with method // returned type (double here) } }
Public method call from a different class public class MethodClass{ public void print2Screen(){ System.out.println(“Hello World.”); } public double addition(double x, int y){ return x+y; } public double callMethod(){ double z = addition(3.0, 5); System.out.println(“Z is: ”+z); } } public class MethodCallClass{ MethodClass mc = new MethodClass(); public String callMethod(){ double z = mc.addition(3.0, 5); // other statements … } } How to call methods implemented in different classes? Create an object from the class where methods you call are defined; Use that object name to call methods.
Private method call from the same class public class PrivateInClassCall{ public void print2Screen(){ System.out.println(“Hello World.”); } private double addition(double x, int y){ return x+y; } public double callMethod(){ double z = method2(3.0, 5); // call private method addition return z; } } Private method can only be called within the same class
Private method call from a different class public class MethodClass{ public void print2Screen(){ System.out.println(“Hello World.”); } private double addition(double x, int y){ return x+y; } public double callMethod(){ double z = addition(3.0, 5); return z; } } public class MethodCallClass{ MethodClass mc = new MethodClass(); public String callMethod(){ double z = mc.addition(3.0, 5); //call private method addition, ERROR! } } Private method can only be called within the same class
Static class method public class MethodCallClass{ MethodClass mc = new MethodClass(); public String callMethod(){ double z =MethodClass.addition(3.0, 5); double z = mc.addition(3.0, 5); // call addition, not recommended! } } public class MethodClass{ public void print2Screen(){ System.out.println(“Hello World.”); } publicstatic double addition(double x, int y){ return x+y; } public double callMethod(){ double z = addition(3.0, 5); ORdouble z = MethodsClass.addition(3.0, 5); return z; } } Use class name to call static methods
Variables in Java public class VariableClass{ public intx,y; private String s; public staticintcouter; public int sum(int a, int b){ intaddition = a+b; return addition; } } Member Variables: x, y, s Static Member Variables: counter Local Variables: a, b, addition
Local variable • Local variables: variables defined inside methods. • A local variable in a method exists only while that method is being executed, and is completely inaccessible from outside of that method. • Any changes about local variables are not visible outside the methods.
Example public class LocalVariableClass{ private intscore; // non-static member variable public static String name; // static member variable public int add(int x, int y){ int sum; // sum is the local variable, only exists in method add sum = x + y; return sum; } public int minus(){ score -= sum; // error: sum is not defined! return score; } }
Example public class addNumbersClass{ private int add (int x, int y){ x++; y++; sum = x + y; return sum; } public void addCall(){ int x = 5; int y = 10; int result = add(x, y); // call the previous method: add System.out.println(“X= ”+x+“, Y= ”+y+“, result= ”+result); } public static void main(String[] args){ addNumbersClassanc = new addNumbersClass(); anc.addCall(); } } X=5, Y=10, result = 17
Member variable • Member variables are also called “fields” in Java. • Member variables are defined outside any methods, but inside a class. • They can be accessed by all methods within the class where they are defined or declared. • Two types: • Non-static member variables: it belongs to an object instantiated from that class. • Static member variables: a static member variable belongs to the class itself, and it exists as long as the class exists.
Static member variables • Static member variables are “shared” by all objectsinstantiated from that class. public class SMV{ public staticint counter; // other member variables; // other methods } SMV smv1 = new SMV(); smv1.counter++; SMV smv2 = new SMV(); smv2.counter++;
Access static member variable from the same class public class StaticVariableClass { public static memVar_1; private static memVar_2; public void method_first(){ memVar_1++; // correct memVar_2++; // correct } } How to access static member variables in the same class? Directly access public/private member variables in a method.
Access static member variable from a different class public class AccessClass{ public StaticVariableClass svc = new StaticVariableClass(); public void method_second(){ svc.memVar_1++; // correct StaticVariableClass.memVar_1++; // correct svc.memVar_2++; // wrong } } public class StaticVariableClass{ public static memVar_1; private static memVar_2; public void method_first(){ memVar_1++; memVar_2++; } } How to access static member variables from a different class? • Create an object instantiated from the class where member variables are defined. • Either using object name or class name to access public static member variables in the other class. Private static member variables can only be accessed within the same class
Named Constants • Sometimes, the value of a variable is not supposed to change after it is initialized. • In Java, the modifier “final” ensures that the value stored in the variable cannot be changed after it has been initialized. • final static double interestRate = 0.05; • It is legal to apply the final modifier to local variables and even to parameters, but it is most useful for member variables.
Named Constants • We often refer to a static member variable that is declared to be final as a named constant, since its value remains constant for the whole time that the program is running. • Usually, give meaningful names to these variables to enhance the program readability. • It is easy for us to change the value of a named constant. (during the initialization)
Enumerated Type Constants • enum Alignment { LEFT, RIGHT, CENTER } • Alignment.LEFT 0 • Alignment.RIGHT 1 • Alignment.CENTER 2 • It is similar to define three named constants • public static final intALIGNMENT_LEFT = 0; • public static final intALIGNMNENT_RIGHT = 1; • public static final intALIGNMENT_CENTER = 2;
Example public class MathOperation{ public final static double PI = 3.14; public final static double NATURAL_LOG = 2.72; public final static String AUTHOR = “IDS201”; public double area(double radius){ doubelcircleArea = PI*radius*radius; System.out.println(“The pi is: ”+PI); return circleArea; } public double naturalLog(double x){ double value; value = Math.log(x); System.out.printf(“The log_%f(%f) is %f\n”,NATURAL_LOG, x, value); return value; } public void printMSG(){ System.out.println(“Author is: ”+AUTHOR); } }
Parameters • Provide inputs (parameters) to the black box • The black box will generate outputs input output
Example public class NumberOperation{ private int add (int x, int y){ // the definition of the subroutine add int sum = 0; sum = x + y; return sum; } public intaddCall(){ int a = 5; int b = 10; int result = add(a, b); // call the previous method: add return result; } } x, y are called formal parameters or dummy parameters a, b are called actual parameters or arguments
Formal Parameters • A formal parameter is a name, a simple identifier. • Changes made inside a subroutine to a formal parameter have no effect on the rest of the program.
Example public class FormalParameter{ public intminus(int x, int y){ ++x; --y; returnx-y; } public voidcallMethod(){ int x = 8; int y = 5; intdiff= minus(x, y); System.out.println(“x=”+x+“ y=”+y+“ diff=”+diff); } public static void main(String[] args){ FormalParameterfp= new FormalParameter(); fp.callMethod(); } } X=8 y=5 diff=5
Actual Parameters • An actual parameter is a value. • Could be a real value; • Could be specified by any expression; • The type of the actual parameter must be one that could legally be assigned to the formal parameter with an assignment statement.
How does computer pass parameters? static voiddoTask(double N, double x, boolean test){ // statements to perform the task go here } doTask(17, Math.sqrt(z+1), z >= 10); { double N; // Allocate memory locations for the formal parameters. double x; booleantest; N = 17; // Assign 17 to the first formal parameter, N. Implicit type conversion x = Math.sqrt(z+1); // Compute Math.sqrt(z+1), and assign it to // the second formal parameter, x. test = (z >= 10); // Evaluate "z >= 10" and assign the resulting // true/false value to the third formal // parameter, test. }
Example public class NumberOperation{ private int add (int x, int y){ // the definition of the subroutine add int sum = 0; sum = x + y; return sum; } public intaddCall(){ int a = 5; int b = 10; int sum = 10; intresult= add(a, b); // call the previous method: add System.out.println(“sum = ”+sum); return result; } public static void main(String[] args){ NumberOperation no = new NumberOperation(); int x = no.addCall(); } } sum = 10