Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 03 Agenda > Gamers survey > Take QT Exam

Similar presentations


Presentation on theme: "Lecture 03 Agenda > Gamers survey > Take QT Exam"— Presentation transcript:

1 Lecture 03 Agenda > Gamers survey > Take QT Exam >VarsAndRefs* >ControlStructures > TypeConversion* > MoreNewKeyword > CalendarTest* >simplepoly* >employee* >Asciify >person*

2 >git fetch origin lab03;
>git checkout origin/lab03 -b lab03;

3

4 2 1 4 3 5

5

6 Strings

7 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()

8 // String strAnimal= “Dog”; //these are equivalent
String is Immutable When delcaring String, we can treat them as if they are primitives, but they are objects! // String strAnimal= “Dog”; //these are equivalent // String strAnimal = new String(“Dog”); //these are equivalent 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! Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

9 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. Using .equals() rather than ==. Break to board ; graph String pools. If you didn't completely understand this; don't worry. Just remember that Strings are passed by value; which means that theyr'e copied.

10 A string is a sequence of characters
The String Class 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”); Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

11 Concatenation 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, all the others are converted to a string String strA = "Agent”; int n = 7; char c = 'b' String strBond = strA + n + c; // strBond is "Agent7c" Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

12 Substring starts at the begin-index and ends at end-index – 1.
String str2 = strGreeting.substring(7, 12); // str2 is "World" Substring starts at the begin-index and ends at end-index – 1. This says, start at 6-7 and end at 11-12 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

13 Escape Sequences to include the quotes in a string, use the escape sequences: strOne = "\"Quotation\""; to print \\ StrBackSlashes = "\\\\"; Unicode values cookbook/appendix.html

14 Escape Sequences Escape Sequence Character \n newline \t tab \b
backspace \f form feed \r return \" "   (double quote) \' '    (single quote) \\ \    (back slash) \uDDDD character from the Unicode character set (DDDD is four hex digits) break to code; StringManipulation

15

16 Class Objects

17 Use static appropriately and parsimoniously.
Self Check 8.15 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. Use static appropriately and parsimoniously. Break to Metric and MetricConverter step code of MetricConverter Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

18 Constants

19 Syntax 4.1 Constant Definition
break into Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

20 A final variable is a constant
Constants: final 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; payment = dollars + quarters * QUARTER_VALUE dimes * DIME_VALUE + nickels * NICKEL_VALUE pennies * PENNY_VALUE; Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

21 Packages

22 Modifier | Class | Package | Subclass | World
————————————+———————+—————————+——————————+——————— public | ✔ | ✔ | ✔ | ✔ protected | ✔ | ✔ | ✔ | ✘ no modifier | ✔ | ✔ | ✘ | ✘ private | ✔ | ✘ | ✘ | ✘

23 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).

24 The API Documentation of the Standard Java Library
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

25 Packages import java.awt.Rectangle;
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 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

26 Syntax 2.4 Importing a Class from a Package
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

27 Package: Set of related classes
Important packages in the Java library: 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 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

28 Organizing Related Classes into Packages
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 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

29 Can always use class without importing:
Importing Packages 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 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

30 Use packages to avoid name clashes vs.
Package Names 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 Path name should match package name: com/horstmann/bigjava/Financial.java

31 Package and Source Files
Base directory: holds your program's Files Path name, relative to base directory, must match package name: com/horstmann/bigjava/Financial.java

32 Which of the following are packages? java.lang java.util
Self Check 8.18 Which of the following are packages? java java.lang java.util java.lang.Math Answer: No Yes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

33 Self Check 8.19 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. break to code, create a package poster and put classes into it. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

34 Gregorian Calendar break to code; step through, CalendarTest and blackboard Calendar

35 Asciify Example break to code; step through, Asciify. Also with a main method, step through it. particularly the getAsciiChars example. Notice that it's defined at static.

36 Polymorphism: assingment to references
An object (instantiated in memory) may be assigned to the following reference types: 1/ a reference type of the same type: Double dubVal = new Double(91.5); 2/ any superclass reference, including abstract classes. i.e; any class in the upline of that object’s hierarchy. Number numNum = new Double(9.15); Object objNum = new Double(91.5);

37 Is-a; or to be or not to be.
...that is the question. To check whether an instantiated object may be stored in reference of another type, it must affirmatively answer this question: "Is object a referenceType?"

38 Upcasting/Downcasting
Upcasting is automatic, whereas downcasting is explicit. Do examples SimplePoly and Employee Upcasting is automatic, but downcasting requires an explicit caste. In Java, as you move down the hierachy, the objects get more complex, so downcasting is dangerous. Only downcast when you KNOW the object stored in the reference is of the type you're casting.

39 Polymorphism: assingment to references
3/ Any Interface that the object implements Comparable comNum = new Double(91.5);

40 Interfaces A class implements an interface rather than extends it. Any class that implements the interface must override all the interface methods with it's own methods. Interface names often end with "able" to imply that they add to the capability of the class. An interface is a contract; it defines the methods

41 Inheritence A class that extends a superclass inherets all the fields and methods of its superclass AND those of its entire class hierarchy. A superclass is more generic and contains less data. A subclass is more specific and contains more data. Access to members through get and set. Boxing application

42 SprintRace Example

43 Poster Example

44 Console21

45 One player and one dealer play against one another in a game of 21
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 initial deal If 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.

46 Tetris is a game where the player is confronted with falling shapes called tetriminos. A tetrimino has seven variations; S, L, O, Z, J, I, and T. See for exact configurations. Tetriminos float down from the top of the gaming-environment. The starting column is random, but the tetrimino always starts at top row and floats downward propelled by a gravitational-force that increases with time. Likewise, the points awarded increase as the speed increases. The player can also see which tetrimino is on-deck, allowing him/her to place the current-tetrimino strategically. The player may rotate the tetrimino 90 degrees clock-wise while it is still floating, so long as the rotation does not cause the tetrimino to be out-of-bounds. The player may also laterally-move the tetrimino left or right. And finally, the player may force the tetrimino to free-fall. When the bottom of a tetrimino touches either the bottom of the gaming-environment or the top of the wall made of previously accumulated tetrimino blocks, then its blocks too become immediately integrated into the wall. This integration triggers a series of events which are described below: If the integration results in a wall with complete-rows, then those rows dissappear and the player is awarded points. A high-scoring "tetris" occurs when "I" is integrated vertically into a wall where 4 rows become complete --and then dissappear. Progressively smaller awards are provided for 3, 2, and 1 row completions. Once the integration occurs (and any row completions are finished) the on-deck tetrimino become the current tetrimino and a new tetrimino is randomly generated to be the on-deck one. The now current tetrimino begins its descent, and the cycle continues until the wall reaches 90% of the height of the gaming environment, at which point the game is over.

47 //generate a new on-deck-tetro
//while wall is < 90% of game-environment height //on-deck becomes current and generate a new on-deck tetro //start current-tetro descent at random column //while current-tetro is floating //allow user to control floating tetro //if current-tetrimino touches wall (or bottom) //integrate //check for row completions and make rows dissappear //award any points //break //pull current down with gravity //game over

48 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).

49 Which of the following are packages? java.lang java.util
Self Check 8.18 Which of the following are packages? java java.lang java.util java.lang.Math Answer: No Yes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

50 Self Check 8.19 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. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

51 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;

52 Imports and the Java API
Determine the version of Java you’re using. From the cmd line> java –version 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


Download ppt "Lecture 03 Agenda > Gamers survey > Take QT Exam"

Similar presentations


Ads by Google