Top Banner
Think Java: Java Programming Language Part 1 Chia James Chang [email protected] 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/2012 Think Java (TSG@ROLF) 1
238

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

Dec 14, 2015

Download

Documents

Welcome message from author
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
Page 1: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 1

Think Java:Java Programming Language Part 1

Chia James [email protected]

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/2012

Page 2: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 3: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 4: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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– http://greenteapress.com/thinkapjava/index.html

• 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/2012

Page 5: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 6: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 7: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 8: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 8

References• Think Java: How to Think Like a Computer Scientist” by Allen B. Downey

– http://greenteapress.com/thinkapjava/index.html • Think Java Class @ TSG of River of Life Foundation website

– http://www.techsamaritan.org/courses/jameschang/java-1.html • GridWorld Case Study (College Board AP Computer Science Curriculum)

– http://www.collegeboard.com/student/testing/ap/compsci_a/case.html• Java SE 7 JDK (Windows, Unix/Linux, and Mac)

– http://www.oracle.com/technetwork/java/javase/downloads/index.html • The Java Tutorials

– http://docs.oracle.com/javase/tutorial/index.html • Eclipse IDE for Java EE Developers

– http://www.eclipse.org/downloads/

10/17/2012

Page 9: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 9

Chapter 1: The way of the program

10/17/2012

Page 10: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 11: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 12: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 13: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 14: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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 result10/17/2012

Page 15: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 16: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 16

Java! Java! Java!

10/17/2012

Page 17: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 17

Java

• “Java: The World's Most Popular Programming Language”– The TIOBE Programming Community Index

• “3 Billion Devices Run Java”– Oracle

10/17/2012

Page 18: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 18

Java Buzzwords

General-purpose High-level

Simple Architecture neutral

Object oriented Portable

Strong typed High performance

Multithreaded Robust

Dynamic SecureThe Java Language Environment , a white paper written by James Gosling and Henry

McGilton (http://java.sun.com/docs/white/langenv/)

10/17/2012

Page 19: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 19

The first program

• “Hello, World.” in Javaclass HelloWorld { public static void main(String[] args) { System.out.println(“Hello World!”); }}

• Java programs are made of class definitionsclass CLASSNAME { public static void main(String[] args) { STATEMENTS; }}

10/17/2012

Page 20: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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 Java VM Java VM Java VM

“Hello World!”

10/17/2012

Page 21: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 21

Java Platform

• Java Virtual Machine (JVM)• Java Application Programming Interface (API)

HelloWorld.java

APIJava

PlatformJava Virtual Machine

Hardware-Based Platform

10/17/2012

Page 22: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 23: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 24: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 24

Summary & Exercises

10/17/2012

Page 25: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 25

Chapter 2: Variables and types

10/17/2012

Page 26: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 27: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 27

The first program

• “Hello, World.” in Javaclass HelloWorld { public static void main(String[] args) { System.out.println(“Hello World!”); }}

10/17/2012

Page 28: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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 printclass 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/2012

Page 29: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 29

Variables

• A variable is a named location that stores a value.

• To declare or to create a variableString bob;String firstName;String lastName;

• To declare multiple variablesint hour, minute;

10/17/2012

Page 30: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Primitive Data Typesdata type size default

byte 8-bit signed 0short 16-bit signed 0int 32-bit signed 0long 64-bit signed 0Lfloat 32-bit signed (single-precision) 0.0f

double 64-bit IEEE 754 (double-precision) 0.0d

boolean true and false falsechar 16-bit Unicode char ‘\u0000’

Page 31: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 31

Assignment

• To store a variable with an assignment statement

bob = “Hello.”;hour = 11;minute = 59;bob = “123”; // legalbob = 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/2012

Page 32: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 33: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 33

Keywords

• There are certain words that are reserved in Java. These words are called keywords.

• The complete list is available at http://download.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html , provided by Oracle.

10/17/2012

Page 34: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 34

Java Reserved Wordsabstract assertboolean break bytecase catch char class const continuedefault do doubleelse enum extendsfalse final finally float forgotoif implements import in instanceof int interfacelongnative new nullpackage private protected publicreturnshort static strictfp super switch synchronizedthis throw throws transient try truevoid volatilewhile

10/17/2012

Page 35: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 36: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 36

Operators

• What is the result?minute = 59;System.out.println(minute/60); // 0.98333?

• 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/2012

Page 37: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 38: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

OperatorsOperators Precedence

Postfix expr++ expr--

Unary ++expr –expr +expr –expr ~ !

Multiplicative * / %

Additive + -

Shift << >> >>>

Relational < > <= >= instanceof

Equality == !=

Bitwise AND &

Bitwise exclusive OR ^

Bitwise inclusive OR |

Page 39: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

OperatorsOperators Precedence

Logical AND &&

Logical OR ||

Tenary ? :

Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Page 40: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 40

Operators for Strings

• In general you cannot perform mathematical operations on Strings, even if the strings look like numbers. the following are illegalbob – 1 “Hello”/123 bob * “Hello”

• For Strings, the + operator represents concatenation, which means joining up the two operands. So “Hello, “ + “world.” yields “Hello, world.”

10/17/2012

Page 41: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Arithmetic operators

+ Addition (also used for String concatenation)x = 1 + 1;String helloWorld = “hello” + “world!”;

- Subtractionx = 3 - 1;

* Multiplicationx = 2 * 1;

/ Divisionx = 4 / 2;

% Remainder (Mode)x = 5 % 3;

Page 42: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Unary operator

+ Unary plusx = +1; // x = x + 1;

- Unary minusx = -1; // x = x – 1;

++ Increment (prefix or postfix)System.out.println(++x); // prefixSystem.out.println(x++); // postfix

-- Decrement (prefix or postfix)System.out.println(--x); // prefixSystem.out.println(x--); // postfix

! Logical Complementboolean success = true;!success;

Page 43: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Equality operator

== Equal toif (x == y) System.out.println(“x == y”);

!= Not equal toif (x != y) System.out.println(“x != y”);

Page 44: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Relational Operator

> Greater thanif (x > y) System.out.println(“x > y”);

>= Greater than or equal toif (x >= y) System.out.println(“x >= y”);

< Less thanif (x < y) System.out.println(“x < y”);

<= Less than or equal toif (x <= y) System.out.println(“x <= y”);

Page 45: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Conditional operator

&& Conditional-ANDif ((x == 1) && (y == 1) System.out.println(“x is 1 AND y is 1”);

|| Conditional-ORif ((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.

Page 46: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Bitwise Operator

~ Unary bitwise complement“00000000” “11111111”

<< >> Signed left or right shiftx << 2;y >> 2;

>>> Unsigned right shift (shifts a zero into the leftmost position)& Bitwise AND^ Bitwise exclusive OR| Bitwise inclusive OR

Page 47: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 48: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 48

Summary & Exercises

10/17/2012

Page 49: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 49

Chapter 3: Void methods

10/17/2012

Page 50: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 50

Floating-point

• in Java, the floating-point type is called double, which is short for “double-precision.”

double pi;pi = 3.14159;

• Initialization: a combined declaration and assignmentdouble pi = 3.14159;

• Java distinguishes the integer value 1 from the floating-point value 1.0.int x = 1.1; // illegaldouble y = 1; // legal, Java automatically convertsdouble z = 1 / 3; //what’s the answer? 0.333333 or 0?

10/17/2012

Page 51: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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 = 3.14159;int x = (int)pi;

10/17/2012

Page 52: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 53: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 53

Adding new methods

• Create your own methodpublic static void NAME(LIST OF PARAMETERS) { STATEMENTS}public static void newLine() { System.out.println(“”);}public static void main(String[] args) { newLine(); newLine();}

• By convention, Java methods start with a lower case letter and use “camel caps”, jamming wordsTogetherLikeThis.

10/17/2012

Page 54: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 54

Parameters and arguments

• Arguments: values that you provide when you invoke the method

• Parameters: variables that store argumentspublic static void printTwice(String s) { // parameter System.out.println(s); System.out.println(s);}

printTwice(“Don’t make me say this twice!.”); // argumentString argument = “Never say never.”;printTwice(argument); // correctprinntTwice(17); // error

10/17/2012

Page 55: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 55

Methods with multiple parameters

• Have to declare the type of every parameterpublic static void printTime(int hour, int minute) { System.out.print(hour); System.out.print(“:”); System.out.println(minute);}

• Don’t declare the types of argumentsint hour = 11;int minute = 59;printTime(int hour, int minute); // WRONG!printTime(hour, minute); // correct

10/17/2012

Page 56: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 57: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 57

Summary & Exercises

10/17/2012

Page 58: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 58

Debugging with Eclipse

• Review Chapter 3 Exercise: ZoopExercise

• Debugging with Eclipse

• Demo

10/17/2012

Page 59: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 59

Chapter 15: Object-oriented programming

10/17/2012

Page 60: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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 )

10/17/2012

Page 61: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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 )

10/17/2012

Page 62: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 63: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 63

Object

Actor Grid

Bug

BugGox

Critter

CrabCritter

Flower Rock

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/2012

Page 64: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 65: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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, 3.14159);System.out.println(t2); //Time@80cc807

10/17/2012

Page 66: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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);// org.techsamaritan.java.thinkjava.Chapter15.MountainBike@6bbc4459

public String toString() {return ("height = " + height + "; ");

}System.out.println(mtnBike); // height = 10;

10/17/2012

Page 67: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 68: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

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?

Page 69: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Naming Conventionshttp://en.wikipedia.org/wiki/Naming_convention_(programming

)#Java

Page 70: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

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 {}

Page 71: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

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

Page 72: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

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;

Page 73: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

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;

Page 74: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

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;

Page 75: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Parent, super, or base classpackage org.techsamaritan.java.thinkjava

public class Bicycle {

// fields

int cadence;

...

// constructor

public Bicycle(...) {...}

// method declarations

public void setCadence(int cadence) {

this.cadence = cadence;

}

}

Page 76: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Child class, subclass, or base classpackage 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(...);

Page 77: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

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

Page 78: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Access LevelModifier Class Package Subclass World

public Y Y Y Y

protected Y Y Y N

No modifier Y Y N N

private Y N N N

Page 79: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

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.

Page 80: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 81: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 82: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 83: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 84: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 84

Object methods and class methods

• printCard as a class methodpublic static void printCard(Card c) { System.out.println(“This card is “ + c.type);}

• print as an object methodpublic void print() { System.out.println(“This card is “ + type);}

10/17/2012

Page 85: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Bicycle in action

• Bicycle• MountainBike

Page 86: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

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.

Page 87: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

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.

Page 88: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Define Interfacepublic 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);

}

Page 89: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Implements Interfacepublic interface Bicycle {

void changeGear(int newValue);

}

class MountainBike implements Bicycle {

void changeGear(int newValue)

gear = newValue;

}

} Bicycle

Mountain Bike

Road Bike Tandem Bike

Page 90: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Rewriting Interfaces

• Developed An InterfacePublic interface DoIt {

void doSomething(int i);

}

• Want to Add A MethodPublic interface DoIt {

void doSomething(int i);

int doSomethingElse(String s);

}

• Add A MethodPublic interface DoItPlus extends DoIt {

boolean doSomethingElse(String s);

}

Page 91: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

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.

Page 92: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Multiple Interfacepublic interface GroupedInterface extends Interface1, Interface2, Interface3 {

// constant declarations

// base of natural logarithms

double E = 2.718282;

// method signatures

void doSomething (int i, double x);

int doSomethingElse(String s);

}

Page 93: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

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

Page 94: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 94

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

10/17/2012

Page 95: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 96: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 97: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 98: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 99: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 100: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 101: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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 = 3. 141592653589793;

10/17/2012

Page 102: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 103: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 103

Summary & Exercises

10/17/2012

Page 104: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 104

Chapter 4 Conditionals and recursion

10/17/2012

Page 105: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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; // 2int 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/2012

Page 106: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 107: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 107

Alternative execution

• Alternative execution: there are two possibilities, and the condition determines which one gets executed.

• if-elsepublic static void printParity(int x) { if (x%2 == 0) { System.out.println(“x is even”); } else { System.out.println(“x is odd”); }}

10/17/2012

Page 108: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 109: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 110: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 111: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 112: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 113: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 113

Summary & Exercises

10/17/2012

Page 114: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 114

Chapter 5: GridWorld: Part 1

10/17/2012

Page 115: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 115

GridWorld: Part 1• AP Computer Science Case Study which is a grogram called

GridWorld.– GridWorld Case Study

• http://www.collegeboard.com/student/testing/ap/compsci_a/case.html

• Unpack the code– GridWorldCode folder– projects/firstProject/BugRunner.java– Instructions: http://

www.collegeboard.com/prod_downloads/student/testing/ap/compsci_a/ap07_gridworld_installation_guide.pdf

• GridWorld Student Manual– http://

www.collegeboard.com/prod_downloads/student/testing/ap/compsci_a/ap07_gridworld_studmanual_appends_v3.pdf.

10/17/2012

Page 116: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 117: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 117

Chapter 6: Value methods

10/17/2012

Page 118: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 118

Return values

• Methods return results, e.g., Math functionsdouble sqrt = Math.sqrt(16.0);

• Methods return no value, void.countdown(3);

• Value methods: methods return valuespublic static double area(double radius) { double area = Math.PI * radius * radius; return area;}//area(10.0);

10/17/2012

Page 119: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 119

Overloading

• Overloading: having more than one method with the same name but different parameters.

• calculate a circle area with radiuspublic static double area(double radius) { double area = Math.PI * radius * radius; return area;}

• calculate a circle area with two pointspublic static double area(double x1, double y1, double x2, double y2) { return area(distance(x1, y1, x2, y2));}

10/17/2012

Page 120: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 120

Boolean expressions

• Boolean: true and falseboolean flag;flag = true;boolean testResult = false;

• The result of a conditional operator is a booleanboolean evenFlag = (n%2 == 0);boolean positiveFlag = (x > 0);

10/17/2012

Page 121: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 121

Logical operators

• AND (&&), OR (||), and NOT (!)x > 0 && x < 10evenFlag || 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/2012

Page 122: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 122

Boolean methods

• Methods return boolean valuespublic 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/2012

Page 123: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 124: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 124

Summary & Exercises

10/17/2012

Page 125: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 125

Chapter 7: Iteration and loops

10/17/2012

Page 126: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 127: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 128: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 129: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 130: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 131: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 132: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 132

Break statement

• The break statement has two forms: labeled and unlabeled.

loop: for (;;) {...

if (...) {break loop;

}...

}

10/17/2012

Page 133: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 133

Continue statement

• The continue statement has two forms: labeled and unlabeled.

loop: for (;;) {...

if (...) {continue loop;

}...

}

10/17/2012

Page 134: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 134

Return statement

• The return statement has two forms: one that returns a value, and one that doesn’t.

return expression;

orreturn;

10/17/2012

Page 135: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 135

Summary & Exercises

10/17/2012

Page 136: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 136

Chapter 8: Strings and things

10/17/2012

Page 137: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

10/17/2012

Page 138: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 138

charAt

• charAt extracts letters from a StringString fruit = “banana”;char letter = fruit.charAt(1);System.out.println(letter);

• zero-basedchar letter = fruit.charAt(0);

10/17/2012

Page 139: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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 stringint strLength = fruit.length();char lastChar = fruit.charAt(strLength – 1);

10/17/2012

Page 140: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 141: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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: 6at 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/2012

Page 142: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 142

The indexOf method

• indexOf is the inverse of charAt– charAx takes an index and returns the character at

the indexString 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/2012

Page 143: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 144: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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-counterwhile (index < length) { if (fruit.charAt(index) == 'a') { count = count + 1; } index = index + 1;}

10/17/2012

Page 145: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 146: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 147: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 147

Summary & Exercises

10/17/2012

Page 148: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 148

Chapter 9: Mutable objects

10/17/2012

Page 149: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 150: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 151: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 152: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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 booleanboolean evenFlag = (n%2 == 0);boolean positiveFlag = (x > 0);

10/17/2012

Page 153: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 153

Objects as parameters

• Pass objects as parameters in the usual waypublic 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/2012

Page 154: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 155: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 155

Objects as return types

• Methods can return objectspublic 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/2012

Page 156: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 157: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 158: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 159: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 160: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 161: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 161

Summary & Exercises

10/17/2012

Page 162: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 162

Chapter 10: GridWorld: Part 2

10/17/2012

Page 163: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 163

GridWorld: Part 2

• Part 2 of the GridWorld case study.• You can find the documentation for the

GridWorld classes at http://www.greenteapress.com/thinkapjava/javadoc/gridworld/

10/17/2012

Page 164: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 164

Chapter 11: Create your own objects

10/17/2012

Page 165: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 166: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 167: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 168: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 169: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 170: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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 booleanboolean evenFlag = (n%2 == 0);boolean positiveFlag = (x > 0);

10/17/2012

Page 171: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 171

Initialize Time objectclass 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/2012

Page 172: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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 = 3.14159; System.out.println(t1); // another way to do the same thing Time t2 = new Time(11, 8, 3.14159); System.out.println(t2); }}

10/17/2012

Page 173: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 173

Operations on objects

• Three kinds of methods that operate on objects– pure function– modifier– fill-in method

10/17/2012

Page 174: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 175: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 176: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 177: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 177

Summary & Exercises

10/17/2012

Page 178: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 178

Chapter 12: Arrays

10/17/2012

Page 179: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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[] countdouble[] values;

• To create the array itself, use new.count = new int[4];values = new double[size];

10/17/2012

Page 180: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 181: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 182: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 183: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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 toINITIALIZER;while (CONDITION) { BODY INCREMENTOR}

10/17/2012

Page 184: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 185: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 185

Summary & Exercises

10/17/2012

Page 186: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 186

Chapter 13: Arrays of Objects

10/17/2012

Page 187: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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: http://en.wikipedia.org/wiki/Playing_card.

10/17/2012

Page 188: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 189: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 190: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 191: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 192: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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 DiamondCard card2 = card1;if (card1 == card2) { System.out.println(“card1 and card2 are identical.”);}

10/17/2012

Page 193: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 194: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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 > 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/2012

Page 195: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 196: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 197: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 198: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 199: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 200: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 201: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 202: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 202

Bisection searchpublic 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/2012

Page 203: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 203

Summary & Exercises

10/17/2012

Page 204: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 204

Chapter 14: Objects of Arrays

10/17/2012

Page 205: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 206: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 206

The printDeck method

• printDeck method prints the deckpublic static void printDeck(Deck deck) { for (int i = 0; i < deck.cards.length; i++) { Card.printCard(deck.cards[i]); }}

10/17/2012

Page 207: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 208: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 209: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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<sub.cards.length; i++) { sub.cards[i] = deck.cards[low+i]; } return sub;}

10/17/2012

Page 210: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 211: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 212: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 213: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 213

Merge sort

• The pseudocode of mergepublic 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/2012

Page 214: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 214

mergeSort

• The pseudocode of mergeSortpublic 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/2012

Page 215: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 216: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 216

Class variables

• A version of Card where suits and ranks are class variablesclass 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/2012

Page 217: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 217

Summary & Exercises

10/17/2012

Page 218: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 218

Chapter 16: GridWorld: Part 3

10/17/2012

Page 219: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 219

GridWorld: Part 3

• Part 3 of the GridWorld case study.• You can find the documentation for the

GridWorld classes at http://www.greenteapress.com/thinkapjava/javadoc/gridworld/

10/17/2012

Page 220: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 220

Appendix A: Graphics

10/17/2012

Page 221: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 221

Java Graphics

• See Appendix A. Graphics

10/17/2012

Page 222: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 222

Appendix B: Input and Output in Java

10/17/2012

Page 223: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 224: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 225: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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 word10/17/2012

Page 226: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 227: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 227

Appendix C: Program development

10/17/2012

Page 228: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 229: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 230: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 231: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 232: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 232

Appendix D: Debugging

10/17/2012

Page 233: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 234: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 235: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 236: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 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/2012

Page 237: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 237

Thank You!

10/17/2012

Page 238: Think Java: Java Programming Language Part 1 Chia James Chang cjameschang@yahoo.com Materials are based on: Professor Allen B. Downey’s “Think Java: How.

Think Java (TSG@ROLF) 238

Think Java:Java Programming Language Part 1

Chia James [email protected]

Materials are based on: Professor Allen B. Downey’s “Think Java: How to Think Like a Computer Scientist”

10/17/2012