1CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)Lecture Set 6:Static Methods & Variables and Exceptions1.Parameter Passing2.Static variables and static methods3.ExceptionsCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)1Parameter PassingParameter ListNames of ParametersPrimitive type parametersReference type parameters(See parameter passing example in CVS)CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)2Why Have Static Variables / Methods?Sometimes info needs to be shared data among all objects of a specific class typee.g. How many objects in a class have been created?A constant that needs to be the same for all objects of that typeSometimes it is useful to have methods that are in a class that can be invoked without first creating objects of that typeStatic components help for these types of things2CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)3Declaring Static Methods (and variables and constants)Static methodspublic static void main (…) { … }public static void drawFlag(MyGrid grid, intCcode) { … }How do we call static methods?FlagMaker.drawFlag(grid, 1);Can have static variables and constants too public static int numStudents = 0;public static final int MAX_ENROLLMENT = 10;How do we use static variables and constants?StudentRoster.numStudentsStudentRoster.MAX_ENROLLMENTCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)4When To Use Static Methods?When a method should be invocable without object creationWhen a method should not change instance variablesA static method can only change static variablesInstance variables can only be changed by non-static methodsCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)5Default ValuesStatic and instance variables initializedmost types to 0char to value 0 (non-printable character)strings are assigned to nullLocal variables do not have a default value and you get a error from eclipse3CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)6Calling one method from another – static and non-staticstatic methodswhen running they ARE NOT associated with a specific instanceyou do NOT have a “current object” but you do have a current classare usually called with: ClassName.sMethodName()if you are already in a static method, since you have a class name understood as the default, you can just use sMethodName()non-static methods when running they ARE associated with a specific instanceyou do have a “current object”are called with: objectName.nsMethodName()if you are already in a non-static method, since you have a current object assumed, you can just use nsMethodName() to call it on that current objectsince that non-static method must also be in the class, the class name is also understood as the default so you can use sMethodName() to call the static member of that classCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)7ExceptionsPrograms can generate errorsArithmeticDivide by zero, overflows, …Object / ArrayUsing a null reference, illegal array index, …File and I/ONonexistent file, attempt to read past the end of the file, (we’ll see more about file I/O later in course), …Application-specificErrors particular to application (e.g., attempt to remove a nonexistent customer from a database)In Java: error = exceptionWhat to do when an error occurs?1.Basically ignore it: Print an error message and terminate?2.Have the method handle it internally: Handle error in the code where the problem lies as best you can.3.Have the method pass it off to someone else to handle: Return “error code” so that whoever called this function can handle it.4.Modern language approach: Cause “exception” to be thrown (and caught (or processed) by any function up the stack trace)CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)8Exception BehaviorIf program generates (“throws”) exception then default behavior is:Java clobbers (“aborts”) the programStack trace is printed showing where exception was generated (red and blue in Eclipse window)Examplepublic static int mpg(int miles, intgallons){return miles/gallons;}Throws an exception and terminates the program.4CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)9Throwing Exceptions YourselfTo throw an exception, use throw command:throw e;e must evaluate to an exception objectYou can create exceptions just like other objects, e.g.:RuntimeException e = new RuntimeException(“Uh oh”);RuntimeException is a classCalling new this way invokes constructor for this classRuntimeException generalizes other kinds of exceptions (e.g. ArithmeticException)CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)10Exceptions, Classes and TypesExceptions are objectsSome examples from the Java class library (mostly java.lang):ArithmeticException: Used e.g. for divide by zeroNullPointerException: attempt to access an object with a null referenceIndexOutOfBoundsException: array or string index out of rangeArrayStoreException: attempting to store wrong type of object in arrayEmptyStackException: attempt to pop an empty Stack (java.util)IOException: attempt to perform an illegal input/output operation (java.io)NumberFormatException: attempt to convert an invalid string into a number (e.g., when calling Integer.parseInt( ) )RuntimeException: general run-time error (subsumes above)Exception: The most generic type of exceptionCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)11Java Exceptions in DetailExceptions are (special) objects in JavaThey are created from classesThe classes are derived (“inherit”) from a special class, ThrowableWe will learn more about inheritance, etc., laterEvery exception object / class has:Exception(String message)Constructor taking an explanation as an argumentString getMessage()Method returning the embedded message of the exceptionvoid printStackTrace()Method printing the call stack when the exception was thrown5CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)12Handling ExceptionsAborting program not always a good ideaE-mail: can’t lose messagesE-commerce: must ensure correct handling of private info in case of crashAntilock braking, air-traffic control: must recover and keep workingJava includes provides the programmer with mechanisms for recovering from exceptionsCMSC
View Full Document