Presentation is loading. Please wait.

Presentation is loading. Please wait.

Think Java: Java Programming Language Part 1 Chia James Chang Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Similar presentations


Presentation on theme: "Think Java: Java Programming Language Part 1 Chia James Chang Materials are based on: Professor Allen B. Downey’s “Think Java: How."— Presentation transcript:

1 Think Java: Java Programming Language Part 1 Chia James Chang Materials are based on: Professor Allen B. Downey’s “Think Java: How to Think Like a Computer Scientist” (10/16/2012 – 11/20/2012) (Update: 10/21/2012) 10/17/2012Think Java

2 Who Am I? James has worked in the software industry for 20+ years and is currently working at Microsoft. He had worked for Yahoo!, Sun Microsystems, Rolm/IBM, and several startups and has used Java and other languages and technologies to develop various mobile, enterprises, security, and Big Data software. 10/17/2012Think Java

3 Freely received, freely give “Freely you have received; freely give.” – Matthew 10:8 (New International Version) “As we enjoy great Advantages from the Inventions of others, we should be glad of an Opportunity to serve others by any Invention of ours, and this we should do freely and generously.” – Benjamin Franklin, quoted in Benjamin Franklin by Edmund S. Morgan. 10/17/2012Think Java

4 Background In 1999, Professor Allen B. Downey was teaching an introductory computer science class using the Java programming language at Colby College, Maine, and start writing this free book. “Think Java: How to Think Like a Computer Scientist” by Allen B. Downey – Each chapter is about ten pages, not including the exercises. It’s a free book! This book about a way of thinking like a computer scientist. 10/17/2012Think Java

5 Think like a computer scientist Computer scientists have an approach to problem-solving, and a way of crafting solutions, that is unique, versatile and powerful. Hope that Professor Downey’s book and this class will give you a sense of what that approach is, and that at some point you will find yourself thinking like a computer scientist. – If you achieved it, all credits go to Professor Downey. – If not, it’s all my fault for not being able to teach. 10/17/2012Think Java

6 Outline - 1 Chapter 1: The way of the program (programming language, program, debug, first program...) Chapter 2: Variables and types (variables, assignments, operators...) Chapter 3: Void methods (floating-point, classes and methods, parameters...) Chapter 15: Object-oriented programming (object methods and class methods, inheritance...) Chapter 4: Conditionals and recursion (modulus operator, conditions, recursion...) Chapter 6: Value methods (return values, overloading...) Chapter 7: Iteration and loops (multiple assignment, while...) Chapter 8: Strings and things (characters, traversal, String...) 10/17/2012Think Java

7 Outline - 2 Chapter 9: Mutable objects (packages, instance variables, Objects...) Chapter 11: Create your own objects (class, constructors...) Chapter 12: Arrays (accessing elements, arrays and objects...) Chapter 13: Arrays of Objects (Card objects, arrays of cards...) Chapter 14: Objects of Arrays (Deck class, shuffling, sorting...) Chapter 5: GridWorld: Part 1 (College Board AP Computer Science Case Study) Chapter 10: GridWorld: Part 2 (College Board AP Computer Science Case Study) Chapter 16: GridWorld: Part 3 (College Board AP Computer Science Case Study) 10/17/2012Think Java

8 References Think Java: How to Think Like a Computer Scientist” by Allen B. Downey – Think Java TSG of River of Life Foundation website – GridWorld Case Study (College Board AP Computer Science Curriculum) – Java SE 7 JDK (Windows, Unix/Linux, and Mac) – The Java Tutorials – Eclipse IDE for Java EE Developers – 10/17/2012Think Java

9 Chapter 1: The way of the program 10/17/2012Think Java

10 The way of the program Think like a computer scientist who combines some of the best features of. Mathematicians: use formal languages to denote ideas Engineers: design things, assembling components into systems and evaluating tradeoffs among alternatives Scientists: observe the behavior of complex systems, form hypotheses, and test predictions. 10/17/2012Think Java

11 Problem-Solving The single most important skill for a computer scientist is problem-solving. What is problem-solving? – the ability to formulate problems, think creatively about solutions, and express a solution clearly and accurately The process of learning to program is an excellent opportunity to practice problem- solving skills. 10/17/2012Think Java

12 What is a programming language? High-level: Java, Python, C, C++, etc. – easier to program; portable; interpret or compile Low-level: machine or assembly language Java is both compiled and interpreted. 10/17/2012Think Java

13 What is a program? A sequence of instructions that specifies how to perform a computation. Instructions or statements perform: – input: get data – output: output data – math: perform math operations – testing: check for conditions, run statements – repetition: perform actions 10/17/2012Think Java

14 What is debugging? Debugging: tracking down and correcting bugs Three kinds of errors: – syntax errors: Syntax refers to the structure of your program and the rules about that structure. e.g. omitting the semi-colon at the end of a statement – run-time errors: In Java, run-time errors (called exceptions) occur when the interpreter is running the byte code and something goes wrong. e.g. an infinite recursion causes a StackOverflowException – logic errors and semantics: The semantics, or meaning of the program, are wrong. e.g. yielding an unexpected result 10/17/2012Think Java

15 Experimental debugging One of the most important skills you will acquire in this class is debugging. Debugging is one of the most interesting, challenging, and valuable parts of programming. Debugging is like detective work. Debugging is like an experimental science. As Sherlock Holmes pointed out, “When you have eliminated the impossible, whatever remains, however improbable, must be the truth.” (From A. Conan Doyle’s The Sign of Four). 10/17/2012Think Java

16 Java! Java! Java! 10/17/2012Think Java

17 Java “Java: The World's Most Popular Programming Language” – The TIOBE Programming Community Index “3 Billion Devices Run Java” – Oracle 10/17/2012Think Java

18 Java Buzzwords General-purposeHigh-level SimpleArchitecture neutral Object orientedPortable Strong typedHigh performance MultithreadedRobust DynamicSecure The Java Language Environment, a white paper written by James Gosling and Henry McGilton (http://java.sun.com/docs/white/langenv/) 10/17/2012Think Java

19 The first program “Hello, World.” in Java class HelloWorld { public static void main(String[] args) { System.out.println(“Hello World!”); } } Java programs are made of class definitions class CLASSNAME { public static void main(String[] args) { STATEMENTS; } } 10/17/2012Think Java

20 Java on different OS Running on different Operating Systems (OS) via Java VM editor HelloWorld.java javac HelloWorld.java java HelloWorld.class Java VM “Hello World!” 10/17/2012Think Java

21 Java Platform Java Virtual Machine (JVM) Java Application Programming Interface (API) HelloWorld.java API Java Platform Java Virtual Machine Hardware-Based Platform 10/17/2012Think Java

22 Create and run Java program - 1 Create a source file  vi HelloWorld.java Compile the source file into.class file  javac HelloWorld.java o Output file: HelloWorld.class Run the program  java –classpath. HelloWorld  Output message: “Hello World!” 10/17/2012Think Java

23 Create and run Java program - 2 Use different Java IDEs or editors In this class, I’ll use Eclipse to create and run Java programs. Demo 10/17/2012Think Java

24 Summary & Exercises 10/17/2012Think Java

25 Chapter 2: Variables and types 10/17/2012Think Java

26 The way of program Think like a computer scientist who combines some of the best features of. – Mathematicians: use formal languages to denote ideas – Engineers: design things, assembling components into systems and evaluating tradeoffs among alternatives – Scientists: observe the behavior of complex systems, form hypotheses, and test predictions. The single most important skill for a computer scientist is problem-solving. – the ability to formulate problems, think creatively about solutions, and express a solution clearly and accurately The process of learning to program is an excellent opportunity to practice problem-solving skills. 10/17/2012Think Java

27 The first program “Hello, World.” in Java class HelloWorld { public static void main(String[] args) { System.out.println(“Hello World!”); } } 10/17/2012Think Java

28 More printing “Hello, World.” in Java class Hello1 { // Generates some simple output. public static void main(String[] args) { System.out.println(“Hello, world.”); // print one line System.out.println(“How are your?”); // print another } } To display the output on one line, use print class Hello2 { // Generates some simple output. public static void main(String[] args) { System.out.print(“Goodbye, ”); System.out.println(“cruel world!”); } } // output: Goodbye, cruel world!. 10/17/2012Think Java

29 Variables A variable is a named location that stores a value. To declare or to create a variable String bob; String firstName; String lastName; To declare multiple variables int hour, minute; 10/17/2012Think Java

30 Primitive Data Types data typesizedefault byte8-bit signed0 short16-bit signed0 int32-bit signed0 long64-bit signed0L float32-bit signed (single-precision)0.0f double64-bit IEEE 754 (double-precision)0.0d booleantrue and falsefalse char16-bit Unicode char‘\u0000’

31 Assignment To store a variable with an assignment statement bob = “Hello.”; hour = 11; minute = 59; bob = “123”; // legal bob = 123; // not legal When you declare a variable, you create a named storage location. When you make an assignment to a variable, you give it a value. 10/17/2012Think Java

32 Printing variables You can print the value of a variable using println or print: class Hello3 { public static void main(String[] args) { String firstLine; firstLine = “Hello, again!”; System.out.println(firstLine); int hour, minute; hour = 11; minute = 59; System.out.print(“The current time is “); System.out.print(hour); System.out.print(“:”); System.out.print(minute); System.out.println(“.”); // output: The current time is 11:59. } } 10/17/2012Think Java

33 Keywords There are certain words that are reserved in Java. These words are called keywords. The complete list is available at va/nutsandbolts/_keywords.html, provided by Oracle. va/nutsandbolts/_keywords.html 10/17/2012Think Java

34 Java Reserved Words abstract assert boolean break byte case catch char class const continue default do double else enum extends false final finally float for goto if implements import in instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient try true void volatile while 10/17/2012Think Java

35 Operators Operators are symbols used to represent computations like addition. addition is +, subtraction is -, multiplication is *, and division is /. Expressions can contain both variable names and numbers. Variables are replaced with their values before the computation is performed. 10/17/2012Think Java

36 Operators What is the result? minute = 59; System.out.println(minute/60); // ? Integer division – The result is 0 because Java is performing integer division. – When both operands are integers (operands are the things operators operate on), the result is also an integer, and by convention integer division always rounds down. 10/17/2012Think Java

37 Order of operations When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. A complete explanation of precedence can get complicated, but just to get you started: – Multiplication and division happen before addition and subtraction. So 2*3-1 yields 5. – If the operators have the same precedence they are evaluated from left to right. So 59*100/60 yields 98. – Any time you want to override the rules of precedence you can use parentheses. So 2*(3-1) yields 4. 10/17/2012Think Java

38 Operators Precedence Postfixexpr++ expr-- Unary++expr –expr +expr –expr ~ ! Multiplicative* / % Additive+ - Shift > >>> Relational = instanceof Equality== != Bitwise AND& Bitwise exclusive OR^ Bitwise inclusive OR|

39 Operators Precedence Logical AND&& Logical OR|| Tenary? : Assignment= += -= *= /= %= &= ^= |= >= >>>=

40 Operators for Strings In general you cannot perform mathematical operations on Strings, even if the strings look like numbers. the following are illegal bob – 1“Hello”/123bob * “Hello” For Strings, the + operator represents concatenation, which means joining up the two operands. So “Hello, “ + “world.” yields “Hello, world.” 10/17/2012Think Java

41 Arithmetic operators +Addition (also used for String concatenation) x = 1 + 1; String helloWorld = “hello” + “world!”; -Subtraction x = 3 - 1; * Multiplication x = 2 * 1; /Division x = 4 / 2; %Remainder (Mode) x = 5 % 3;

42 Unary operator +Unary plus x = +1; // x = x + 1; -Unary minus x = -1; // x = x – 1; ++ Increment (prefix or postfix) System.out.println(++x); // prefix System.out.println(x++); // postfix --Decrement (prefix or postfix) System.out.println(--x); // prefix System.out.println(x--); // postfix !Logical Complement boolean success = true; !success;

43 Equality operator ==Equal to if (x == y) System.out.println(“x == y”); !=Not equal to if (x != y) System.out.println(“x != y”);

44 Relational Operator > Greater than if (x > y) System.out.println(“x > y”); >=Greater than or equal to if (x >= y) System.out.println(“x >= y”);

45 Conditional operator && Conditional-AND if ((x == 1) && (y == 1) System.out.println(“x is 1 AND y is 1”); ||Conditional-OR if ((x == 1) || (y == 1) System.out.println(“x is 1 OR y is 1”); ?:Tenary (shorthand for an if-then-else) int result = (x > y) ? x : y; “Short-circuiting” behavior means that the second operand is evaluated only if needed.

46 Bitwise Operator ~Unary bitwise complement “ ”  “ ” >Signed left or right shift x << 2; y >> 2; >>>Unsigned right shift (shifts a zero into the leftmost position) &Bitwise AND ^Bitwise exclusive OR |Bitwise inclusive OR

47 Composition One of the most useful features of programming languages is their ability to take small building blocks and compose them. int percentage; percentage = (minute * 100) / 60; System.out.println(hour * 60 + minute); WARNING: The left side of an assignment has to be a variable name, not an expression. 10/17/2012Think Java

48 Summary & Exercises 10/17/2012Think Java

49 Chapter 3: Void methods 10/17/2012Think Java

50 Floating-point in Java, the floating-point type is called double, which is short for “double-precision.” double pi; pi = ; Initialization: a combined declaration and assignment double pi = ; Java distinguishes the integer value 1 from the floating-point value 1.0. int x = 1.1; // illegal double y = 1; // legal, Java automatically converts double z = 1 / 3; //what’s the answer? or 0? 10/17/2012Think Java

51 Converting from double to int Java converts int to double automatically without losing information. Going from a double to an int requires rounding off and rounding down. Java doesn’t coverts double to int automatically. The simplest way to convert a floating-point value to an integer is to use a typecast. double pi = ; int x = (int)pi; 10/17/2012Think Java

52 Math methods Java provides functions (methods) that perform the most common math operations. double root = Math.sqrt(16.0); Java methods can be composed, meaning that you use one expression as part of another. double x= Math.exp(Math.log(10.0)); // log base e 10/17/2012Think Java

53 Adding new methods Create your own method public static void NAME(LIST OF PARAMETERS) { STATEMENTS } public static void newLine() { System.out.println(“”); } public static void main(String[] args) { newLine(); } By convention, Java methods start with a lower case letter and use “camel caps”, jamming wordsTogetherLikeThis. 10/17/2012Think Java

54 Parameters and arguments Arguments: values that you provide when you invoke the method Parameters: variables that store arguments public static void printTwice(String s) { // parameter System.out.println(s); } printTwice(“Don’t make me say this twice!.”); // argument String argument = “Never say never.”; printTwice(argument); // correct prinntTwice(17); // error 10/17/2012Think Java

55 Methods with multiple parameters Have to declare the type of every parameter public static void printTime(int hour, int minute) { System.out.print(hour); System.out.print(“:”); System.out.println(minute); } Don’t declare the types of arguments int hour = 11; int minute = 59; printTime(int hour, int minute); // WRONG! printTime(hour, minute); // correct 10/17/2012Think Java

56 Methods that return values Some methods, like Math methods, return values Other methods, like println and newLine, don’t return values What happens if you invoke a method and you don’t do anything with the results? Math.sqrt(16.0); What happens if you use a print method as part of any expression System.out.println(“boo!”) + 7? Can we write methods that return values, or are we stuck with things like newLine and printTwice? int value = myMethod(1, 2); 10/17/2012Think Java

57 Summary & Exercises 10/17/2012Think Java

58 Debugging with Eclipse Review Chapter 3 Exercise: ZoopExercise Debugging with Eclipse Demo 10/17/2012Think Java

59 Chapter 15: Object-oriented programming 10/17/2012Think Java

60 Object-oriented Concept Encapsulation – Information hiding, the internal representation of an object is generally hidden from view outside of the object’s definition. Inheritance – A way to reuse code of existing objects or to establish a subtype from an existing object. Polymorphism – (in Greek means many forms) the ability to create a variable, a function, or an object that has more than one form. (Source: Wikipedia (http://en.wikipedia.org/wiki/Object- oriented_programming )http://en.wikipedia.org/wiki/Object- oriented_programming 10/17/2012Think Java

61 Object-oriented programming What is Object-oriented programming? – Object-oriented programming (OOP) is a programming paradigm using "objects" – usually instances of a class – consisting of data fields and methods together with their interactions – to design applications and computer programs. (Source: Wikipedia (http://en.wikipedia.org/wiki/Object- oriented_programming )http://en.wikipedia.org/wiki/Object- oriented_programming 10/17/2012Think Java

62 Java programs Java programs are object-oriented, which means that the focus is on objects and their interactions. – Objects often represent entities in the real world, e.g., Bicycle class – The majority of methods are object methods (like the methods you invoke on Strings) rather than class methods (like the Math methods). – Objects are isolated from each other by limiting the ways they interact, especially by preventing them from accessing instance variables without invoking methods. – Classes are organized in family trees where new classes extend existing classes, adding new methods and replacing others. 10/17/2012Think Java

63 Object Actor Grid Bug BugGox Critter CrabCritter FlowerRock ChameleonCritter The class hierarchy The “family tree” of classes is called the class hierarchy. Object usually appears at the top, with all the “child” classes below. 10/17/2012Think Java

64 The class hierarchy In Java, all classes extend some other class. The most basic class is called Object. – Contains no instance variables. – Provides the methods equals and toString, among others. Any class that does not explicitly name a parent inherits from Object by default. 10/17/2012Think Java

65 The toString method Every object type has a method called toString that returns a string representation of the object. When you print an object using print or println, Java invokes the object’s toString method. The default version of toString returns a string that contains the type of the object and a unique identifier. Time t2 = new Time(11, 8, ); System.out.println(t2); // 10/17/2012Think Java

66 The toString method When you define a new object type, you can override the default behavior by providing a new method with the behavior you want. MountainBike mtnBike = new MountainBike(10, 12, 10, 1); System.out.println(mtnBike); // public String toString() { return ("height = " + height + "; "); } System.out.println(mtnBike); // height = 10; 10/17/2012Think Java

67 The equals method Review two notions of equality – identity: two variables refer to the same object The == operator tests identity. – equivalence: they have the same value no operator tests equivalence because what “equivalence” means depends on the type of the objects. Java classes provide equals methods that defines equivalence. 10/17/2012Think Java

68 Classes and objects A class is a blueprint or prototype from which objects are created.  Class header  Class body An object is an instance of a class. An object is a software bundle of related behavior (methods) and state (fields). Ask yourself two questions: – What possible states (fields) can this object be in? – What possible behavior (methods) can this object perform?

69 Naming Conventions

70 Naming Conventions - Classes Class names should be nouns in Upper CamelCase, with the first letter of every word capitalized. Use whole words — avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML). class Bicycle { }

71 Naming Conventions - Methods Methods should be verbs in lower CamelCase; that is, with the first letter lowercase and the first letters of subsequent words in uppercase. public int getGear() { }

72 Naming Conventions - Variables Local variables, instance variables, and class variables are also written in lower CamelCase. Variable names should not start with underscore (_) or dollar sign ($) characters, even though both are allowed. Certain coding conventions state that underscores should be used to prefix all instance variables, for improved reading and program understanding. public int gear;

73 Naming Conventions - Variables Variable names should be short yet meaningful. The choice of a variable name should be mnemonic — that is, designed to indicate to the casual observer the intent of its use. The convention is to always begin the variable names with a letter, not "$" or "_“. Subsequent characters may be letters, digits, dollar signs, or underscore characters. The name must not be a keyword or reserved word. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters. public int speed;

74 Naming Conventions - Constants Constants should be written in uppercase characters separated by underscores. Constant names may also contain digits if appropriate, but not as the first character. public final static int MAXIMUM_NUM_OF_SPEEDS = 10;

75 Parent, super, or base class package org.techsamaritan.java.thinkjava public class Bicycle { // fields int cadence;... // constructor public Bicycle(...) {...} // method declarations public void setCadence(int cadence) { this.cadence = cadence; } }

76 Child class, subclass, or base class package org.techsamaritan.java.thinkjava public class MountainBike extends Bicycle implements YourInterface { // fields int seatHeight; // constructor public MountainBike(...) {...} // method declarations public void setHeight(int seatHeight) { this.seatHeight = seatHeight; } } // MountainBike mb = new MountainBike(...);

77 Access Modifiers Two levels of access control:  At the top level: public, or package-private(no explicit modifier).  At the member level: public, private, protected, or package-private(no explicit modifier). public: accessible from all classes private: accessible only within its own class protected: accessible from within its own package and by a subclass of its class in another package

78 Access Level ModifierClassPackageSubclassWorld publicYYYY protectedYYYN No modifierYYNN privateYNNN

79 Choosing an Access Level Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to. Avoid public fields except for constants. Public fields tend to link you to a particular implementation and limit your flexibility in changing your code.

80 Inheritance Inheritance is the ability to define a new class that is a modified version of an existing class. The existing class is called the parent class and the new class is called the child. Advantage: you can add methods and instance variables without modifying the parent. 10/17/2012Think Java

81 Inheritance An example of inheritance: public class MountainBike extends Bicycle implements YourInterface { // fields int seatHeight; // constructor public MountainBike(...) {...} // method declarations public void setHeight(int seatHeight) { this.seatHeight = seatHeight; } } 10/17/2012Think Java

82 Inheritance Inheritance is a powerful feature. Some programs that would be complicated without it can be written concisely and simple with it. Inheritance can facilitate code reuse, since you can customize the behavior of existing classes without having to modify them. 10/17/2012Think Java

83 Object methods and class methods Class methods are identified by the keyword static in the first line. Any method that does not have the keyword static is an object method. Whenever you invoke a method “on” an object, it’s an object method, String.charAt. Anything that can be written as a class method can also be written as an object method, and vice versa. 10/17/2012Think Java

84 Object methods and class methods printCard as a class method public static void printCard(Card c) { System.out.println(“This card is “ + c.type); } print as an object method public void print() { System.out.println(“This card is “ + type); } 10/17/2012Think Java

85 Bicycle in action Bicycle MountainBike

86 Interfaces An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface. An interface declaration consists of modifiers, the keyword interface, the interface name, a comma- separated list of parent interfaces (if any), and the interface body.

87 Interfaces Interface can contain only constants, method signatures, and nested types. There are no method bodies. All methods declared in an interface are implicitly public. All constants defined in an interface are implicitly public, static, and final. Interface cannot be instantiated—they can only be implemented by classes or extended by other interfaces.

88 Define Interface public interface Bicycle { // constant int MAX_GEARS = 20; // wheel revolutions per minute void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); void changeCadence(int newValue); }

89 Implements Interface public interface Bicycle { void changeGear(int newValue); } class MountainBike implements Bicycle { void changeGear(int newValue) gear = newValue; } } Bicycle Mountain Bike Road BikeTandem Bike

90 Rewriting Interfaces Developed An Interface Public interface DoIt { void doSomething(int i); } Want to Add A Method Public interface DoIt { void doSomething(int i); int doSomethingElse(String s); } Add A Method Public interface DoItPlus extends DoIt { boolean doSomethingElse(String s); }

91 Interfaces & Multiple Inheritance The Java programming language does not permit multiple inheritance, but interfaces provide an alternative. In Java, a class can inherit from only one class but it can implement more than one interface. Therefore, objects can have multiple types: the type of their own class and the types of all the interfaces that they implement. This means that if a variable is declared to be the type of an interface, its value can reference any object that is instantiated from any class that implements the interface.

92 Multiple Interface public interface GroupedInterface extends Interface1, Interface2, Interface3 { // constant declarations // base of natural logarithms double E = ; // method signatures void doSomething (int i, double x); int doSomethingElse(String s); }

93 Summary of Interfaces A protocol of communication between two objects Contains signatures and constant but not method implementation A class implements an interface must implement all methods An interface name can be used anywhere a type can be used

94 HelloWorld in C# // C# using System; namespace HelloWorld { public class HelloWorld { public static void Main(string[] args) { Console.WriteLine(“Hello, world!”); } } } // Java public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello World!”); } } 10/17/2012Think Java

95 What do you mean by static in Java? When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance (object) variables and instance (object) methods. 10/17/2012Think Java

96 What do you mean by static in Java? (continued) Sometimes, you want to have variables and methods that are common to all objects. This is accomplished with the static modifier. static fields or class variables static methods or class methods They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable. 10/17/2012Think Java

97 What do you mean by static in Java? (continued) The static keyword can be used: static variables static methods Constants static blocks of code 10/17/2012Think Java

98 static variable Belongs to the class and not to object (instance) Is initialized only once, at the start of the execution. A single copy is shared by all instances of the class. Is accessed directly by the class name and doesn’t need any object ClassName.variableName Bicycle.numberOfBicycles 10/17/2012Think Java

99 static method Belongs to the class and not to the object (instance) Can access only static data. It can not access non-static data (instance variables) Can call only other static methods and can not call a non- static method from it. Can be accessed directly by the class name and doesn’t need any object. Can not refer to “this” or “super” keywords in anyway. ClassName.methodName(args) Bicycle.getNumberOfBicycles() 10/17/2012Think Java

100 Instance and class variables and methods Instance methods can access instance variables and instance methods directly. Instance methods can access class variables and class methods directly. Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly—they must use an object reference. Class methods cannot use the this keyword as there is no instance for this to refer to. 10/17/2012Think Java

101 Constants The static modifier, in combination with the final modifier, is used to define constants. The final modifier indicates that the value of this field cannot change. static final double PI = ; 10/17/2012Think Java

102 static blocks of code The static initialization block is a normal block of code enclosed in braces, {}, and preceded by the static keyword that will be executed when a class is first loaded into the JVM. static { // whatever code is needed for initialization goes here } 10/17/2012Think Java

103 Summary & Exercises 10/17/2012Think Java

104 Chapter 4 Conditionals and recursion 10/17/2012Think Java

105 The modulus operator The modulus operator works on integers (and integer expression) and yields the remainder when the first operand is divided by the second. In Java, the modulus operator is a percent sign, %. int quotient = 7 / 3; // 2 int remainder = 7 % 3; // 1 The modulus operator turns out to be surprisingly useful. For example: – check whether one number is divisible by another, e.g., if x % y is zero, then x is divisible by y. – extract the rightmost digit or digits from a number, e.g., x % 10 yields the rightmost digit of x. 10/17/2012Think Java

106 Conditional execution Conditional statements: check conditions and change the behavior of the program accordingly. if (x > 0) { System.out.println(“x is positive”); } Relational (comparison) operators: (== != > = <=) x == y; = is the assignment operator and == is a comparison operator. 10/17/2012Think Java

107 Alternative execution Alternative execution: there are two possibilities, and the condition determines which one gets executed. if-else public static void printParity(int x) { if (x%2 == 0) { System.out.println(“x is even”); } else { System.out.println(“x is odd”); } } 10/17/2012Think Java

108 Chained conditions Chaining: check a number of related conditions and choose one: if (x > 0) { System.out.println(“x is positive”); } else if (x < 0) { System.out.println(“x is negative”); } else { System.out.println(“x is zero”); } 10/17/2012Think Java

109 Nested conditions Nest one conditional within another: if (x == 0) { System.out.println(“x is zero”); } else { if (x > 0) { System.out.println(“x is positive”); } else { System.out.println(“x is negative”); } } 10/17/2012Think Java

110 The return statement To terminate the execution of method before you reach the end. public static void printLogarithm(double x) { if (x <= 0.0) { System.out.println(“Positive numbers only, please”); return; } double result = Math.log(x); System.out.println(“The log of x is ” + result); } 10/17/2012Think Java

111 Type conversion Whenever you try to “add” two expressions, – “The log of x is “ + result if one of them is a String, Java converts the other to a String and then perform string concatenation. – 5 + pi if one of them is floating-point, Java converts the other to a double and then perform addition. 10/17/2012Think Java

112 Recursion one method to invoke another one method to invoke itself – recursion public static void countdown(int n) { if (n == 0) { System.out.println(“Blastoff!”); } else { System.out.println(n); countdown(n – 1); } } // countdown(3); 10/17/2012Think Java

113 Summary & Exercises 10/17/2012Think Java

114 Chapter 5: GridWorld: Part 1 10/17/2012Think Java

115 GridWorld: Part 1 AP Computer Science Case Study which is a grogram called GridWorld. – GridWorld Case Study ml ml Unpack the code – GridWorldCode folder – projects/firstProject/BugRunner.java – Instructions: g/ap/compsci_a/ap07_gridworld_installation_guide.pdf g/ap/compsci_a/ap07_gridworld_installation_guide.pdf GridWorld Student Manual – g/ap/compsci_a/ap07_gridworld_studmanual_appends_v3.pdf. g/ap/compsci_a/ap07_gridworld_studmanual_appends_v3.pdf 10/17/2012Think Java

116 Vocabularies The components of GridWorld, including Bugs, Rocks and the Grid itself, are objects. A constructor is a special method that creates new objects. A class is a set of object; every object belongs to a class. An object is also called an instance because it is a member, or instance, of a class. An attribute is a piece of information about an object, like its color or location. An accessor method is a method that returns an attribute of an object. A modifier method changes an attribute of an object. 10/17/2012Think Java

117 Chapter 6: Value methods 10/17/2012Think Java

118 Return values Methods return results, e.g., Math functions double sqrt = Math.sqrt(16.0); Methods return no value, void. countdown(3); Value methods: methods return values public static double area(double radius) { double area = Math.PI * radius * radius; return area; } // area(10.0); 10/17/2012Think Java

119 Overloading Overloading: having more than one method with the same name but different parameters. calculate a circle area with radius public static double area(double radius) { double area = Math.PI * radius * radius; return area; } calculate a circle area with two points public static double area(double x1, double y1, double x2, double y2) { return area(distance(x1, y1, x2, y2)); } 10/17/2012Think Java

120 Boolean expressions Boolean: true and false boolean flag; flag = true; boolean testResult = false; The result of a conditional operator is a boolean boolean evenFlag = (n%2 == 0); boolean positiveFlag = (x > 0); 10/17/2012Think Java

121 Logical operators AND (&&), OR (||), and NOT (!) x > 0 && x < 10 evenFlag || n%3 == 0 !evenFlag Logical operators can simplify nested conditional statements. if (x > 0) { if (x < 10) { System.out.println(“x is a positive single digits.”); } } if (x > 0 && x < 10) { System.out.println(“x is a positive single digits.”); } 10/17/2012Think Java

122 Boolean methods Methods return boolean values public static boolean isSingleDigit(int x) { if (x >= 0 && x < 10) { return true; } else { return false; } } public static boolean isSingleDigit(int x) { return (x >= 0 && x < 10); } boolean bigFlag = !isSingleDigit(17); 10/17/2012Think Java

123 More recursion factorial function  0! = 1  n! = n. (n – 1)! public static int factorial(int n) { if (n == 0) { return 1; } else { int recurse = factorial(n-1); int result = n * recurse; return result; } } 10/17/2012Think Java

124 Summary & Exercises 10/17/2012Think Java

125 Chapter 7: Iteration and loops 10/17/2012Think Java

126 If statement The If statement tells your program to execute a certain section of code only if a particular test evaluates to true. if (testScore >= 90) { grade = ‘A’; } else if (testScore >= 80) { grade = ‘B’; } else { grade = ‘C’; } 10/17/2012Think Java

127 Switch statement The switch value can be a byte, short, char, and int primitive data, enumerated, String class or special classes wrapped certain primitive (e.g. Character) switch (expression) { case 1: case 2: month(); break; default: noneOfTheAbove(); break } 10/17/2012Think Java

128 While statement Continually executes a block of statements while a particular condition is true. while (expression) { statement(s); } // public static void countdown(int n) { while (n > 0) { System.out.println(n); n = n-1; } System.out.println(“Blastoff!”); } 10/17/2012Think Java

129 While statement (continued) Continually executes a block of statements while a particular condition is true. do { statement(s); } while (expression); // public static void countdown(int n) { do { System.out.println(n); n = n-1; } while (n > 0) System.out.println(“Blastoff!”); } 10/17/2012Think Java

130 For statement Iterate through all of the elements of an array: for (var i = 0; i < array.length; i += 1) { // within the loop, // i is the index of the current member // array[i] is the current element } 10/17/2012Think Java

131 For statement (continued) Iterate through a range of values. for (int i = 0; i < 10; i++) { count += i; } Iterate through Collections and arrays. int numbers = {0,1,2,3}; for (int item : numbers) { count += item; } for (Objec obj: collection) { obj.method(); } 10/17/2012Think Java

132 Break statement The break statement has two forms: labeled and unlabeled. loop: for (;;) {... if (...) { break loop; }... } 10/17/2012Think Java

133 Continue statement The continue statement has two forms: labeled and unlabeled. loop: for (;;) {... if (...) { continue loop; }... } 10/17/2012Think Java

134 Return statement The return statement has two forms: one that returns a value, and one that doesn’t. return expression; or return; 10/17/2012Think Java

135 Summary & Exercises 10/17/2012Think Java

136 Chapter 8: Strings and things 10/17/2012Think Java

137 Characters Java String is an object. “What is the data contained in a Strings object?” “What are the methods we can invoke on String object?” The components of a String object are letters or characters (characters, numbers, symbols, other things.) Java API document for String: ng/String.html ng/String.html 10/17/2012Think Java

138 charAt charAt extracts letters from a String String fruit = “banana”; char letter = fruit.charAt(1); System.out.println(letter); zero-based char letter = fruit.charAt(0); 10/17/2012Think Java

139 Length Length returns the number of characters in the string. String fruit = “banana”; int strLength = fruit.length(); To find the last letter of a string int strLength = fruit.length(); char lastChar = fruit.charAt(strLength – 1); 10/17/2012Think Java

140 Traversal Traversal: start at the beginning, do some thing with it, and continue until the end. int index = 0; while (index < fruit.length()) { char letter = fruit.charAt(index); System.out.println(letter); index = index + 1; } 10/17/2012Think Java

141 Run-time errors In Java run-time errors are called exceptions. Java prints an error message with the type of exception and a stack trace, which shows the methods that were running when the exception occurred. public class BadString{ public static void main(String[] args) { processWord(“banana”); } public static void processWord(String s) { char c = getLastLetter(s); System.out.println(c); } public static char getLastLetter(String s) { int index = s.length(); char c = s.charAt(index); return c; } } Java prints the stack trace and ends the program: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6 at java.lang.String.charAt(String.java:694) at BadString.getLastLetter(BadString.java:24) at BadString.processWord(BadString.java:18) at BadString.main(BadString.java:14) 10/17/2012Think Java

142 The indexOf method indexOf is the inverse of charAt – charAx takes an index and returns the character at the index String fruit = “banana”; char letter = fruit.charAt(1); – indexOf takes a character and finds the index where that character appears String fruit = “banana”; int index = fruit.indexOf(‘a’); 10/17/2012Think Java

143 Looping and counting Letter-counter: loops and counts the number of times the letter ‘a’ appears in a string. String fruit = "banana"; int length = fruit.length(); int count = 0; int index = 0; while (index < length) { if (fruit.charAt(index) == 'a') { count = count + 1; } index = index + 1; } System.out.println(count); 10/17/2012Think Java

144 Increment and decrement operators ++ operator adds one to the current value and -- operator subtracts one. System.out.println(i++); System.out.println(j--); Rewrite the previous letter-counter while (index < length) { if (fruit.charAt(index) == 'a') { count = count + 1; } index = index + 1; } 10/17/2012Think Java

145 Strings are immutable Invoke toUpperCase or toLowerCase on a String, you get a new String as return value. String name = “Alan Turing”; String upperName = name.toUpperCase(); 10/17/2012Think Java

146 Strings are incomparable Can’t use == and > or < to compare strings To compare Strings, we have to use the equals and compareTo methods. int flag = name1.compareTo(name2); int flag2 = name1.equals(name2); 10/17/2012Think Java

147 Summary & Exercises 10/17/2012Think Java

148 Chapter 9: Mutable objects 10/17/2012Think Java

149 Mutable objects Strings are objects – They are immutable. – They have no attributes. – You don’t have to use new to create one. Two objects from Java libraries, Point and Rectangle. 10/17/2012Think Java

150 Packages Java libraries are divided into packages, e.g., java.lang To use a class defined in another package, you have to import it. import java.awt.Point; import java.awt.Rectangle; All import statements appear at the beginning of the program, outside of the class definition. import java.awt.Point; public class NewClass { … } 10/17/2012Think Java

151 Point objects A point is two numbers (coordinates); in Java, a point is represented by a Point object. Point blank; blank = new Point(3, 4); blank-> 3 4 x y 10/17/2012Think Java

152 Instance variables The pieces of data that make up an object are called instance variables. boolean flag; flag = true; boolean testResult = false; The result of a conditional operator is a boolean boolean evenFlag = (n%2 == 0); boolean positiveFlag = (x > 0); 10/17/2012Think Java

153 Objects as parameters Pass objects as parameters in the usual way public static void printPoint(Point p) { System.out.println(“(“ + p.x + “, “ + p.y + “)”); } public static double distance(Point p1, Point p2) { double dx = (double)(p2.x – p1.x); double dy = (double)(p2.y – p2.y); return Math.sqrt(dx*dx + dy*dy); } 10/17/2012Think Java

154 Rectangles Rectangles are similar to points, except that they have four instance variables: x, y, width, and height. Rectangle box = new Rectangle(0, 0, 100, 200); 10/17/2012Think Java

155 Objects as return types Methods can return objects public static Point findCenter(Rectangle box) { int x = box.x + box.width/2; int y = box.y + box.height/2; return new Point(x, y); } 10/17/2012Think Java

156 Objects are mutable You can change the contents of an object by making an assignment to one of its instance variables. public static void moveRect(Rectangle box, int dx, int dy) { box.x = box.x + dx; box.y = box.y + dy; } // Rectangle box = new Rectangle(0, 0, 100, 200); moveRect(box, 50, 100); 10/17/2012Think Java

157 Aliasing When you assign an object to a variable, you are assigning a reference to an object. It’s possible to have multiple variables that refer to the same object. This is called aliasing. Any changes that affect one variable also affect the other. Rectangle box1 = new Rectangle(0, 0, 100, 200); Rectangle box2 = box1; 10/17/2012Think Java

158 null null is a special value that means “no object.” When you create an object variable, you are creating a reference to an object. Until you make the variable point to an object, the value of the variable is null. If you try to use a null object, either by accessing an instance variable or invoking a method, Java throws a NullPointException. Point blank = null; int x = blank.x; blank.translate(50, 50); 10/17/2012Think Java

159 Garbage collection What happens when no variable refers to an object? Point blank = new Point(3, 4); blank = null; Periodically Java Garbage collector will delete the object and reclaim the resources/memory spaces. This is called garbage collection. 10/17/2012Think Java

160 Objects and primitives Two kinds of types in Java: primitive types and object types. Primitives, like int and boolean begin with lower-case letters. – Declaring a primitive variable, you get storage space. – If you don’t initialize a primitive type, it is given a default value. – Primitive variables are well isolated. – You cannot add new primitives to Java. Object types begin with upper-case letters. – Declaring an object variable, you get a space for a reference to an object. To get space for the object itself, you have to use new. – The default value for object types is null. – Pass a reference to an object as an assignment, the method you invoke might modify the object. – You can create new object types. 10/17/2012Think Java

161 Summary & Exercises 10/17/2012Think Java

162 Chapter 10: GridWorld: Part 2 10/17/2012Think Java

163 GridWorld: Part 2 Part 2 of the GridWorld case study. You can find the documentation for the GridWorld classes at avadoc/gridworld/ avadoc/gridworld/ 10/17/2012Think Java

164 Chapter 11: Create your own objects 10/17/2012Think Java

165 Class definitions and object types Defining a new class also creates a new object type with the same name. A class definition is like a template for objects. Every object belongs to some object type. When you invoke new to create an object, Java invokes a special method called constructor to initialize the instance variables. The methods that operate on a type are defined in the class definition for that type. 10/17/2012Think Java

166 Syntax issues about class definition Class names (and hence object types) should begin with a capital letter, e.g., Time class You usually put one class definition in each file, and the name of the file must be the same as the name of the class, with the suffix.java, e.g., Time class in Time.java In any program, one class is designated as the startup class. The startup class must contain a method named main, which is where the execution of the program begins. 10/17/2012Think Java

167 Time class A common motivation for creating an object type is to encapsulate related data in an object that can be treated as a single unit. For example, Time which represents the time of day, encapsulates the data of an hour, a minute, and second. class Time { int hour, minute; double second; } 10/17/2012Think Java

168 Constructors Constructors initialize instance variables. The syntax for constructors is similar to that of other methods, with three exceptions: – The name of the constructor is the same as the name of the class. – Constructors have no return type and no return value. – The keyword static is omitted. public Time() { this.hour = 0; this.minute = 0; this.second = 0.0; } The name this is a special keyword that refers to the object we are creating. this is created by the system. 10/17/2012Think Java

169 More constructors Constructors can be overloaded: multiple constructors with different parameters. It is common to have one constructor that takes no arguments and one constructor that takes a parameter list identical to the list of instance variables. public Time(int hour, int minute, double second) { this.hour = hour; this.minute = minute; this.second = second; } 10/17/2012Think Java

170 Creating a new object You almost never invoke constructors directly. When you invoke new, the system allocates space for the new object and then invokes your constructor. boolean flag; flag = true; boolean testResult = false; The result of a conditional operator is a boolean boolean evenFlag = (n%2 == 0); boolean positiveFlag = (x > 0); 10/17/2012Think Java

171 Initialize Time object class Time { int hour, minute; double second; public Time() { this.hour = 0; this.minute = 0; this.second = 0.0; } public Time(int hour, int minute, double second) { this.hour = hour; this.minute = minute; this.second = second; } 10/17/2012Think Java

172 Initialize Time object public static void main(String[] args) { // one way to create and initialize a Time object Time t1 = new Time(); t1.hour = 11; t1.minute = 8; t1.second = ; System.out.println(t1); // another way to do the same thing Time t2 = new Time(11, 8, ); System.out.println(t2); } } 10/17/2012Think Java

173 Operations on objects Three kinds of methods that operate on objects – pure function – modifier – fill-in method 10/17/2012Think Java

174 Pure functions A method is considered a pure function if the result depends only on the arguments, and it has no side effects like modifying an argument or printing something. The only result of invoking a pure function is the return value. public static boolean isAfter(Time time1, Time time2) { if (time1.hour > time2.hour) return true; … return false; } 10/17/2012Think Java

175 Modifiers Take objects as arguments and modifies some or all of them. Often returns void. public static void increment(Time time, double secs) { time.second += secs; if (time.second >= 60.0) { time.second -= 60.0; time.minute += 1; } … } 10/17/2012Think Java

176 Fill-in method One of the arguments is an “empty” object that gets filled in by the method. Technically, this is a type of modifier. public static void addTimeFill(Time t1, Time t2, Time sum) { sum.hour = t1.hour + t2.hour; sum.minute = t1.minute + t2.minute; sum.second = t1.second + t2.second; … } 10/17/2012Think Java

177 Summary & Exercises 10/17/2012Think Java

178 Chapter 12: Arrays 10/17/2012Think Java

179 Arrays An array is a set of values where each value is identified by an index. Until you initialize these variables, they are set to null. All the values in an array have to have the same type. int[] count double[] values; To create the array itself, use new. count = new int[4]; values = new double[size]; 10/17/2012Think Java

180 Accessing elements To store values in the array, use the [] operator. count[0] = 7; count[1] = count[0] * 2; count[2]++; You can use any expression as an index, as long as it has type int. int i = 0; while (i < 4) { System.out.println(count[i]); i++; } 10/17/2012Think Java

181 Copying arrays When you copy an array variable, you are copying a reference to the array. Any changes in either array will be reflected in the other. double[] a = new double [3]; double[] b = a; Real copy: allocate a new array and copy double[] b = new double [3]; int i = 0; while (i < 4) { b[i] = a[i]; i++; } 10/17/2012Think Java

182 Arrays and objects In many ways, arrays behave like objects When you declare an array variable, you get a reference to an array. You have to use new to create the array itself. When you pass an array as an argument, you pass a reference, which means that the invoked method can change the contents of the array. The elements of an array are identified by indices, and the elements of an object have names. The elements of an array have to be the same type. Objects can have instance variable with different types. 10/17/2012Think Java

183 for loops for loop general syntax looks like this: for (INITIALIZER; CONDITION; INCREMENTOR) { BODY } for (int i = 0; i < 4; i++) { System.out.println(count[i]); } The for statement is equivalent to INITIALIZER; while (CONDITION) { BODY INCREMENTOR } 10/17/2012Think Java

184 Array length All arrays have one named instance variable: length. Array contains the length of the array (number of elements). for (int i = 0; i < a.length; i++) { b[i] = a[i]; } 10/17/2012Think Java

185 Summary & Exercises 10/17/2012Think Java

186 Chapter 13: Arrays of Objects 10/17/2012Think Java

187 The Road Ahead Outline of the steps to develop programs to work with playing cards In Chapter 13 we’ll define a Card class and write methods that work with Cards and arrays of Cards. In Chapter 14 we’ll create a Deck class and write methods that operate on Decks. In Chapter 15 we’ll transform the Card and Deck classes into the object-oriented programming (OOP). wikipedia.org’s Playing card: 10/17/2012Think Java

188 Playing cards There are 52 cards in a deck; each belongs to one of four suits and one of 13 ranks. The suits are Spades, Hearts, Diamonds and Clubs (in descending order in Bridge). The ranks are Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen and King. We use integers to encode/map the ranks and suits. 10/17/2012Think Java

189 Card objects Mapping (encoding) suits – Spades: 3 – Hearts: 2 – Diamonds: 1 – Clubs: 0 Mapping (encoding) ranks – Each of the numerical ranks maps to the corresponding integer – For face cards: Jack: 11 Queen: 12 King: 13 10/17/2012Think Java

190 Create a new Card class The first step is to declare the instance variables and write constructors. class Card { int suit, rank; public Card() { this.suit = 0; this.rank = 0; } public Card(int suit, int rank) { this.suit = suit; this.rank = rank; } } // Card threeOfClubs = new Card(0, 3); 10/17/2012Think Java

191 The printCard method The second step is to write the standard methods that every object should have such as printCard. public static void printCard(Card c) { String[] suits = {“Clubs”, “Diamonds”, “Hearts”, “Spades”}; String[] ranks = {“narf”, “Ace”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “Jack”, “Queen”, “King”}; System.out.println(ranks[c.rank] + “ of “ + suits[c.suit]); } // Card card = new Card(1, 11); printCard(card); // Jack of Diamonds 10/17/2012Think Java

192 The sameCard method If two Cards are the same, does that mean they contain the same data (rank and suit), or they are actually the same Card object? To see if two references refer to the same object, we use the == operator. Card card1 = new Card(1, 11); // Jack of Diamond Card card2 = card1; if (card1 == card2) { System.out.println(“card1 and card2 are identical.”); } 10/17/2012Think Java

193 The sameCard method References to the same object are identical. References to objects with same data are equivalent. If references are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical. To check equivalent, it is common to write a method with a name like sameCard. public static boolean sameCard(Card c1, Card c2) { return(c1.suit == c2.suit && c1.rank == c2.rank); } 10/17/2012Think Java

194 The compareCard method For primitive types, the conditional operators compare values and determine when one is greater or less than another. These operators ( and the others) don’t work for object types. For Strings Java provides a compareTo method. For Cards we have to write our own, compareCard. The set of playing cards is partially ordered, which means that sometimes we can compare cards and sometimes not. Which is better, the 3 of Clubs or the 2 of Diamonds? 10/17/2012Think Java

195 The compareCard method To make cards comparable, we have to decide which is more important, rank or suit. The choice is arbitrary. public static int compareCard(Card c1, Card c2) { if (c1.suit > c2.suit) return 1; if (c1.suit < c2.suit) return -1; // the suits must be equal if (c1.rank > c2.rank) return 1; if (c1.rank < c2.rank) return -1; return 0; // the ranks must be equal } 10/17/2012Think Java

196 Arrays of cards You can define objects with arrays as instance variables; you can make arrays that contain arrays; you can define objects that contain objects, and so on. Here is an array of 52 cards. The array contains references to objects; it does not contain the Card objects themselves. Card[] cards = new Card[52]; if (cards[0] == null) { System.out.println(“No cards yet!”); } card[0].rank; // NullPointerException 10/17/2012Think Java

197 Populate the Card objects The easiest way to populate the deck with Card objects is to write nested for loops: int index = 0; for (int suit = 0; suit <= 3; suit++) { for (int rank = 1; rank <= 13; rank++) { cards[index] = new Card(suit, rank); index++; } } 10/17/2012Think Java

198 The printDeck method When you work with arrays, it is convenient to have a method that prints the contents. print static void printDeck(Card[] cards) { for (int i = 0; i < cards.length; i++) { printCard(cards[i]); } } 10/17/2012Think Java

199 Searching findSearch searches an array of Cards to see whether it contains a certain card. – This method gives a chance to demonstrate two algorithms: linear search and bisection search. Linear search: traverses the deck and compare each card to the one we are looking for. public static int findCard(Card[] cards, Card card) { for (int i = 0; i < cards.length; i++) { if (sameCard(cards[i], card) { return i; } } return -1; } 10/17/2012Think Java

200 Searching Bisection search: continually cuts the array in half searching only the half in which the card might be found. The algorithm works similar to looking for a word in a dictionary: – The words are in alphabetical order in a dictionary. 1.Start in the middle somewhere. 2.Choose a word on the page and compare it to the word you are looking for. 3.If you find the word you are looking for, stop. 4.If the word you are looking for comes after the word on the page, flip to somewhere later in the dictionary and go to step 2. 5.If the word you are looking for comes before the word on the page, flip to somewhere earlier in the dictionary and go to step 2. 6.If your word comes between two adjacent words on the page, you can conclude that your word is not in the dictionary. 10/17/2012Think Java

201 Bisection search findBisect method implements the bisection search: 1.To search the array, choose an index between low and high (call it mid) and compare it to the card you are looking for. 2.If you found it, stop. 3.If the card at mid is higher than your card, search the rang from low to mid-1. 4.If the card at mid is lower than your card, search the rang from mid-1 to high. In general, bisection search is much faster than a linear search (calling compareCard comparing 6 or 7 times to 52 times). 10/17/2012Think Java

202 Bisection search public static int findBisect(Card[] cards, Card card, int low, int high) { System.out.println(low + “,“ + high); if (high < low) return -1; // base case int mid = (high + low) / 2; int comp = compareCard(cards[mid], card); if (comp == 0) { return mid; } else if (comp > 0) { return findBisect(cards, card, low, mid-1); } else { return findBisect(cards, card, mid+1, high); } } // Card card1 = new Card(1, 11); System.out.println(findBisect(cards, car1, 0, 51)); //card in the deck: 0,51; 0,24; 13,24; 19,24; 22,24; 23 //15 of Diamond: 0,51; 0,24; 13,24; 13,17; 13,14; 13,12; -1 10/17/2012Think Java

203 Summary & Exercises 10/17/2012Think Java

204 Chapter 14: Objects of Arrays 10/17/2012Think Java

205 The Deck class Create a Deck object that contains an array of Cards. class Deck { Card[] cards; public Deck(int n) { this.cards = new Card[n]; } public Deck() { this.cards = new Card[52]; int index = 0; for (int suit = 0; suit <= 3; suit++) { for (int rank = 1; rank <= 13; rank++) { cards[index] = new Card(suit, rank); index++; } } } } 10/17/2012Think Java

206 The printDeck method printDeck method prints the deck public static void printDeck(Deck deck) { for (int i = 0; i < deck.cards.length; i++) { Card.printCard(deck.cards[i]); } } 10/17/2012Think Java

207 Shuffling For most card games you need to be able to shuffle the deck; that is, put the cards in a random order. The better shuffling algorithm is to traverse the deck one card at a time, and at each iteration choose two cards and swap them. Here is pseudocode for shuffling: for (int i = 0; i < deck.cards.length; i++) { // choose a number between i and deck.cards.length-1 // swap the ith card and the randomly-chosen card } 10/17/2012Think Java

208 Sorting Put the deck in order. We’ll use the algorithm called selection sort because it works by traversing the array repeatedly and selecting the lowest remaining card each time. Here is pseudocode for selection sort: for (int i = 0; i < deck.cards.length; i++) { // find the lowest card at or to the right of i // swap the ith card and the lowest card } 10/17/2012Think Java

209 Subdecks How should we represent a hand or some other subset of a full deck? We’ll represent a hand with a Deck object with fewer than 52 cards. public static Deck subdeck(Deck deck, int low, int high) { Deck sub = new Deck(high-low+1); for (int i = 0; i

210 Shuffling and dealing shuffleDeck takes a deck as an argument and shuffles it. Deck deck = new Deck(); shuffleDeck(deck); Deck hand1 = subdeck(deck, 0, 4); Deck hand2 = subdeck(deck, 5, 9); Deck pack = subdeck(deck, 10, 51); How would you deal the cards? 10/17/2012Think Java

211 Dealing cards Should you give one card to each player in the round-robin style that is common in real card games? – The round-robin convention is intended to mitigate imperfect shuffling and make it more difficult for the dealer to cheat. – Neither of these is an issue for a computer. The dangers of engineering metaphors: – Impose restrictions on computers that are unnecessary – Expect capabilities that are lacking 10/17/2012Think Java

212 Mergesort mergesort: if you have two subdecks, each of which has been sorted, it is easy (and fast) to merge them into a single, sorted deck. 1.Form two subdecks with about 10 cards each and sort them so that when they are face up the lowest cards are on top. Place both decks face up in front of you. 2.Compare the top card from each deck and choose the lower one. Flip it over and add it to the merged deck. 3.Repeat step two until one of the decks is empty. Then take the remaining cards and add them to the merged deck. 10/17/2012Think Java

213 Merge sort The pseudocode of merge public static Deck merge(Deck d1, Deck d2) { // create a new deck big enough for all the cards Deck result = new Deck(d1.cards.length + de.cards.length); // use the index i to keep track of where we are in // the first deck, and the index j for the second deck int i = 0; int j = 0; // the index k traverses the result deck for (int k =0; k < result.cards.length; k++) { // if d1 is empty, d2 wins; if d2 is empty, d1 wins; // otherwise, compare the two cards // add the winner to the new deck } return result; } 10/17/2012Think Java

214 mergeSort The pseudocode of mergeSort public static Deck mergeSort(Deck deck) { // if the deck is 0 or 1 cards, return it // find the midpoint of the deck // divide the deck into two subdecks // sort the subdecks using sortDeck // merge the two halves and return the result } 10/17/2012Think Java

215 Class variables Local variables are declared inside a method and they are created when a method is invoked and destroyed when the method ends. Instance variables are declared in a class definition and they are created when you create an object and destroyed when the object is garbage collected. Class variables are declared in a class definition and they are created when the program starts and survive until the program ends. – They are identified by the keyword static. – You can refer to a class variable from anywhere inside the class definition. – Class variables are often used to store constant values that are needed in several places. 10/17/2012Think Java

216 Class variables A version of Card where suits and ranks are class variables class Card { int suit, rank; static String[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" }; static String[] ranks = { "narf", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" }; public static void printCard(Card c) { System.out.println(ranks[c.rank] + " of " + suits[c.suit]); } } 10/17/2012Think Java

217 Summary & Exercises 10/17/2012Think Java

218 Chapter 16: GridWorld: Part 3 10/17/2012Think Java

219 GridWorld: Part 3 Part 3 of the GridWorld case study. You can find the documentation for the GridWorld classes at avadoc/gridworld/ avadoc/gridworld/ 10/17/2012Think Java

220 Appendix A: Graphics 10/17/2012Think Java

221 Java Graphics See Appendix A. Graphics 10/17/2012Think Java

222 Appendix B: Input and Output in Java 10/17/2012Think Java

223 System objects The System class provides methods and objects that get input from the keyboard, print text on the screen, and do file input and output (I/O). System.out is the object that displays on the screen. System.out.println(“Hello, World!”); System.in gets input from the keyboard. 10/17/2012Think Java

224 Keyboard input First, you have to use System.in to create a new InputStreamReader. InputStreamReader in = new InputStreamReader(System.in) ; Then you use in to create new a new BufferedReader. BufferedReader keyboard = new BufferedReader(in) ; Finally you can invoke readLine on keyboard, to take the input from the keyboard and convert it to a String. String input = keyboard.readLine(); A method that throws an exception has to include it in the prototype, like this: public static void main(String[] args) throws IOException { // body of main } 10/17/2012Think Java

225 File input Read lines from a file and prints them import java.io.*; public class Words { public static void main(String[] args) throws FileNotFoundException, IOException { processFile(“words.txt”); } public static void processFile(String filename) throws FileNotFoundException, IOException { FileReader fileReader = new FileReader(filename); BufferedReader in = new BufferedReader(fileReader); while(true) { String s = in.readLine(); if (s == null) break; System.out.println(s); } } } The same program looks like in Python: for word in open(‘words.txt’): print word 10/17/2012Think Java

226 Catching exceptions processFile can throw FileNotFoundException and IOException. Since main calls processFile, it has to declare the same exception. The alternative is to catch the exception with a try statement. public static void main(String[] args) { try { processFile("words.txt"); } catch (Exception ex) { System.out.println("That didn't work. Here's why:"); ex.printStackTrace(); } } 10/17/2012Think Java

227 Appendix C: Program development 10/17/2012Think Java

228 Strategies The foundation of all strategies is incremental development, which goes like this: – Start with a working program that does something visible, like printing something. – Add a small number of lines of code at a time, and test the program after every change. – Repeat until the program does what it is supposed to do. After every change, the program should produce some visible effect that tests the new code. This approach to programming can save a lot of time. The challenge of incremental development is that it is not easy to figure out a path from the starting place to a complete and correct program. There are several strategies to choose from. 10/17/2012Think Java

229 Strategies to choose from Here are several strategies to choose from: Encapsulation and generation: – If you don’t know yet how to divide the computation into methods, start writing code in main, then look for coherent chunks to encapsulate in a method, and generalize them appropriately. Rapid prototyping: – If you know what method to write, but not know to write it, start with a rough draft that handles the simplest case, then test it with other cases, extending and correcting as you go. 10/17/2012Think Java

230 Strategies to choose from (continued) Bottom-up: – Start by writing simple methods, then assemble them into a solution. Top-down: – Use pseudocode to design the structure of the computation and identify the methods you’ll need. – Then write the methods and replace the pseudocode with real code. You might need some scaffolding: – for example, each class should have a toString method that lets you print the state of an object in human- readable form 10/17/2012Think Java

231 Failure modes Non-incremental development – If you write more than a few lines of code without compiling and testing, you are asking for trouble. Attachment to bad code – If you write more than a few lines of code without compiling and testing, you may not be able to debug it. Ever. Random-walk programming – Some students make a change, run the program, get an error, make a change, run the program, etc…. – If you get an error message, take the time to read it. More generally, take time to think. Compiler submission – Error messages are useful, but they are not always right. – e.g. if the message says, “Semi-colon expected on line 13”… 10/17/2012Think Java

232 Appendix D: Debugging 10/17/2012Think Java

233 Debugging strategy The best kind of debugging is the kind you don’t have to do because you avoid making errors in the first place. The best debugging strategy depends on what kind of error you have: Syntax errors are produced by the compiler and indicate that there is something wrong with the syntax of the program. Example: omitting the semi-colon at the end of a statement. Exceptions are produced if something goes wrong while the program is running. Example: an infinite recursion eventually causes a StackOverflowException. Logic errors cause the program to do the wrong thing. Example: an expression may not be evaluated in the order you expect, yielding an unexpected result. 10/17/2012Think Java

234 Syntax errors The compiler is spewing error messages. – Only fix one error at a time, and then recompile the program. I’m getting a weird compiler message and it won’t go away. – Read the error message carefully. – Take a breath and look more broadly at the entire program. More syntax errors… 10/17/2012Think Java

235 Run-time errors My program hangs. – Infinite loop: add a print statement immediately before and after the loop. When I run the program I get an Exception. – Java prints a message that includes the name of the exception, the line of the program where the problem occurred, and a stack trace. – The first step is to examine the place in the program where the error occurred and see if you can figure out what happened. More run-time errors… 10/17/2012Think Java

236 Logic errors Logic errors are hard to find because the compiler and the run-time system provide no information about what is wrong. My program doesn’t work. – The first step is to make a connection between the code and the behavior you get. – You need a hypothesis about what the program is actually doing. Is there something the program was supposed to do, but doesn’t seem to be happening? Is something happening that shouldn’t? I’ve got a big hairy expression and it doesn’t do what I expect. – It is often a good idea to break a complex expression into a series of assignments to temporary variables. More logic errors… 10/17/2012Think Java

237 Thank You! 10/17/2012Think Java

238 Think Java: Java Programming Language Part 1 Chia James Chang Materials are based on: Professor Allen B. Downey’s “Think Java: How to Think Like a Computer Scientist” 10/17/2012Think Java


Download ppt "Think Java: Java Programming Language Part 1 Chia James Chang Materials are based on: Professor Allen B. Downey’s “Think Java: How."

Similar presentations


Ads by Google