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
86
Embed
Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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
Control Structures
See edu.uchicago.cs.java.lec02.control
Shorthand
See blackboard
Arrays & ArrayLists
See edu.uchicago.cs.java.lec02.arrays
Arrays
• arrays of prmitivies• arrays of Objects• multidimentional arrays
• 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:
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)
• Each Wrapper class has some parse functions.• Integer.parseInt(String str);• Double.parseDouble(String str);• Byte.parseByte(String str);• Boolean.parseBoolean(String str);• etc.
The New Keyword
See edu.uchicago.cs.java.lec02.newkeyword
Using the new Keyword
• Unless you use the ‘new’ keyword, nothing has been instantiated and the object does NOT exist in memory.
• public class Geometry{ public static double area(Rectangle rec) { return rec.getWidth() * rec.getHeight(); } // More geometry methods can be added here.}
Static Methods
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
• 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
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.
• 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
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.
• 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
Random
See edu.uchicago.cs.java.lec02.random
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.
Pass by value and reference
See edu.uchicago.cs.java.lec02.passby
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.
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
Objects
See edu.uchicago.cs.java.lec02.console21
Class Object
• A blueprint is to a house as a class is to an object• Class = Blueprint
Class Objects
Class Object
• A blueprint is to a car as a class is to an object• Class = Blueprint
Class Objects
Spot the “class” here
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.
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.
Review of Eclipse
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
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.
Packages
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).
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!
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;
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