COP 2800 Lake Sumter State College Mark Wilson, Instructor
Mid-Term Review
Static and Final
Static variable is still variable (mutable) Sometimes called a class variable One variable shared with all objects of the class (belongs to the class, not the object) Default Initialization applies Initialized before object creation and before any static method of the class runs Improves compiler optimization private static int variableName;
Point to a single object Can’t be altered to point to another object Object pointed to works as expected
Public class Duck { private int size; private static in duckCount = 0; public Duck () { duckCount++; } public void setSize(int s) { size = s; } public int getSize() { return size; }
Good for utilities that don’t rely on instance variables Belongs to the class, not the object Can call any other static method Can’t call non-static methods Can’t use non-static instance data Can act on variables passed in parameters Called using the class name: Math.abs(i); Remember: every program has a public static void main(String[] args) public static void methodName() {... }
Only available to nested classes We aren’t going there in this course
Not really variable (immutable) Must be initialized at definition or in constructor Can only be assigned once Static final variable = constant private final int VARIABLE_NAME = 0; public static final double PI =
Initialize at definition or Initialize in static public static final double PI = public static final double SEED; static { SEED = Math.random(); }
Can’t be overridden class Stuff { public final void things () { // do important things // that can’t be overridden }
Can’t be extended final class Stuff { public final void things () { // do important things // that can’t be overridden } // more stuff }
Math
Provides a set of math functions Similar to but, less extensive than C/C++ math libraries Included in java.lang, no import required Methods are all static No instance variables Private constructor therefore can’t be instanced Employs overloading int index = Math.random() * range;
Random Round Min Max Abs Sqrt Cbrt Pow Floor Ceil copySign Sin Sinh Cos Cosh Tan Asin Acos Atan Atan2 ToDegrees toRandom Exp Expm1 Hypot Log Log10 Log1p Nextafter Nextup Scalb getExponent
Wrapping Primitives
Boolean Character Byte Short Integer Long Float Double One to one match to the primitives Spelling isn’t always the same Have some static methods int aValue = 999; Integer wrappedValue = new Integer(aValue); int unWrapped = wrappedValue.intValue();
Use either a primitive or its wrapper type virtually anywhere either is expected Method arguments Return values Boolean expressions Operations on numbers Assignments Compiler takes care of the accounting Not the same as assigning different number formats or casting
Exceptions Packages, Jars and Deployment. Oh, my!