111
GSAMS’ GSAMS’ Un Un distinguished distinguished Lecture Series Lecture Series presents . . . presents . . . Java for the Java for the Impatient Impatient

GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Embed Size (px)

Citation preview

Page 1: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

GSAMS’GSAMS’UnUndistinguished distinguished Lecture SeriesLecture Series

presents . . .presents . . .

Java for the ImpatientJava for the Impatient

Page 2: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

WHOWHO@@

Russ Shackelford, B.A., M.A., M.S., Ed.S., Ph.D.

David Dagon, B.S., J.D., etc. David Dagon, B.S., J.D., etc.

[email protected]@[email protected]@cc.gatech.edu

Page 3: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

WHATWHATCovers essential Java syntaxCovers essential Java syntax

and debugging techniquesand debugging techniques

Presumes familiarity with computer, and an IDE or text editor

David Dagon:

Georgia Tech’s introductory computing course has the students use NTEmacs with JDE to edit their code. You can get a copy of this distribution at:

http://www.cc.gatech.edu/classes/cs1502

Look for the links on “Help with IDEs”

David Dagon:

Georgia Tech’s introductory computing course has the students use NTEmacs with JDE to edit their code. You can get a copy of this distribution at:

http://www.cc.gatech.edu/classes/cs1502

Look for the links on “Help with IDEs”

Page 4: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

A Note on Noise

• Some noise is good

• We must share the medium, and should be aware of others.

• However, please feel free to ask questions

Page 5: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

What is Java?

"A simple, object-"A simple, object-oriented, oriented, distributed, distributed, interpreted, robust, interpreted, robust, secure, architecture secure, architecture neutral, portable, neutral, portable, high-performance, high-performance, multithreaded, and multithreaded, and dynamic language”dynamic language”

-- Sun

Sounds like marketing;let’s take a closer look . . .

David Dagon:

FYI. The next set of slides give a brief explanation of each of these terms. Some of the slides introduce some complicated subjects; future sets of slides will cover them in greater detail.

David Dagon:

FYI. The next set of slides give a brief explanation of each of these terms. Some of the slides introduce some complicated subjects; future sets of slides will cover them in greater detail.

Page 6: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

“… object oriented …”

Java is an “object oriented” (or “OO”) language.

• It is possible (but seldom desirable) to write non-object oriented Java code (so-called “hybrid OO”).

• In an OO language, classes are used to encapsulate data (state) and behavior.

• Instances of a class are then used to manipulate data and drive the program.

• Classes are arranged in an hierarchy, or package structure.

Page 7: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

“… object oriented, …”Example:

A “Stack” is a class found in the packagejava.util. We create an instance of the classStack using the keyword new thus:

import java.util.*;Stack c = new Stack();c.push(“3”);

java.util.Stack x = new Stack();

David Dagon:

It’s difficult to come up with a simple example of an object. One might use java.lang.String; however, there are some exceptions to String creation built into Java. One could also use the java.lang.Integer class; however, this presumes some knowledge of wrapper classes.

Note also that I’ve called the Stack in this example “c”, instead of “myStack” or something similar. It’s very common to use the ‘my-’ prefix in object creation; however, those not used to OO language might find it confusing. To emphasize that the Stack instance is merely an object, we use the familiar variable ‘c’. Of course, we could have called the Stack “foo”.

David Dagon:

It’s difficult to come up with a simple example of an object. One might use java.lang.String; however, there are some exceptions to String creation built into Java. One could also use the java.lang.Integer class; however, this presumes some knowledge of wrapper classes.

Note also that I’ve called the Stack in this example “c”, instead of “myStack” or something similar. It’s very common to use the ‘my-’ prefix in object creation; however, those not used to OO language might find it confusing. To emphasize that the Stack instance is merely an object, we use the familiar variable ‘c’. Of course, we could have called the Stack “foo”.

This differs from procedural (e.g., C) and functional languages (e.g., Lisp) where other data structures would be used to model the Stack. More on classes in later slides . . .

Page 8: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

“… “… distributed, …”distributed, …”Java is also a distributed language.

It was built with networking in mind

Fully supports IPv4, with structures to support IPv6.

Includes support for “Applets”:small programs embedded inHTML documents.

See: java.net package RMI/CORBA

David Dagon: Java provides convenient access to the OSI Network layer. Other APIs allow one to access even lower layers.

David Dagon: Java provides convenient access to the OSI Network layer. Other APIs allow one to access even lower layers.

Page 9: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

“… “… interpreted, …”interpreted, …”

Java is an interpreted language, meaning that each instruction is translated into machine code at the time of execution, not during compilation.

This allows for platform neutrality:“WORA”

This allows one to rewrite andchange a program while itis running.

Penalty: speed

Page 10: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

“… “… robust, …”robust, …”

Java is simple--no pointers/stack concerns (for the most part)

In-bound checking at runtime of array pointers--no memory corruption and cryptic error messages.

Exception handling: try/catch/finally series allows for simplified error recovery

Strongly typed language:many errors caught duringcompilation.

Page 11: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Byte-code verification on loading (not just compilation).

Applet code runs in 'sandbox', with significant restrictions

Security is enforced by the SecurityManager class

Work-arounds for applet security restrictions include digitally signing code, andServlets

“… “… secure, …”secure, …”

Page 12: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

• Strengths of Java:– A real language, in demand in industry– Portability– Comparatively easy to learn– Difficult to destroy a machine with it ;-)– Advanced built-in GUI/Graphics features

• Weaknesses of Java:– Slow: interpreted and OO– GUI/Graphics via “Least Common Denominator” approach (due to platform independence)– Awkward/annoying syntax

Evaluation of JavaEvaluation of Java

Page 13: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Structure of Java ProgramsStructure of Java Programs• Applications (“normal” computer programs):

– Each program consists of multiple files.– Each file contains a class.– First method (module) called is: public static void main(String[ ] argv)

– The main method controls program flow (but OO orientation means that it starts a process that features decentralized control).

Page 14: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Structure of Java ProgramsStructure of Java Programs

• Applets (transportable over WWW):– Similar to applications, but...– First method is: public void init( )

– Remainder of applet is a series of handlers that respond to events (e.g., user actions).

– Program is executed by Java interpreter running in Web browser or applet viewer.

Page 15: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Sample Program (in a file Sample Program (in a file called “HelloWorld.java”)called “HelloWorld.java”)

public class HelloWorld

{

public static void main(String argv[])

{

System.out.println(“Hello World!”);

}

}

Page 16: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Basic SyntaxAll java programs contain (within one or more* classes):

public static void main (String a[ ]) { ... }

The Java interpreter runs until the main() returns, a System or Runtime exit is called, a fatal error occurs, or until the end of main is found.

David Dagon: The following slide is the traditional HelloWorld program. Note that white space is irrelevant. Also note that the naming of local variables is arbitrary (compare a[ ] to arg[ ]).

David Dagon: The following slide is the traditional HelloWorld program. Note that white space is irrelevant. Also note that the naming of local variables is arbitrary (compare a[ ] to arg[ ]).

Page 17: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

GoodBye Worldimport java.lang.Runtime; /* not necessary */class GoodByeWorld { public static void main (String arg[]) { Runtime.getRuntime().traceInstructions(true); Runtime.getRuntime().traceMethodCalls(true); System.out.println (”Here’s some stats:"); System.out.println (Runtime.getRuntime().totalMemory() + " total memory\n” + Runtime.getRuntime().freeMemory() + " available"); if (true) return; /* 1 */ System.exit(0); /* 2 terminates */ Runtime.getRuntime().exit(0); /* 3 terminates only if the thread is running */ } /* 4 --end of main*/ }//test

Page 18: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

VocabularyVocabulary• Structured Programming:

– A programming paradigm in which the actions (or verbs, or procedures) are emphasized.

• OO Programming:– A programming paradigm in which the actors (or nouns,

or objects) and their interaction is emphasized.

• Byte Compiler:– A compiler which translates human-readable source code into byte code (transportable to various virtual machines) instead of object code written for a specific kind of machine.

Page 19: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Vocabulary (cont’d)Vocabulary (cont’d)• Byte Interpreter:

– An interpreter which translates byte code into object code for a particular kind of machine and executes them on that machine.

• Byte Code:– An instruction for a virtual machine.

• Java Virtual Machine (JVM):– The virtual machine (software) for which all Java programs are compiled. A byte code interpreter is required to translate from the JVM byte code instructions into to instructions for a given actual machine.

Page 20: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Java’s PopularityJava’s Popularity• Keys to Java’s Popularity:

– An OO language that’s relatively simple.– Virtual Machine approach, allowing

transportability to various different kinds of computers (operating systems).

– Presence of JVM as part of Web browsers, encouraging movement of Java programs over the Web.

Page 21: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Java is not a purely OO language, and supports several primitive data types, including:

PrimitivesPrimitives

Primitive Type Default Value

boolean falsechar '\u0000' (null)byte (byte) 0short (short) 0int 0long 0Lfloat 0fdouble 0dvoid N/A

David Dagon: According to the Java Language Specification, void is a primitive. But introducing void to students might be confusing. We include it here to be complete; in teaching, you might omit this 9th primitive

David Dagon: According to the Java Language Specification, void is a primitive. But introducing void to students might be confusing. We include it here to be complete; in teaching, you might omit this 9th primitive

Page 22: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Variable Declarations

• Java:– <datatype> <identifier>;

• or (optional initialization at declaration)– <data type> <identifier> = <init value>;

int x;x = 3;int y = 5;

Page 23: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Naming Conventions

• Begin variable identifiers with abbreviation of their type:– i for int (integer)– f for float– b for boolean– ch for char– str for String

Page 24: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Examples• int iCounter;• int iNumStudents = 583;• float fGPA;• float fBatAvg = .406;• char chGender;• char chGender = ‘f’;• boolean bSafe;• boolean bEmpty = true;• String strPersonName • = “Fred”;• String strStreetName;

Page 25: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

OperatorsOperators• Assignment: =• Arithmetic: +, -, *, /, % (mod)

int iNumLect = 2;int iNumStudents = 583;int iStudentsPerLect;iStudentsPerLect = iNumStudents / iNumLect; // gives 291 due to integer division

int iNumQualPoints = 30;int iNumCreditHours = 8;float fGPA;fGPA = iNumQualPoints / iNumCreditHours; // gives 3.0 due to integer division

iVar = iVar * flVar// gives compile-time error

Page 26: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Shorthand OperatorsShorthand Operators• iCounter = iCounter + 1; OR iCounter++;• iCounter = iCounter - 1; OR iCounter--;• iCounter = iCounter + 2; OR

iCounter+=2;• iCounter = iCounter * 5; OR iCounter*=5;• latter 2 examples:

– it’s “op” then “equals” (e.g., +=2), not “equals” then “op” (e.g., isn’t =+2)

Page 27: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

1. C-style comments with /* */; no nesting

2. C++ style comments beginning //

3. A unique "doc comment" starting with /** ...*/ Fun with comments:

/*/

/* // */

///////////////////

/* ========= */

Some Comments on CommentsSome Comments on Comments

worthless

Never closed

Good for blocks

Page 28: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

/** * <PRE>* getName(int i) - returns the name at a* specified array location* </PRE>* @param int i - the index of the array to* be retrieved* @return String strName - the name * @see Employees#isEmployed() - called to* verify employment */ public String getName (int i) { if (myEmpl.isEmployed()) return myArray[i]; else return "Nada"; } // getName(int)

Javadoc

David Dagon: Javadoc can generate an API listing of your code

David Dagon: Javadoc can generate an API listing of your code

Page 29: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

@author @param@return @exception @deprecated // jdk 1.1 @since // jdk 1.1@serial // jdk 1.2

@ see <class name> @ see <full-class name> @ see<full-class

name#method.name>@ version

• You may include HTML tags (but avoid structuring tags, like <H1>, etc.)

• Javadoc comments should immediately preceed the declaration of the class, field or method. The first sentence should be a summary. Use the special javadoc tags--@. When '@' tags are used, the parsing continues until the doc compiler encounters the next '@'

tag.

Javadoc (Cont’d)

David Dagon: The @deprecated tag interacts with the compiler to turn off warnings.

David Dagon: The @deprecated tag interacts with the compiler to turn off warnings.

Page 30: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

ConstantsConstants• Valid:

– public final <type> <IDer> = <value>;

• Preferred:– public final static <type> <IDer> = <value>;– public final static int – iMIN_PASSING = 60;– public final static float fPI = 3.14159;

• Details on “why this syntax” to come soon...

Page 31: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Printing to ScreenPrinting to Screen• Various techniques:

– System.out.println(<arguments>);– System.out.println( ); // prints blank line– System.out.println(5); // prints 5– System.out.println(“Hello World”); // prints Hello World

– “println” vs. “print” in Java:• println includes “carriage return” at end, next print or println on new line

• print causes next print or println to begin at next location on same line

Page 32: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Printing (cont’d)Printing (cont’d)• When starting Java, there are at least three streams

created for you: System.in // for getting input System.out // for output

System.err // for bad news output

• These are InputStream and PrintStream objects

• Note: For Win95/NT System.out is

"almost" identical to System.err -

the both display to the screen

(the one exception is when using

DOS redirect, >, where System.out

is redirected, while System.err is

still put to the screen )

Page 33: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

System.out.println

("This line is printed out")

System.err.println

("This is the error stream's output");

These are both instances of the PrintStream class.There are other methods you might find useful in

these classes:

System.out.flush(); System.out.write(int);

System.out.write(byte[] buf,

int offset, int length);

Printing (cont’d)Printing (cont’d)

Page 34: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Decision StatementsDecision Statements• Pseudocode:

if (condition) then statementselse other statementsendif

• Java:if (condition) single statement;else single statement;

• or:if (condition){ statements;}else{ statements;}

Page 35: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Conditional AssignmentConditional Assignment

boolean b; int iCount;

b = checkCompletion();iCount = (b) ? 3 : 1;

Must resolve to boolean

If true . . .

. . . if false

<boolean> ? <true condition>: <false condition>

Page 36: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

ExamplesExamples

• Pseudocode:test_grade isofftype

Num...is_passing isoftype

Booleanis_passing <- TRUEif (test_grade < 60)

then is_passing <- FALSEendifprint (is_passing)

• Java: what happens here?boolean bPassing =

true;int iTestGrade;...if (iTestGrade < 70) bPassing = false;System.out.println (bPassing);

Page 37: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Boolean and Boolean and Relational OperatorsRelational Operators

• Boolean: Pseudocode: Java: AND AND && OR OR || NOT NOT !

• Relationalequal to = = =not equal to <> !=less than < <less than or equal to <= <=greater than > >greater than or equal to >= >=

Page 38: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

ErrorsErrors• Compile-time errors:

– Syntax errors: illegal language statements– Certain kinds of semantic errors.

e.g., type mismatch (assign a Character value to Boolean var)

• Run-time errors:– Certain kinds of semantic errors.

e.g., try to access non-existent dynamic data (dereference a nil/null pointer)

– Logic errors: legal program that produces wrong behavior

Page 39: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Debugging StrategiesDebugging Strategies

• Compile-time errors:– The compiler will yell at you about them.

• BUT . . . industry research shows . . .– It is a time-waster to:

• code sloppy• use the compiler to find your mistakes

• It is faster to:– check the “annoying details” of your code to catch them BEFORE compilation.

• Lesson: don’t become a compiler junkie!

Page 40: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Debugging StrategiesDebugging Strategies• Run-time errors:

– Programming environment provides tools for tracing values as code executes.

– But: the most basic tools are independent of the programming environment:

• 1. Code tracing: use your eyes and mind!

• 2. Use print statements: insert statments that tell you

what key values are at given points in your program.

• 3. Use DEBUG flags: build in print statements

in a way that lets you turn them on and off.

Page 41: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

The “DEBUG” Flag IdeaThe “DEBUG” Flag Idea

• In Pseudocode:// in the mainDEBUG is TRUE // or FALSE

// inside of procedure This_Proc . . .if DEBUG then print (“am entering proc This_Proc”)

print (“this_param: “, this_param:) print (“that_param: “, that_param:)endif

// code goes hereif DEBUG then print (“am leaving proc This_Proc”)

print (“this_param: “, this_param:) print (“that_param: “, that_param:)endif

Page 42: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

The “DEBUG” Flag IdeaThe “DEBUG” Flag Idea

• In Java:public static final boolean DEBUG = true;…public void myMethod(){ if (DEBUG) System.out.println (“Entering myMethod()”); … if (DEBUG) System.out.println (“Leaving myMethod()”);}

Page 43: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Source code files must have the ".java" extension. The file name should match the class name. This naming convention is enforced by most reasonable compilers. Thus, an improperly named java file, saved as "myTest.java":

class test { ... }

Compiled byte code has the ".class" extension.

Java File NamesJava File Names

Page 44: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Java Files:

1. Consist of the optional package statement, 2. followed by any necessary import statements

3. followed by the class name,

4. followed by any inheritance and interface declarations.

5. Note: if the file defines more than one class or interface, only one can be declared public, and the source file name must match the public class name.

Java File Structure

Page 45: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Thus:

package edu.gatech.cc.dagon.gsams-java; import java.util.*;import edu.gatech.cc.dagon.gsams-java.hashtable.*;import netscape.javascript.JSObject;import netscape.javascript.JSException;

public class SplayTree implements TreeType, TreeConstants { ...

}// SplayTree

Note the globally unique package name. Without a package specification, the code becomes part of an unnamed default package in the current directory.

An Average Java File

Page 46: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Import statements Come in three flavors:

import package.class; // 1 import package.*; // 2import java.lang.*; // 3 (Implicit)

What it does: provides the Java interpreter with a reference to other classes necessary for the compilation of the present .java file

What it does NOT: actually "import" or ”#include" the code. There’s no overheador object bloat.

Import Statements

Page 47: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Java maps fully qualified class names to a directory path, and therefore does not need an #include, #ifdef, etc. (and no preprocessor as well)

Thus:

java.awt.TextField

is mapped to:

java/awt/TextField

and dynamically loaded, as needed.

Why No #include statements?

David Dagon: This explains the mystery behind the error message reported when one attempts to run a file with the “.class” extension passed into the java VM:

java FooBar.class

Exception in thread "main" java.lang.NoClassDefFoundError: FooBar/class

Here, the VM looks for a file “FooBar in a folder called “class”

Also, some might argue that javadoc and doclets are types of preprocessors.

David Dagon: This explains the mystery behind the error message reported when one attempts to run a file with the “.class” extension passed into the java VM:

java FooBar.class

Exception in thread "main" java.lang.NoClassDefFoundError: FooBar/class

Here, the VM looks for a file “FooBar in a folder called “class”

Also, some might argue that javadoc and doclets are types of preprocessors.

Page 48: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Methods, Control Structures and Data

Structures

Page 49: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Java MethodsJava MethodsThere exists a single construct, the method, for both procedures and functions:

• when a procedure is called for, specify the return type “void” before method name

•Note: All methods must have parentheses for parameters . . . even if no parameters!

public void printHelloWorld( ) {

System.out.println(“Hello World!”);

} // of printHelloWorld

Page 50: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Single construct for both procedures and functions:

• when a function is called for, specify the appropriate return type before method name

Java MethodsJava Methods

public float average (float fNum1, float fNum2, float fNum3) { float fReturnVal; fReturnVal = (fNum1 + fNum2 + fNum3)/ 3; return (fReturnVal); } // of average

Page 51: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Writing Methods: A Larger LookWriting Methods: A Larger LookA Java requirement:

--All methods belong to an object (or class).--Name of object (or class) must be unambiguous when method called.--To run a program, there must be a class (whose name is the name-of-the-program), containing a special method called main:

a class method,

not aninstancemethod

visible to all

nothingreturned

Method name

for command line parameters

public static void main (String[ ] argv)

Page 52: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Multiple Selections via Multiple Selections via switchswitch

Use if construct for one selection.

Use if/else construct for double selection.

Use switch construct for multiple selection. (e.g., situations appropriate for if-elseif-elseif-else)

Note:

• Useful when making a selection among multiple values of the same variable.

• Not useful when selecting among values of different variables.

Page 53: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

• The switch statement can only be used with the following types:

int, char, short & byte

(You can cast floats, doubles, etc.)

• The case values must all be of the same type.

• The case values must all be FINAL constants.

Multiple Selections via Multiple Selections via switch--Notesswitch--Notes

Page 54: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Multiple Selections via Multiple Selections via switchswitch

switch (chGrade) { case ‘A’: case ‘a’: iCountOfAGrades++; break; case ‘B’: case ‘b’: iCountOfBGrades++; break; case ‘C’: case ‘c’: iCountOfCGrades++; break; case ‘D’: case ‘d’: iCountOfDGrades++; break; case ‘F’: case ‘f’: iCountOfFGrades++; break; default: System.out.println(“Invalid grade”); break;}

(assume these variables exist and have value)

If (chGrade==‘A’ || chGrade==‘a’)iCountOfAGrades++;

else if (chGrade==‘B’ || chGrade==‘b’)iCountOfBGrades++;

else if (chGrade==‘C’ || chGrade==‘c’)iCountOfCGrades++;

else if (chGrade==‘D’ || chGrade==‘d’) iCountOfDGrades++;

else if (chGrade==‘F’ || chGrade==‘f’) iCountOfFGrades++;

elseSystem.out.println (“Invalid grade”);

same

Page 55: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Multiple Selections via switch

Note the “optional” default case at the end of the switch statement. It is optional It is optional onlyonly in terms of syntax. in terms of syntax.

switch (iNumber) { case 1:

System.out.println (“One”);break;

case 2:System.out.println (“Two”);break;

case 3:System.out.println (“Three”);break;

default: System.out.println(“Not 1, 2, or 3”);

} // switch

In practice you should always include a ‘default’ case statement.

E.g., 1989 AT&T phone system crash

This wouldwork without

the default, but would be

poortechnique

Page 56: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Java Basics: Iteration ConstructsJava Basics: Iteration Constructs

• In Pseudocode, we had a single iteration construct, flexible enough to be used in all iteration contexts.

• Java, like most programming languages does not provide a single flexible construct.

• Instead, Java offers three special case loop constructs, each good for a particular context.

• Do not get accustomed to only one of them and try to use it for all situations.

Page 57: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Pseudocode:

i isoftype Num i <- 0 loop exitif (i =10) <some statements> i <- i + 1 endloop

Java Iteration Constructs: “For Loops”Java Iteration Constructs: “For Loops”

Java example:

int i; for (i=0; i<10; i++) { <some statements> }

Java syntax: for (<initialization>; <continue if>;<increment>)

Page 58: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

For Loopsint count; for (count = 0; count < 10; count ++)

for ( ; count < 10; count ++)

for (; count++<10;)

for (; ++count<10;)

for (int count =10; count -- > 0;)

for ( ; ; ) // infinite

for (count = 0; count < 10 && bNotDoneYet; count ++, otherCount--)

for (count = 0; count < 10; printCount(count++); )

Page 59: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Common Problems with For Loops include:

Java Iteration Constructs: “For Loops”Java Iteration Constructs: “For Loops”

for (i=0; i<N; i++);{ … }

for (int i=0; i<N; i++){…}

--variable declared inside for loop signature; poor style

--the variable may be needed outside the for loop structure

--Spins on ending semicolon; code in braces executed once!

Page 60: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Java example:

do { statement 1; ... statement N; } while (condition);

Java Iteration Constructs: “Do While Loops”Java Iteration Constructs: “Do While Loops”

Pseudocode:

loop statement 1 ... statement N exitif (NOT(condition)) endloop

Page 61: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Java example:

<get the first value> while (condition) { <process the

current value> <get the next value> }

Pseudocode:

loop <get the next value> exitif (NOT(condition))... <process the value> endloop

Java Iteration Constructs: “While Loops”Java Iteration Constructs: “While Loops”

Page 62: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

When repeating steps, people naturally want to follow the pattern:

get a value, then process that value

The while loop construct calls for the unnatural pattern:

obtain the first loop control value before entering the loop itself;

then, within the loop body,

first do the process steps,

then do the get next steps

Java Iteration Constructs: “While Loops”Java Iteration Constructs: “While Loops”

Page 63: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

--The term “control variable” refers to the variable whose value is tested to determine if the loop should continue for another iteration or halt.

--For example, variable thisVar, below:

while (thisVar < = SOME_CONSTANT)

--To determine which loop construct is appropriate for a given situation, ask yourself “where does the control variable’s value come from?”

Java Iteration Constructs: When to UseJava Iteration Constructs: When to Use

ASK:ASK:

Is it simply a count of the number of iterations?

Is it a value that the loop itself must compute?

Is it a value that already exists somewhere, and the loop only obtains it from elsewhere?

Page 64: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

The for loop: used when the control variable is a simple count of the number of iterations,

e.g.: “create a loop that reads and processes the next 100 numbers.”

The while loop: used when the control variable has a value that already exists and is simply obtained by the loop.

e.g.: “create a loop that reads in numbers and processes them until it reads in a 100.”

The do-while loop: used when the control variable’s value must be calculated by the loop itself.

e.g.: “create a loop that reads in numbers until their sum is greater than 100.”

Java Iteration Constructs: When to UseJava Iteration Constructs: When to Use

Page 65: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Which loop construct would you use if...

Java Iteration Constructs: ReviewJava Iteration Constructs: Review

You need to perform a series of steps exactly N times?

You need to traverse a linked list of unknown size, and stop when you find a certain value?

You need to perform a series of steps at least once, and continue performing these steps for an unknown number of times

Page 66: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Debugging Tools/Strategies: The Assert StatementDebugging Tools/Strategies: The Assert Statement

CS1502 has created a general purpose utility class to assist you in programming. (See the class web page, and labs.) One useful method is ASSERT(), which can be used to validate assumptions and conditions.

Precondition: statement that must be truebefore the method can begin execution.

Postcondition: statement that must be trueafter the method has executed.

Usage: util.ASSERT(iDenominator!=0,

“Can’t divide by zero!”); iFraction = iNumerator/iDenominator;

Page 67: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Writing Methods--Flawed ExampleWriting Methods--Flawed Examplepublic char letterGrade (int iGrade) { util.ASSERT(iGrade >= 0 && iGrade <=100, “iGrade param has invalid value.”); if (iGrade >= 90) return (“A”); if (iGrade >= 80 || iGrade < 90) return (“B”); if (iGrade >= 70 || iGrade < 80) return (“C”); if (iGrade >= 60 || iGrade < 70) return (“D”); if (iGrade <= 60) return (“F”);} // of letterGrade

What’s wrongwith this?

--Error: returns a --Error: returns a String, not a char!String, not a char!

--Style: multiple returns are --Style: multiple returns are to be avoided, if possibleto be avoided, if possible

--Style: use if/else chain to avoid --Style: use if/else chain to avoid unintended execution of codeunintended execution of code

Page 68: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Writing Methods--Repaired ExampleWriting Methods--Repaired Example

public char letterGrade (int iGrade){ char chReturnValue = ‘I’; util.ASSERT(iGrade >= 0 && iGrade <=100, “iGrade param has invalid value.”); if (iGrade >= 90) chReturnValue = ‘A’; else if (iGrade >= 80 && iGrade < 90) chReturnValue = ‘B’; else if (iGrade >= 70 && iGrade < 80) chReturnValue = ‘C’; else if (iGrade >= 60 && iGrade < 70) chReturnValue = ‘D’; else // given Assertion, iGrade must be < 60 chReturnValue = ‘F’; return (chReturnValue);} // of letterGrade

Is this right?

Page 69: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Writing Methods--Flawed ExampleWriting Methods--Flawed Example

/** * Calculate the recurrence relation, r(n) = r(n-1) + * r(n-2) - r(n-3), where: r(1)=1, r(2)=2, r(3)=3, n>=1. * @param is the value of recurrence relation to calculate. * @return the integer value of the recurrence relation at n. */public int recurrence (int iN) { int iReturnVal = 0; util.ASSERT(iN >= 1, “int param is less than 1”); if (iN == 1) iReturnVal = 1; else if (iN == 2) iReturnVal = 2; else if (iN == 3) iReturnVal = 3; else iReturnVal = recurrence (iN-1) + recurrence(iN-2) - recurrence(iN-3); return (iReturnVal);} // of recurrence

What’s wrongwith it?

Page 70: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Writing Methods--Repaired ExampleWriting Methods--Repaired Example

/** * Calculate the recurrence relation, r(n) = r(n-1) + * r(n-2) - r(n-3), where: r(1)=1, r(2)=2, r(3)=3, n>=1. * @param is the value of recurrence relation to calculate. * @return the integer value of the recurrence relation at n. */public int recurrence (int iN){ util.ASSERT ( iN >= 1, “int param is less than 1”); return (iN);} // of recurrence

Lesson: while creating code that works, remember to think!

Page 71: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Classes and ObjectsClasses and Objects

Class: describes the form of an object, a template or blueprint or mold specifies data representation, behavior, and inheritance (via variables, methods and parents)

Object: an instance of a class--has unique copy of every non-static variable (i.e., the “instance variables” but not the class variables).

Naming Conventions:Classes: Identifiers begin with cap letters for each word in the Identifier, e.g., NeuralNetwork.javaObjects: Identifiers begins with lower case letter, then caps for other words in identifier, e.g., myObjectIdentifier

Difference between “a class and an object of that class” is analogous to the difference between “a type and a variable of that type”.

KEY CONCEPT

Page 72: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Java Data StructuresJava Data Structures

Thus, to create what is logically a record, define a class (ala a type), specifying both:

the data fields of the record all the methods that can act upon those data.

Because we can use a class to encapsulate both the data and the methods associated with the what would be a record, there is no need for a record construct.

Java doesn’t need a record construct

Java doesn’t have a record construct.

Instead, one implements records (with methods) as a class.

In Java, any data structure that is not a primitive must be an object of some class.

Page 73: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Evolution of an Object: An ExampleEvolution of an Object: An Example

Pro: Straightforward, no special techniques

Con: No data type; no reusability, cannot create multiples of it.

Poor abstraction (none, except for data identifiers)

Pseudocode:

length isoftype Num read(length)

width isoftype Num read(width)

height isoftype Num read(height)

volume isoftype Num volume <- length * width * height

Page 74: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Evolution of an Object (cont’d)Evolution of an Object (cont’d)

Box_Type definesa record length isoftype Num width isoftype Num height isoftype Num volume isoftype Num endrecord

this_box isoftype Box_Type

read(this_box.length, this_box.width, this_box.height)

this_box.volume <- this_box.length * this_box.width*this_box.height

Pro: Grouping of data, better data abstraction: box as data entity, not just a set of variables.

More reusable: can easily get multiple boxes

Con: Direct manipulation of data

Low procedural abstraction: must think about “how to do it?” instead of “what I want to do?”

Page 75: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

How to model a box? (Java example)

class Box { int iLength; int iWidth; int iHeight;

public void setLength (int iNewLength) { util.ASSERT (iNewLength > 0, “iNewLength <= 0”); iLength = iNewLength; } // of setLength public void setWidth (int iNewWidth) { util.ASSERT (iNewWidth > 0, “iNewWidth <= 0”); iWidth = iNewWidth; } // of setWidth

public int getLength ( ) { return (iLength); } // of getLength

Evolution of an Object (cont’d)Evolution of an Object (cont’d)

Instance variables (because they’re not static)

Methods to change (‘modify’) instance variables

Method to get (‘access’) instance variable

Page 76: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

public void setHeight (int iNewHeight) { util.ASSERT (iNewHeight > 0, “iNewHeight <= 0”); iHeight = iNewHeight; } // of setHeight

public int getWidth ( ) { return (iWidth); } // of getWidth

public int getHeight ( ) { return (iHeight); } // of getHeight

public int getVolume ( ) { return ( getLength( ) * getWidth( ) * getHeight( ) ); } // of getVolume

} // of class Box

How to model a box? (Java example cont’d)

Evolution of an Object (cont’d)Evolution of an Object (cont’d)

Methods to get (‘access’) instance variables

Page 77: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Object TerminologyObject Terminology“Accessor” and “Modifier” Methods: “state objects.”

Accessor Methods:Accessor Methods: The “get” methods . . .

( The identifier name prefix “get” not required, but is preferred practice. )

Modifier Methods:Modifier Methods: The “set” methods . . .

( The identifier name prefix ‘set” not required, but is preferred practice. )

Allows us to restrict access to variables and thereby control their values. (Otherwise, we would have to include util.ASSERT statements everywhere!)

They can return a variable value, and can return something that is calculated (e.g. getVolume; no need for an iVolume attribute).

They return a value about the state of an object.

Page 78: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Using Objects: Creating a BoxUsing Objects: Creating a Boxclass BoxesExample { public static void main (String[ ] argv) { Box shoeBox; shoeBox = new Box( ); shoeBox.setLength(35); shoeBox.setWidth(19); shoeBox.setHeight(13); Box cdBox = new Box( ); cdBox.setLength(14); cdBox.setWidth(9); cdBox.setHeight(1);

int iTotalVolumeOfBoxes; iTotalVolumeOfBoxes = shoeBox.getVolume()

+ cdBox.getVolume(); System.out.println (“The combined volume of the boxes”); System.out.println (“is: “, iTotalVolumeOfBoxes); } // of main} // of class BoxesExampleProgram

A second class is used to create an instance of our box class.

The BoxesExampleclass has a mainmethod, and is runas a program

Page 79: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Using Objects: Creating a BoxUsing Objects: Creating a Boxclass BoxesExample { public static void main (String[ ] argv) { Box shoeBox; shoeBox = new Box( ); shoeBox.setLength(35); shoeBox.setWidth(19); shoeBox.setHeight(13); Box cdBox = new Box( ); cdBox.setLength(14); cdBox.setWidth(9); cdBox.setHeight(1);

int iTotalVolumeOfBoxes; iTotalVolumeOfBoxes = shoeBox.getVolume()

+ cdBox.getVolume(); System.out.println (“The combined volume of the boxes”); System.out.println (“is: “, iTotalVolumeOfBoxes); } // of main} // of class BoxesExampleProgram

First, we declaredeclarea variablecalled ‘shoeBox.’ At this point, shoeBoxis merely a nullreference.

Second, we instantiateinstantiate shoeBox.Values are assigned.

Page 80: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Using Objects: Creating a BoxUsing Objects: Creating a Boxclass BoxesExample { public static void main (String[ ] argv) { Box shoeBox; shoeBox = new Box( ); shoeBox.setLength(35); shoeBox.setWidth(19); shoeBox.setHeight(13); Box cdBox = new Box( ); cdBox.setLength(14); cdBox.setWidth(9); cdBox.setHeight(1);

int iTotalVolumeOfBoxes; iTotalVolumeOfBoxes = shoeBox.getVolume()

+ cdBox.getVolume(); System.out.println (“The combined volume of the boxes”); System.out.println (“is: “, iTotalVolumeOfBoxes); } // of main} // of class BoxesExampleProgram

These steps arerepeated for ournext variable,cdBox. Note that the1st two steps are herecollapsed intoone line:

Declaration & Instantiation

Page 81: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Using Objects: Creating a BoxUsing Objects: Creating a Boxclass BoxesExample { public static void main (String[ ] argv) { Box shoeBox; shoeBox = new Box( ); shoeBox.setLength(35); shoeBox.setWidth(19); shoeBox.setHeight(13); Box cdBox = new Box( ); cdBox.setLength(14); cdBox.setWidth(9); cdBox.setHeight(1);

int iTotalVolumeOfBoxes; iTotalVolumeOfBoxes = shoeBox.getVolume()

+ cdBox.getVolume(); System.out.println (“The combined volume of the boxes”); System.out.println (“is: “, iTotalVolumeOfBoxes); } // of main} // of class BoxesExampleProgram

Another variable is declared and assigned a value.

NOTE: We obtaininformation aboutthe box ONLY throughit’s accessor methods

Page 82: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Using Objects: Creating a BoxUsing Objects: Creating a Boxclass BoxesExample { public static void main (String[ ] argv) { Box shoeBox; shoeBox = new Box( ); shoeBox.setLength(35); shoeBox.setWidth(19); shoeBox.setHeight(13); Box cdBox = new Box( ); cdBox.setLength(14); cdBox.setWidth(9); cdBox.setHeight(1);

int iTotalVolumeOfBoxes; iTotalVolumeOfBoxes = shoeBox.getVolume()

+ cdBox.getVolume(); System.out.println (“The combined volume of the boxes”); System.out.println (“is: “, iTotalVolumeOfBoxes); } // of main} // of class BoxesExampleProgram

Comments:

1. Variable declaration and assignment is mixed together. A more complex program might require better organization

2. “Hybrid OO”: We have classes, but everything occurs within a static method, “main”, making things linear. This is fine for small programs, but larger programs would benefit from “Pure OO”. Keep this in mind; it becomes very important later.

Page 83: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Review: Our Box Model

class Box { int iLength; int iWidth; int iHeight;

public void setLength (int iNewLength) { util.ASSERT (iNewLength > 0,

“iNewLength <= 0”); iLength = iNewLength; } // of setLength

public int getLength ( ) { return (iLength); } // of getLength public void setWidth (int iNewWidth) { util.ASSERT (iNewWidth > 0,

“iNewWidth <= 0”); iWidth = iNewWidth; } // of setWidth

public int getWidth ( ) { return (iWidth); } // of getWidth

public void setHeight (int iNewHeight) { util.ASSERT (iNewHeight > 0,

“iNewHeight <= 0”); iHeight = iNewHeight; } // of setHeight

public int getHeight ( ) { return (iHeight); } // of getHeight

public int getVolume ( ) { return ( getLength( ) * getWidth( )

* getHeight( ) ); } // of getVolume} // of class Box

Page 84: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

We found that to use this class, we had to ‘declare an object’. “Declaring an object” really means declaring a reference to an object.”

A reference is an implict (or automatic) pointer that can point to an object of the specified class.

Thus, the code: Box shoeBox;

• does not create an object of class Box.• does create a reference (or ptr) shoeBox that can point to an object of class Box.• gives us what amounts to a ptr to a Box which is null:

shoeBox

Declaring ObjectsDeclaring Objects

Page 85: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Objects and References

• To make the reference shoeBox be not null, it is necessary to instantiate it, e.g.,

shoeBox = new Box( );

So far, we have: Box shoeBox; shoeBox

shoeBox

an instance of class Box

When Java encounters the keyword “new”, it allocates space in memory for an instance of that object. Now, shoeBox refers to an instance of class Box, i.e., an object.

Note that the instance (or object) “gets” everything defined in class Box. It has unique copies of all the variables. (The methods are shared between all instance of the class, but Java knows which instance you are referring to.)

Page 86: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

shoeBox

The data fields (“attributes”):int iLength;int iWidth;int iHeight;

What can be done to that data(“methods”):public void setLength (int iNewLength)public int getLength ( )public void setWidth (int iNewWidth)public int getWidth ( )public void setHeight (int iNewHeight)public int getHeight ( )public int getVolume ( )

(a reference

to an object

of class Box)

A closer look:

Objects and References

Page 87: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Objects and ReferencesBox shoeBox = new Box();Box cdBox = new Box();Box present = new Box();

The data fields (“attributes”):int iLength;int iWidth;int iHeight;

What can be done to that data(“methods”):public void setLength (int iNewLength)public int getLength ( )public void setWidth (int iNewWidth)public int getWidth ( )public void setHeight (int iNewHeight)public int getHeight ( )public int getVolume ( )

shoeBoxshoeBox

The data fields (“attributes”):int iLength;int iWidth;int iHeight;

What can be done to that data(“methods”):public void setLength (int iNewLength)public int getLength ( )public void setWidth (int iNewWidth)public int getWidth ( )public void setHeight (int iNewHeight)public int getHeight ( )public int getVolume ( )

cdBoxcdBox

The data fields (“attributes”):int iLength;int iWidth;int iHeight;

What can be done to that data(“methods”):public void setLength (int iNewLength)public int getLength ( )public void setWidth (int iNewWidth)public int getWidth ( )

. . .

presentpresent

Each time we instantiatea Box, therefore, we get a unique copy to work with. This is one of the most powerful aspect of Object-Oriented Programming!

David Dagon:

(Cautionary Note: Here, we suggest that each object gets a unique copy of each method. Although each object is allocated unique memory space for variables, Java efficiently shares methods in common with all objects. For now, you might find it helpful to picture objects in the manner, even though it’s not technically what happens with the heap’s method space in the Java Virtual Machine.)

David Dagon:

(Cautionary Note: Here, we suggest that each object gets a unique copy of each method. Although each object is allocated unique memory space for variables, Java efficiently shares methods in common with all objects. For now, you might find it helpful to picture objects in the manner, even though it’s not technically what happens with the heap’s method space in the Java Virtual Machine.)

Page 88: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

What do we conclude from this?

1. all objects are dynamic data.

2. because all objects are dynamic, Java “knows” that, whenever we reference an object, it must “follow the pointer”.

For example: shoeBox.setLength(35); shoeBox.setWidth(19); shoeBox.setHeight(13);

is equivalent to the pseudocode: shoeBox^.setLength(35) shoeBox^.setWidth(19) shoeBox^.setHeight(13)

Objects and References

Page 89: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Java is advertised as “having no pointers.”

In reality, Java is mostly pointers! Every non-primitive datum must be an object. All objects are dynamic data, accessible via references. And references are really implicit pointers.

Java does not have explicit pointers: There exists no way to explicitly manipulate pointers. There is no explicit dereferencing operator

So: if you don’t know about pointers, then references are “magic” if you do understand pointers, then you know what references really are!

References vs. Pointers

Page 90: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Calling (or Invoking) MethodsCalling (or Invoking) Methods

•Restrictions:

1. Invocation must be unambiguous re: which object or class the method is to act upon.

2. If the method call appears inside a class, then that class is presumed to contain the appropriate method:

class CompanyStock { public double getAmountEarned ( ) { double dOpen = getOpenValue(); /* calls method in this class */ double dClose = getCloseValue(); /* calls method in this class */ . . .//etc. etc. } // of getAmountEarned

public double getOpenValue() { return 1234.5d; } public double getCloseValue(){ return 2345.6d; } } // of CompanyStock

Page 91: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

• If the method is NOT inside the class where method declared, then the object must be specified.

class WallstreetJitters { public void panicSell ( ) { Greenspan fedChair

= new Greenspan(); if (fedChair.raisesInterest())

{ buyOnMargin(); }

else{

sellAllStock();}

} // of panicSell} // of WallstreetJitters

Calling (or Invoking) MethodsCalling (or Invoking) Methods

Greenspan class must have this method!

These methods must appear in this class!

FORMAT: <object reference>..<method name>

Page 92: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Java ConstructorsJava Constructors

Motivation: We need a means of initializing the attributes of a new object (or “instance”) when it is created. Means: “Constructor methods” that are invoked automatically upon “instantiation” (creation) of new object. Example:public Box (int iNewLength, int iNewWidth, int iNewHeight) { setLength (iNewLength); setWidth (iNewWidth); setHeight (iNewHeight);} // of constructor

Note: Constructor method has same identification as the class.

Can now do: Box subwooferBox = new Box (46, 46, 82);

Equivalent to: Box subwooferBox = new Box; subwooferBox.setLength(46); subwooferBox.setWidth(46); subwooferBox.setHeight(82);

Page 93: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Java Constructors

A class may have more than one constructor.

If so, then each constructor must have unique formal parameter list.

Constructor calls must match one of the available constructors

Terminology: Creating multiple methods with same identifier is called “method overloading.”

Given: public String ( ) public String (String value)

We can: String strInput1 = new String ( ); String strInput2 = new String (“A valid constructor.”);

Such that:

strInput1 will be an empty String (with the value ““)strInput2 will be a String containing “A valid constructor.”

Page 94: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Java Constructors:Another Example

class person { String strName; int iAge;

public Person (String strNewName){ setName (strNewName); } // of constructor

public Person (String strNewName, int iNewAge) { setName (strNewName); setAge (int iNewAge); } // of constructor

public void setName (String strNewName){ strName = strnewName; } // of setName

public void setAge (int iNewAge) { iAge = iNewAge: } // of setAge} // of Person

Note that theconstructors call

the modifiers

Page 95: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Can now create a new Person via: Person guitarist1 = new Person (“Clapton”); Person guitarist2 = new Person (“Hendrix”, 27); Determining which constructor to invoke requires unique signature.

Signature means “identifier and parameter list”

Thus, one cannot do: public Person (String strNewFirstName) { . . . } // of constructor

public Person (String strNewLastName) { . . . } // of constructor

due to ambiguity. Can’t tell which one to invoke.

Java Constructors

Page 96: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Java Constructors

Default constructors:

If you don’t define a constructor, a default constructor will be automatically invoked.

The default constructor expects no parameters.

The default constructor initializes instance variables to standard Java default values (0 for nums, false for booleans, null for references).

Default constructor equivalent to: public Person ( ) { ; } // of default constructor

You can override this by creating your own default constructor (no params) that does contains code.

Page 97: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Java Constructors

Constructors CANNOT have return values: Do NOT do this:

public int Person ( ) { . . . // whatever code } // of constructor

public void Person ( ) { . . . // whatever code } // of constructor

Nope!

A return value (including void) means that the method is NOT a constructor, and it won’t be auto-invoked.

Page 98: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Creating Instances of Classes

Involves three things:

1. Creating the reference: Box thisBox ;

2. Instantiating the object: thisBox = new Box( );

OR do first two steps at once, e.g., Box thisBox = new Box( )

3. Having constructor(s) set initial values:

public Box (int iNewLength, int iNewWidth, int iNewHeight) { setLength (iNewLength); setWidth (iNewWidth); setHeight (iNewHeight);} // of constructor

With an appropriate constructor, we can do all three at once:

Box thisBox = new Box (10, 5, 25);

Page 99: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Objects and References

Distinguish between primitives and objects.

Assignment with Primitives:

Code: Memory:

int x;x

int y;

iThis = 5; x=5

iThat = iThis;

yx

x=5 y=5

y

Page 100: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

L=3, W=9, H=2

Objects and ReferencesObjects and References

Assignment with References to Objects:

Code: Memory:

Box box1;Box box2;

box1box2

box1 = new Box(8, 5, 7); L=8, W=5, H=7box1

box2

box2 = box1;// note: two references// but only one object

box1

box2

box1 = new Box(3, 9, 2);

box1

box2

box1 = box2;// Old reference lost!

box1

box2

L=8, W=5, H=7

L=8, W=5, H=7

L=3, W=9, H=2

L=8, W=5, H=7

Page 101: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Instance vs. Class Declarations

A distinction that applies to both:• variables• methods

An instance <variable or method> is one thatbelongs to each object of a class.

A class <variable or method> is one that belongs only to the class itself.

The keyword static:

• indicates a class variable or class method.

• absence of the keyword static indicates an instance variable or instance method.

Page 102: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Instance vs. Class Variables

Suppose we wanted to track the total number of objects created.

Consider:

class Human { String strName; int iPopulation = 0;

public Human (String strName) { this.strName = strName; iPopulation++; //WRONG! } // of constructor

} // of Human

Declares a strName String for each instance . Thus, each Human will have its own name.

But . . . Also declares an iPopulation counter for each instance of Human. Thus, each Human will have its own iPopulation variable, each having a value of one. This makes no sense!

Page 103: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

class Human { String strName; static int iPopulation = 0;

public Human (String strName) { this.strName = strName; iPopulation++; } // of constructor

} // of Human

Instance vs. Class Variables

one change

As we know, this declares a strName String for each instance.

Thus, each Human will have its own name.

NOTE: Each Human does not get an iPopulation counter. This declares a single iPopulation counter for the class Human itself. It is a class variable. Thus, each Human will increment this single shared counter by 1.

Page 104: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Instance vs. Class Variables:When to Use

Use instance variables whenever each object should have its own variable. e.g.,

attributes of the particular object.

Use a class variable whenever the class itself should maintain a single copy of datum pertaining to all instances of the class. e.g.,

population counts. summary data. assigning serial numbers. shared resources.

Page 105: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Instance vs. Class Variables

Constants Revisited:

class ConstantExample { final int iMAXSIZE = 10; } // of ConstantExample

Declares a different-but-identical constant for each instance of the class.

Wasteful with zero benefit.

Declares a single constant for use by all instances of the class.

class ConstantExample { static final int iMAXSIZE = 10; } // of ConstantExample

Page 106: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

class MyObject { String name; public MyObject (String n) { name = n; }

public String toString () { return (name);

}}

public class SwapTester {

public static void swapInt (int x, int y) { int temp; System.out.println ("Doing swapInt"); temp = x; x = y; y = temp; }

Objects vs. References--An ExampleObjects vs. References--An Example

Page 107: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

/* in class Basics (cont’d) . . . */

public static void swapObject1 (MyObject x, MyObject y) { MyObject temp; System.out.println ("Doing swapObject1"); temp = x; x = y; y = temp; }

public static void swapObject2 (MyObject x, MyObject y) { MyObject temp = new MyObject ("temp"); System.out.println ("Doing swapObject2"); temp.name = x.name; x.name = y.name; y.name = temp.name; }// swapObject2

Page 108: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

/* in class SwapTester (cont’d) . . . */

public static void main (String argv[]) { int x, y, z; x = 5; y = 10; z = y; y = 5;

System.out.println ("x=" + x + " y=" + y + " z=" + z); System.out.println ("x==5 is " + (x==5)); System.out.println ("x==y is " + (x==y)); System.out.println ("y==z is " + (y==z)); swapInt (x, z);

System.out.println ("x=" + x + " y=" + y + " z=" + z); System.out.println ();

Output for this portion of the program:

x=5 y=5 z=10x==5 is truex==y is truey==z is falseDoing swapIntx=5 y=5 z=10

Page 109: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

/* in class SwapTester’s main method (cont’d) . . . */ String a, b, c;

a = "hello"; b = new String ("hello"); c = b; System.out.println ("a=" + a + " b=" + b + " c=" + c); System.out.println ("a==hello is " + (a=="hello")); System.out.println ("b==hello is " + (b=="hello")); System.out.println ("a==b is " + (a==b)); System.out.println ("a.equals(b) is " + (a.equals(b))); System.out.println ("b==c is " + (b==c)); System.out.println ("b.equals(c) is " + (b.equals(c))); System.out.println ();

a=hello b=hello c=helloa==hello is trueb==hello is falsea==b is falsea.equals(b) is trueb==c is trueb.equals(c) is true

Output

Page 110: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

/* in class SwapTester’s main method (cont’d) . . . */ MyObject p, q, r, s;

p = new MyObject ("hello"); q = new MyObject ("hello"); r = q; s = new MyObject ("world"); System.out.println ("p=" + p + " q=" + q + " r=" + r + " s=" + s); System.out.println ("p==q is " + (p==q)); System.out.println ("q==r is " + (q==r)); swapObject1 (p, s); System.out.println ("p=" + p + " q=" + q + " r=" + r + " s=" + s); swapObject2 (p, s); System.out.println ("p=" + p + " q=" + q + " r=" + r + " s=" + s); }// end of main}// class SwapTester

p=hello q=hello r=hello s=worldp==q is falseq==r is trueDoing swapObject1p=hello q=hello r=hello s=worldDoing swapObject2p=world q=hello r=hello s=hello

Output:

Page 111: GSAMS’ Undistinguished Lecture Series presents... Java for the Impatient

Key Concepts: = and == with objects and references. Parameter passing, call by value, call by constant reference.

Summary: Java has no pointers, only references. Null is a special value that means "no object" or "absenceof reference”.

All objects and arrays (i.e., everyting except primitivetypes) are handled by reference

= assigns references to objects (use clone() to copy theobject itself).

== and != test references with references (use equals() totest the objects themselves).

Objects vs. References: SummaryObjects vs. References: Summary