Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Java ProgrammingWeek 2
Alice E. Fischer
Feb 3 and 5, 2015
Java Programming - Week 2. . . 1/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Functions and MethodsCalling MethodsMethod Categories
Types and ClassesJava TypesWrapper Example: Integer
Variables and ObjectsArrays are ObjectsObjects and Constructors
Summary and Homework
Java Programming - Week 2. . . 2/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Functions and Methods
Calling MethodsMethod categories
What methods should you define?
Java Programming - Week 2. . . 3/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Calling Methods
Functions vs. Methods
I A function is a collection of methods that perform the sametask on different kinds of objects or the same task on thesame kind of object with different combinations of parameters.
I A method is one of possibly many definitions for the samefunction. Each method must have a different set ofparameters or be defined in a different class.
I All methods are defined inside classes.
I Methods can be static or dynamic.
I A static method can use only static data and other staticmethods. It lives in the static world.
I Many library methods are static so that they can be called anytime, anywhere.
Java Programming - Week 2. . . 4/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Calling Methods
Entering The Dynamic WorldThe first two programs (WinterWork and MPH) were very simple:the entire program was inside the main function, and the class wassimply a container for main().
I These programs operated in the static world, using only staticfunctions, static objects, and local variables in main.
I We move on now to OO programs. From now on, the mainfunction has one major responsibility: to create a new classinstance and call its primary function, and by doing so, enterthe dynamic world:
public static void main (String args[]) {
Hungry hannah = new Hungry();
hannah.go();
}
Java Programming - Week 2. . . 5/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Calling Methods
Calling a Static Method
To call a static method:
I Write the name of the class that defines it,
I followed by the function name and a parameter list inparentheses.
I For example, to round the double number x to the nearestintegral value: Math.round( x );
Java Programming - Week 2. . . 6/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Calling Methods
Calling a non-static Method
I Non-static methods are called using the name of an objectand the function name.
I For example, suppose hannah and john are Hungry objects,and the Hungry class has a method named go.
I We call the go() method this way:hannah.go();
john.go();
I The object that is used to call a method (in this case, hannahor john) is called the implied parameter.
I The method’s code can freely use all data members of theimplied parameter.
Java Programming - Week 2. . . 7/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Calling Methods
Example: Methods in the Die Class
I The Die class has 2 data members: faces, and value.
I It has two constructors and three methods (roll(),getValue(), toString()).
I Main creates Die objects on line 45 and stores them in a Diearray named dice.
I Line 49 calls the roll() method using the object dice[k],which is one of the Die objects in the array named dice.
I Inside the go() method, dice[k], is the implied parameterand can be referenced by writing this.
I dice[k].roll() uses the member named faces of the k’thDie in the array to calculate and store a random value.
Java Programming - Week 2. . . 8/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Method Categories
Categories of Methods
I Constructors.
I Public interface methods, that carry out the activities of theclass.
I Private helper methods, that are called from the publicmethods of the class.
I Public toString methods that format the data members ofthe class for printing
I Public Accessors (getters) to return the value of a single datamember. This gives read-only access to private data.
I Public Mutators (setters) used to interact with JavaFX. Idon’t want you to define any in your classes unless I giveexplicit permission.
Java Programming - Week 2. . . 9/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Method Categories
Methods to WriteI Constructors: Every class should have a constructor with
parameters. Some should have a default constructor. Someshould have both.
I For every class, write a toString method that format thedata members of the class for printing. You will need to usethese functions during debugging.
I Classes normally have at least one action method. Theassignments I give normally list the action functions that youshould write.
I You will want accessors for some, but not all, private datamembers. If you don’t need it, don’t write it.
I I don’t want you to define setters in your classes. If you needone, I will tell you to include it.
Java Programming - Week 2. . . 10/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Primitive Types and Wrapper Classes
Java primitive typesPurpose of Wrappers in Java
Wrapper typesExample: Integer
Java Programming - Week 2. . . 11/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Java Types
Java Primitive Types
Type Size Default
boolean 1 bit true or false falsechar 2 bytes Unicode unsigned \u0000byte 1 bytes signed integer 0short 2 bytes signed integer 0int 4 bytes signed integer 0long 8 bytes signed integer 0float 4 bytes single precision floating point 0.0fdouble 8 bytes double precision floating point 0.0
Java Programming - Week 2. . . 12/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Java Types
What is a Wrapper Class?
I Every Java primitive type has a matching wrapper class.
I An instance of the wrapper class is an object with one datamember of the matching primitive type.
I The class “wraps” the primitive so that we can use it whereobjects are required.
I Java has both primitives and wrappers because using theprimitives is much more efficient in both space and time.
obj
13
int prim = 4;Integer obj = new Integer( 13 ); 4
prim
Java Programming - Week 2. . . 13/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Java Types
A Java Design Problem
These basic Java facts are almost contradictory:
1. All Java code is and must be inside some class.
2. A modern language must provide the functions in thestandard C libraries (math, ctype).
3. A modern language must support pre-programmed collectionsof both primitive values and objects.
4. Java strictly divides the world of primitive objects from theworld of dynamic objects.
I You cannot create a primitive variable in dynamic memory.I All class objects are in dynamic memory.
#1 and #2 conflict, as do #3 and #4.
Java Programming - Week 2. . . 14/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Java Types
Purpose of Wrappers in Java
The wrapper classes in Java solve the problem.A wrapper class:
I . . . gives us an easy way to turn a primitive into an object withthe same meaning that can be dynamically allocated and putinto a collection.
I . . . gives us a place to put the related standard librarymethods and methods that convert values to and from thewrapper type.
I . . . gives us a place to put information about theimplementation of the primitive type on the local system. InC, this information is in a header file such as limits.h.
Every primitive type has a matching wrapper class.
Java Programming - Week 2. . . 15/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Java Types
Java Wrapper Classes
Primitive Type Wrapper Class
boolean Booleanchar Characterbyte Byteshort Short
int Integerlong Longfloat Float
double Double
Familiarize yourself with the Java API documentation.Look at a few of the wrapper classes.
Java Programming - Week 2. . . 16/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Java Types
Static Functions and Values
I All code in Java must be inside a class. This is one reason forhaving wrapper classes.
I The wrapper class defines important constants: the size (inbits) of the type, the maximum value, and the minimum value.
I Each primitive type has a set of related functions that aredefined inside its wrapper.
I Most of these functions are static and are can be used withoutinvolving an object.
I Included are constructors, toString(), conversion functions,and miscellaneous other functions that you would find in theanalogous C standard library.
Java Programming - Week 2. . . 17/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Java Types
Wrappers and Java Collections
I The other important use of wrappers is that Java genericcollections (data structures) cannot store primitive values.
I You must wrap your primitive data in an object before youcan store it in a Java List or HashTable.
I We will study the ArrayList collection soon.
Java Programming - Week 2. . . 18/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Wrapper Example: Integer
Wrapper Example: an int and an Integer
An Integer is an object that contains an int.
obj
13
int prim = 4;Integer obj = new Integer( 13 ); 4
prim
Java Programming - Week 2. . . 19/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Wrapper Example: Integer
Information about Integers
The Integer class contains static data members that describe thetype int:
I static int MAX_VALUE A constant holding the maximumvalue an int can have, 231 − 1.
I static int MIN_VALUE A constant holding the minimumvalue an int can have, −231.
I static int SIZE The number of bits used to represent anint value in two’s complement binary form (32).
Every other wrapper class contains the same static members, withvalues appropriate for each different type.
Java Programming - Week 2. . . 20/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Wrapper Example: Integer
Integer
An Integer object has exactly one non-static data member, whichis an int. Significant methods include:
I static int signum(int k) : Return -1, 0, or +1,according to the sign of k. Returns the signum function of thespecified int value.
I static int parseInt(String s) Convert the String asinto a signed decimal integer.
I String toString() Convert the value of an Integer to aString.
I int intValue() Return the value of this Integer as an int.Similarly, byteValue(), doubleValue(), floatValue(),
longValue() etc.
Java Programming - Week 2. . . 21/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Wrapper Example: Integer
Integer Methods
An Integer object has exactly one data member, which is an int.Significant methods include:
I static int signum(int k) : Return -1, 0, or +1,according to the sign of k. Returns the signum function of thespecified int value.
I static int parseInt(String s) Convert the String asinto a signed decimal integer.
I String toString() Convert the value of an Integer to aString.
I int intValue() Return the value of this Integer as an int.Similarly, byteValue(), doubleValue(), floatValue(),
longValue() etc.
Java Programming - Week 2. . . 22/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Variables and Objects
A variable is a pointer.Creating garbageArrays are objects
Java Programming - Week 2. . . 23/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Variables
A variable of some class-type is just an uninitialized pointer.
I When declared like this, sc has no usable memory attached:Scanner sc;
You must set it = a new object before you can use it.
I Variables are commonly initialized in the declaration:Scanner sc = new Scanner(System.in);
I Calling new allocates memory and calls the class constructorto initialize it. This is how data gets inside an object.
I Then new returns a pointer to the object, which is stored inyour variable.
Java Programming - Week 2. . . 24/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Variables, Objects and Arrays
A class-type variable or an array variable is an uninitialized pointer.Nothing can be stored in it until you attach new memory.
Die d2 = new Die(4); d2.roll(); // Randomize again.
Die d1;
nulld1
d2
d1.roll(); // Null pointer exception
4 3faces value
int [] ar2 = new int[5];ar2[1] = 17;
int [] ar1;
nullar1
ar2
ar1[0] = 3; // Null pointer exception
175
The blue area is the run-time stack; yellow is dynamic memory
Java Programming - Week 2. . . 25/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Object Assignment can Create Garbage
An object becomes garbage when the last pointer to it is lost.
A variable can point at one object, and later point at another.
int[] ar2 = {3, 11,13};ar2 = new int[5];ar2[0] = 17;
ar2
175
3 11 133
The original object becomes garbage after the assignment.
Java Programming - Week 2. . . 26/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Arrays are Objects
Arrays
Arrays are ObjectsLike C and Unlike C
The Length of an ArrayArrays of primitives vs. Arrays of objects
Dice
Java Programming - Week 2. . . 27/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Arrays are Objects
Array Variables.
int[] myStuff ;
I myStuff is not an array – it is a name to which we can attachan array. That array must be created by calling new.
I An array variable can refer to (or point at) any array of theright base type. The length does not matter.
I An array variable can point to different arrays of differentlengths at different times.
I Write the brackets next to the name of the base type.
I An array name can refer to any array of the matching basetype but not to other types. It is not legal to write this:int[] ar = new double[3];
Java Programming - Week 2. . . 28/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Arrays are Objects
Array Objects.myStuff = new int[5];
I We attach the name myStuff to an array, which is an objectcreated by calling new.
I Every array-object in Java “knows” its length. The length isstored just before slot 0 of the array.
I When this object becomes garbage, its length is used by thegarbage collector to manage memory.
I Write the brackets next to the name of the base type.
I A set of initial values, in braces, can be used to both allocateand initialize an array.
I The contents of the array can be changed later, if it is not afinal array.
Java Programming - Week 2. . . 29/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Arrays are Objects
Array Declaration and Allocation
int [] myStuff = new int[5];int [] emptyAr;bool[] mask = {true, true, false, true}
myStuff 175
emptyAr null
true true false truemask4
Java Programming - Week 2. . . 30/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Arrays are Objects
Arrays: Like C in some ways
C: int myStuff [5];
Java: myStuff = new int[ENOUGH];
I Once created, the length of an array object is fixed. Thelength is stored as part of the object.
I myStuff[0] is the first slot in the myStuff array.
I Memory will be allocated in consecutive memory locations,with subscript 0 at the lowest memory address.
I A Java array variable is very much like a C pointer to an array.
Java Programming - Week 2. . . 31/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Arrays are Objects
Arrays: Unlike C in some ways.
I The brackets are part of the type name!
I Java arrays are objects that must be dynamically createdusing new.
I In Java, ar.length is the length of the array ar.
I When you subscript an array to get an element, Java checksyour subscript .
I Java will throw an exception if a subscript is < 0 or subscript>= length.
I In C, the array name cannot be attached to a different array.In Java, it can.
Java Programming - Week 2. . . 32/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Arrays are Objects
Compare to a C++Array
A C or C++ array can be allocated either on the stack or indynamic memory. Not so with Java.
int ara[5] = {0, 17);int ary[] = new int[3];
ara 017000
in C++:
ary ?? ?3
int[] ar1 = {3, 11,13};ar2 = new int[5];ar1 = ar2
ar25
3 11 133
ar1
Java Programming - Week 2. . . 33/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Arrays are Objects
The Length is part of the Array Object.
An array variable can point at an array of any length with the rightbase type.
I When you allocate a new array, Java knows its length andstores that length as part of the new object.
I In the diagram above, ar1.length is 3. The length is apublic data member, not a function.
I If we set ar1 = ar2, then both variables point at the samearray and ar1.length is 5.
Java Programming - Week 2. . . 34/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Arrays are Objects
Two Levels of Pointers
I When we make a new array of objects, it is really an array ofnull pointers. Memory exists for the pointers, but not for theobjects themselves.
I The objects that will be attached to the array must beallocated one by one.
I In this example, we call a constructor of the Integer class tocreate a new Integer, initialized to 13, and store the pointer inour array: ar3[3] = new Integer(13);
I If you try to use an array element before you initialize it, youwill get a “Null pointer exception”.
I Compare this to the analogous C array:
Java Programming - Week 2. . . 35/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Arrays are Objects
The Length is part of the Array Object.
An array variable can point at an array of any length with the rightbase type.
I When you allocate a new array, Java knows its length andstores that length as part of the new object.
I In the diagram above, ar1.length is 3. The length is apublic data member, not a function.
I If we set ar1 = ar2, then both variables point at the samearray and ar1.length is 5.
Java Programming - Week 2. . . 36/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Arrays are Objects
Arrays of Objects
An Integer is an object with an int inside it.An Integer array has multiple objects connected by pointers.
Integer [] ary = new Integer[4];ary[2] = new Integer(13);
ary
13
null null null4
An array of objects has two levels of dynamic allocation, and twolevels of pointers.
Java Programming - Week 2. . . 37/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Objects and Constructors
Objects and Constructors
InitializationFinal
Constructors
Java Programming - Week 2. . . 38/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Objects and Constructors
Initialization
Some things are automatically initialized in Java, others are not.
I When you create a new object, all its members are initializedto a default value (all 0-bits).
I The elements of a new array are automatically initialized tothe default value.
I When you declare a variable of a class-type, it is initialized tonull.
I Local variables of primitive types (inside a function) are notinitialized. You must initialize them before you can use them.
Java Programming - Week 2. . . 39/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Objects and Constructors
Initialization Rules
Java has rules for correct source code that are stricter than C.
I In Java, you are not permitted to use a variable unless it hasbeen initialized.
I To enforce this rule, the Java compiler does a complete flowanalysis of your code.
I If there is any way that control could bypass the initialization,the code will not compile.
Java Programming - Week 2. . . 40/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Objects and Constructors
Final
A final variable is a lot like a const variable in C
I In both languages, the first value assigned to the variable isthe ONLY value it can ever have.
I In C, that value must be assigned in the declaration.
I But in Java, that first assignment can be anywhere.
I Parameters can be final. That means that the function callwill give the parameter a value, and it cannot be changedwithin the function body.
Java Programming - Week 2. . . 41/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Objects and Constructors
Initialization of Final VariablesIn Jellybeans, the variable full is a final member of the classMain.
I We set it to 17 in the declaration; thereafter, it is constant.
I If we wished, we could delay this initialization, but only oneassignment is permitted.
I We are able to initialize level and full in the classdeclaration because these numbers do not depend on userinput or anything else that happens at runtime.
I These two variables are visible to all function bodies in thesame class. They can be used by one function to send info toanother.
I Guideline: if you CAN initialize things in the declaration, DO.However, don’t initialize things to meaningless values.
Java Programming - Week 2. . . 42/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Objects and Constructors
ConstructorsA constructor is a function whose purpose is to initialize the newobject. It has the same name as its class and it is calledautomatically when a new object is created.
I A constructor normally has parameters and stores thoseparameters into the data members of the new object.Sometimes more than one data member relies on the sameparameter.
I Parts of the object that rely only on compile-time informationcan be initialized in the class declaration.
I Parts of the object that depend on run-time informationshould be initialized by the constructor.
I The combination of class declaration and constructor shouldleave all data members initialized so that the object is readyto use and internally consistent.
Java Programming - Week 2. . . 43/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Objects and Constructors
Default Constructors and Null Constructors
Most constructors have parameters and initialize the data membersof the class.
I A null constructor is a constructor that does not initializeanything.
I A default constructor is a constructor with no parameters.
I Null constructors are not the same as default constructors.
I If you do not provide any constructors for your class, Java willprovide a null default constructor.
Example: the Hungry class does not have a constructor.
Java Programming - Week 2. . . 44/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Java Summary
We have used the following packages and classes so far:
I java.lang.System: for the streams named in and out andprintf().
I java.lang.Math: for random().
I java.lang.String: for text strings and input.
I java.util.Scanner: nextInt(), nextLine(), next()
Java Programming - Week 2. . . 45/46
Outline Functions and Methods Types and Classes Variables and Objects Summary and Homework
Homework This Week
Vending Machine
I Quickly read Chapters 5, 6, 7, and 8 in the text.
I P2. Birthday Day of the YearDetails are given athttp://eliza.newhaven.edu/javaG/attach/p2Birthday.pdf.
Java Programming - Week 2. . . 46/46