Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming...

86
Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion and Casting Random Numbers Arrays & ArrayList<E> Driver, Bean, Utility Reference versus variable MyGregCalendar The new keyword Implicit versus explicit params Return mutable reference member cloned Static fields such as Math.PI passByVal, passByRef, swap JavaDocs

Transcript of Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming...

Page 1: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Lecture 2 Content:

Control Structures: Branching logicControl Structures: Looping logicDiagramming Reading Files from ScannerType ConversionsPromotion and CastingRandom NumbersArrays & ArrayList<E>Driver, Bean, UtilityReference versus variableMyGregCalendarThe new keywordImplicit versus explicit paramsReturn mutable reference member clonedStatic fields such as Math.PIpassByVal, passByRef, swapJavaDocs

Page 2: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Control Structures

See edu.uchicago.cs.java.lec02.control

Page 3: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Shorthand

See blackboard

Page 4: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Arrays & ArrayLists

See edu.uchicago.cs.java.lec02.arrays

Page 5: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Arrays

• arrays of prmitivies• arrays of Objects• multidimentional arrays

Page 6: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

• Array: Sequence of values of the same type

• Construct array:new double[10]

• Store in variable of type double[]:

double[] dDatas = new double[10];

• When array is created, all values are initialized depending on array type:

• Numbers: 0

• Boolean: false

• Object References: null

Arrays

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 7: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

• Array: Sequence of values of the same typedouble[] dValues = {2.5, 8.1, 3.79, 0, 6.0};

The above declares and intializes an array of double[]

String[] strNames = {"Harry", "Lary", "Mary", "Perry"};

The above declares and initializes an array of String[]

Arrays: declare and init

Page 8: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

ArraysUse [] to access an element:

double[] dValues = new double[10];

dValues[2] = 29.95;

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 9: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

• Using the value stored:

System.out.println("The value of this data item is " + dValues[2]); //dValues[2] (a double) is promoted to a String.

• Get array length as dValues.length (Not a method!)

• Index values range from 0 to length - 1

• Accessing a nonexistent element results in a bounds error:

double[] values = new double[10]; values[10] = 29.95; // ERROR – out of bounds

• Limitation: Arrays have fixed length!

Arrays

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 10: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Declaring Arrays

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 11: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Syntax 7.1 Arrays

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 12: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

// Don't do this int[] accountNumbers; double[] balances;

Make Parallel Arrays into Arrays of Objects

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 13: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Avoid parallel arrays by changing them into arrays of objects:

BankAccount[] accounts;         

Make Parallel Arrays into Arrays of Objects

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 14: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

multidimensional arrays

• int[][] nNumbers = new int[3][4];• boolean[][] bExams = {

new boolean[6],new boolean[9],new boolean[3],new boolean[8]

}; //ragged array

Page 15: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Array Lists

• ArrayList class manages a sequence of objects

• Can grow and shrink as needed (it's a Vector)

• ArrayList class supplies methods for many common tasks, such as inserting and removing elements

• ArrayList is a generic class:

ArrayList<T>

collects objects of type parameter T:

ArrayList<String> strNames = new ArrayList<String>();strNames.add("Emily");strNames.add("Bob");strNames.add("Cindy");

• size method yields number of elementsBig Java by Cay Horstmann

Copyright © 2009 by John Wiley & Sons. All rights reserved.

Page 16: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

To add an object to the end of the array list, use the add method:

names.add("Emily");names.add("Bob");names.add("Cindy");

Adding Elements

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 17: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

• To obtain the value an element at an index, use the get method

• Index starts at 0

• String strName = strNames.get(2);// gets the third element of the array list

• Bounds error if index is out of range

• Most common bounds error:

int n = strNames.size();strName = strNames.get(n); // Error // legal index values are 0 ... n-1

Retrieving Array List Elements

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 18: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

• To set an element to a new value, use the set method:

strNames.set(2, "Carolyn");

Setting Elements

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 19: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

• To remove an element at an index, use the remove method:

strNames.remove(1);

Removing Elements

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 20: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

strNames.add("Emily");strNames.add("Bob");strNames.add("Cindy");strNames.set(2, "Carolyn");strNames.add(1, "Ann");strNames.remove(1);

Adding and Removing Elements

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 21: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Syntax 7.2 Array Lists

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 22: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Promotion and Casting

See edu.uchicago.cs.java.lec02.cast

Page 23: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Promotion & Casting• Automatic promotion; this occurs when one operand is of lesser precision than the other and completing the operation will not reduce precision of result.

double dResult = nNumerator / dDenominator;

In the above case, nNumerator is promoted to a double.

int nResult = (int)(nNumerator / dDenominator);

you must CAST because you can't assign the return value, intially a double (64 bit flotating precision) to an int (32 bit int precision)

Page 24: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• Cast converts a value to a different type:

double dBalance = dTotal + dTax; //dBalance == 10.89int nDollars = (int) dBalance; //nDollars == 10

• Math.round converts a floating-point number to nearest integer:

long lRounded = Math.round(dBalance); // if dBalance is 13.75, then lRounded is set to 14

Cast and Round

Page 25: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

Syntax 4.2 Cast

Page 26: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Type Conversion

• Each Wrapper class has some parse functions.• Integer.parseInt(String str);• Double.parseDouble(String str);• Byte.parseByte(String str);• Boolean.parseBoolean(String str);• etc.

Page 27: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

The New Keyword

See edu.uchicago.cs.java.lec02.newkeyword

Page 28: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Using the new Keyword

• Unless you use the ‘new’ keyword, nothing has been instantiated and the object does NOT exist in memory.

• (the exception is static)• Driver/Bean/Utility

Page 29: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• Example:

public class Financial{ public static double percentOf(double dP, double dA) { return (dP / 100) * dA; } // More financial methods can be added here.}

• Call with class name instead of object:

double dTax = Financial.percentOf(dTaxRate, dTotal);

Static Methods

Page 30: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• Here is another example:

• public class Geometry{ public static double area(Rectangle rec) { return rec.getWidth() * rec.getHeight(); } // More geometry methods can be added here.}

Static Methods

Page 31: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Implicit versus Explicit Parameters

• The implicit parameter is the object reference, whereas the explicit parameter(s) are/is the argument(s) to the method.

• strName.indexOf(cSpace);• Math.pow(2,3); //no implicit param -- static• Most often, when we refer to parameters, we

mean the explicit parameters.

Page 32: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• A static method does not operate on an object

double dY = mthObject.sqrt(); // Error

double dY = Math.sqrt(9); //correct

• Naming convention: Classes start with an uppercase letter; objects start with a lowercase letter:

• Sometimes you will find nonstatic implementations in Java that would seem like perfect candidates for static, such as Random.

Random rnd = new Random();

rnd.nextInt(10); //correct

Random.nextInt(10); //incorrect

Calling Static Methods

Page 33: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Suppose Java had no static methods. How would you use the Math.sqrt method for computing the square root of a number nX?

Answer:

Math mat = new Math();double dResult = mth.sqrt(nX);

Self Check 8.12

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 34: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

Syntax 4.3 Static Method Call

Page 35: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• A static variable belongs to the class, not to any object of the class:

public class BankAccount { ... private double dBalance; private int nAccountNumber; private static int nLastAssignedNumber = 1000; }

• If nLastAssignedNumber was not static, each instance of BankAccount would have its own value of nLastAssignedNumber

Static Variables

Page 36: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• Static constants, which may be either private or public: public class BankAccount { ... public static final double OVERDRAFT_FEE = 5;

// Refer to it as BankAccount.OVERDRAFT_FEE }

//in the above case, OVERDRAFT_FEE is a constant

Static Variables

Page 37: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

Syntax 4.1 Constant Definition

Page 38: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• A final variable is a constant

• Once its value has been set, it cannot be changed

• Named constants make programs easier to read and maintain

• Convention: Use all-uppercase names for constants

final double QUARTER_VALUE = 0.25; final double DIME_VALUE = 0.1; final double NICKEL_VALUE = 0.05; final double PENNY_VALUE = 0.01; dPayment = nDollars + nQuarters * QUARTER_VALUE + nDimes * DIME_VALUE + nNickels * NICKEL_VALUE + nPennies * PENNY_VALUE;

Constants: final

Page 39: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Harry tells you that he has found a great way to avoid those pesky objects: Put all code into a single class and declare all methods and variables static. Then main can call the other static methods, and all of them can access the static variables. Will Harry’s plan work? Is it a good idea?

Answer: Yes, it works. Static methods can access static variables of the same class. But it is a terrible idea. As your programming tasks get more complex, you will want to use objects and classes to organize your programs.

Self Check 8.15 - funny

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 40: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Strings

Page 41: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Useful methods of String

• char charAt(int index)• int compareTo(String anotherString)• boolean endsWith(String suffix)• int indexOf(multiple)• int length()• String substring(int begin, int end)• String trim()

Page 42: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• Immutable class: Has no mutator methods (e.g., String):

String strName = "John Q. Public"; String strUppercased = strName.toUpperCase();

// strName is not changed

• It is safe to give out references to objects of immutable classes; no code can modify the object at an unexpected time. The implicit paramater is immutable!

String is Immutable

Page 43: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

String Pools• To optimize performance, the JVM may keep a String

in a pool for reuse. Sometimes is does and sometimes it doesn't. Very unpredictable.

• This means that in some VMs (or even the same VM at different times), two or more object references may be pointing to the same String in memory.

• However, since you can not rely upon pooling, you MUST assume that each string has its own object reference.

• Besides, since Strings are immutable, you need not consider the consequences of passing a reference.

Page 44: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• A string is a sequence of characters

• Strings are objects of the String class

• A string literal is a sequence of characters enclosed in double quotation marks:

"Hello, World!"

• String length is the number of characters in the String• Example: "Harry".length() is 5

• Empty string: ""

• Although we use the shortcut: String strName = “Robert”; we are actually doing this: String strName = new String(“Robert”);

The String Class

Page 45: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• Use the + operator:

String strName = "Dave"; String strMessage = "Hello, " + strName; // strMessage is "Hello, Dave"

• If one of the arguments of the + operator is a string, the other is converted to a string

String strA = "Agent”;int n = 7;String strBond = strA + n; // strBond is "Agent7"

Concatenation

Page 46: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• String str2 = strGreeting.substring(7, 12); // str2 is "World"

• Substring starts at the begin-index and ends at end-index - 1

Substrings

Page 47: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Escape Sequences

• to include the quotes in a string, use the escape sequences:

• strOne = "\"Quotation\"";• to print \\• StrBackSlashes = "\\\\";• Unicode valueshttp://oreilly.com/actionscript/excerpts/as3-

cookbook/appendix.html

Page 48: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Escape SequencesEscapeSequence Character

\n newline

\t tab

\b backspace

\f form feed

\r return

\" " (double quote)

\' ' (single quote)

\\ \ (back slash)

\uDDDDcharacter from the Unicode character set (DDDD is four hex digits)

Page 49: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Keyboard Input

edu.uchicago.cs.java.lec02.scanner

Page 50: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Keyboard Input

• Scanner -- or you can define your own

• Scanner scn = new Scanner(System.in);• Scanner scn = new Scanner(File filSource);

throws FileNotFoundException• strInput = scn.nextLine();

Page 51: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• System.in has minimal set of features — it can only read one byte at a time

• In Java 5.0, Scanner class was added to read keyboard input in a convenient manner

• Scanner scn = new Scanner(System.in); System.out.print("Enter quantity:"); int nQuantity = scn.nextInt();

• nextDouble reads a double

• nextLine reads a line (until user hits Enter)

• next reads a word (until any white space)

Reading Input

Page 52: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Random

See edu.uchicago.cs.java.lec02.random

Page 53: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Random numbers

• import java.util.Random;• int n = rnd.nextInt();• double d = rnd.nextDouble();• int n = rnd.nextInt(int nNum);rnd.nextInt(20); //0-19//in this above case 20 is multipled by some real

number between 0 and 1 exclusive; then converted to int; it will return 0 to 19.

Page 54: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Pass by value and reference

See edu.uchicago.cs.java.lec02.passby

Page 55: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

pass by value pass by reference

Action: Tell my accountant how much I intend to spend on a new car. Change in bank account: no change.

Action: Swipe debit card and enter pin at the Bently dealership.

Change in bank account: -125k.

Page 56: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Primitives versus Objectsmemory

Primitives Objects

Variables store values and are allocated memory depending on their type. How much?...refer to Java Primitives slide.

References store memory addresses. The size of the allocation for the object reference is VM specific, but is usually the native pointer size; 32bits in 32-bit VM, and 64bits in a 64-bit VM.

Garbage collected when out-of-scope. Garbage collected when out-of-scope.

Passed into methods by value Passed into methods by reference

Page 57: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Objects

See edu.uchicago.cs.java.lec02.console21

Page 58: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Class Object

• A blueprint is to a house as a class is to an object• Class = Blueprint

Page 59: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Class Objects

Page 60: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Class Object

• A blueprint is to a car as a class is to an object• Class = Blueprint

Page 61: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Class Objects

Page 62: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Spot the “class” here

Page 63: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Constructors

• Has the same name and as the class (very important - otherwise not a constructor)

• The ONLY method that is allowed to be capitalized; and must be capitalized.

• If you don't define a constructor, a default no-arg constructor is implied that will set fields to zero, or null.

• If you define any constructor, then the default constructor is not available to you.

Page 64: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Using anonymous objects

• Anonymous objects are useful for "hard-coding" objects and passing them into Constructors.

• The enclosing class will contain a reference to this object, so we can find it later.

Page 65: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Review of Eclipse

Page 66: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Important shortcuts in EclispeCtrl-space – materialize template code“.” - when used on a class or object reference, this pulls up code-complete.Alt-shift-r – used to rename variable-names globally throughout the applicationCtrl-shift-f – FormatRefactor || Extract method() / Convert Local Variable to FieldSource || Generate

Window || Preferences || Java || Code Style || Formatter || Edit || On/Off Tags

//@formatter:off//####################### PSEUDOCODE #########################${cursor}//############################################################//@formatter:on

Window || Preferences || Java || Code Style || Fields || Edit List: b,y,s,c,n,l,d,f,str

Page 67: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Console21

Page 68: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

One player and one dealer play against one another in a game of 21. A player starts with some money (100 dollars) and bets 10 dollars each hand. The game is played with a 52-card chute. The game ends when the player decides to quit.

Game-play starts with the player introducing himself by name, and the dealer dealing himself and the player two cards each.

After the intial dealIf the dealer and the player both have blackjack, then push, ask to play again. If the dealer has blackjack then the player loses his 10 dollars, ask to play again.If the player has blackjack, then the player wins 15 dollars, ask to play again

If neither dealer nor player have blackjack, then the player has the option to either hit (so long as the total value of his hand is less than or equal to 21) or stick. If the player busts when hitting, then the player loses his 10 dollars, and is asked to play again.If the player does not bust, then the dealer is obliged to hit while his total is less than 17.

If the dealer busts, then the player wins $10, and is asked to play again.If neither dealer nor player busts, then a tie will push.If the player has the highest hand, then the player wins $10, and is asked to play again.If the dealer has the highest hand, then the player loses $10, and is asked to play again.

Once the hand is over, both players return their cards, and those cards are put-back onto the top of the chute. The chute is shuffled once 52 cards have been dealt.

Page 69: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Packages

Page 70: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Packages

• Packages help organize your code• Packages disambiguate• Packages avoid naming conflicts• Using the fully qualified name of an object,

you need not import it (though it's best to import).

Page 71: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• Package: a collection of classes with a related purpose

• Import library classes by specifying the package and class name:

import java.awt.Rectangle;

• You don’t need to import classes in the java.lang package such as String and System

Packages

Page 72: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

Syntax 2.4 Importing a Class from a Package

Page 73: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

Package Purpose Sample Class

java.lang Language support Math

java.util Utilities Random

java.io Input and output PrintStream

java.awt Abstract Windowing Toolkit Color

java.applet Applets Applet

java.net Networking Socket

java.sql Database Access ResultSet

javax.swing Swing user interface JButton

omg.w3c.dom Document Object Model for XML documents Document

Packages

• Package: Set of related classes

• Important packages in the Java library:

Page 74: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• To put classes in a package, you must place a line

package packageName;

as the first instruction in the source file containing the classes

• Package name consists of one or more identifiers separated by periods

Organizing Related Classes into Packages

Page 75: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• For example, to put the Financial class introduced into a package named com.horstmann.bigjava, the Financial.java file must start as follows:

package com.horstmann.bigjava;

public class Financial { ... }

• Default package has no name, no package statement

Organizing Related Classes into Packages

Page 76: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• Can always use class without importing:

java.util.Scanner in = new java.util.Scanner(System.in);

• Tedious to use fully qualified name

• Import lets you use shorter class name:

import java.util.Scanner; ... Scanner in = new Scanner(System.in)

• Can import all classes in a package:

import java.util.*;

• Never need to import java.lang

• You don’t need to import other classes in the same package

Importing Packages

Page 77: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• Use packages to avoid name clashes

java.util.Timer

vs.

javax.swing.Timer

• Package names should be unambiguous

• Recommendation: start with reversed domain name:

com.horstmann.bigjava

• edu.sjsu.cs.walters: for Britney Walters’ classes ([email protected])

• Path name should match package name:

com/horstmann/bigjava/Financial.java

Package Names

Page 78: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Big Java by Cay HorstmannCopyright © 2009 by John Wiley &

Sons. All rights reserved.

• Base directory: holds your program's Files

• Path name, relative to base directory, must match package name:

com/horstmann/bigjava/Financial.java

Package and Source Files

Page 79: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Which of the following are packages?

a. java

b. java.lang

c. java.util

d. java.lang.Math

Answer:

a.No

b.Yes

c.Yes

d.No

Self Check 8.18

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 80: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Java Doc

• Generate default JavaDocs.• Using decorations/tags.• Project || Generate JavaDoc.

– In Eclipse; navigate to JDK\bin\javadoc.exe to configure.

• Scope; public to private methods• Use F1 to pull up your javadocs.

Page 81: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Is a Java program without import statements limited to using the default and java.lang packages?

Answer: No — you simply use fully qualified names for all other classes, such as java.util.Random and java.awt.Rectangle.

Self Check 8.19

Big Java by Cay HorstmannCopyright © 2009 by John Wiley & Sons. All rights reserved.

Page 82: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Gregorian Calendar Example

Page 83: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Asciify Example (if we have time)

Page 84: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Adding examples code to javadocs/** * * @param perSoldiers ArrayList<String> * @return Person object * * <pre> * Example: * perSenior = getMostSenior(perVets); //will return a reference to Person * </pre> */

Use the <pre> code here </pre> tages in javadocs before the methods Good idea!

Page 85: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Object Composition

• Objects are composed of instance fields• Instance fields can be primitives or other objects• //fields of this class• private String strFirstName;• private String strLastName;• private byte yAge; //-128 to 127• private boolean bVeteran;• private String strSocialSecurityNum;• private ArrayList<Person> perDependents;

Page 86: Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.

Imports and the Java API

• Determine the version of Java you’re using. From the cmd line> java –version

• http://download.oracle.com/javase/6/docs/api/• java.lang.* is automatically imported. This default

behavior is know as ‘convention over configuration’. So• Eclipse is very good about importing packages and

catching compile-time errors. • To use the javadoc for the core Java API; F1

– JDK\src.zip• To see source code; F3