Think Java: Java Programming Language Part 1 - PowerPoint PPT Presentation

Loading...

PPT – Think Java: Java Programming Language Part 1 PowerPoint presentation | free to download - id: 6e70c2-MDlmN



Loading


The Adobe Flash plugin is needed to view this content

Get the plugin now

View by Category
About This Presentation
Title:

Think Java: Java Programming Language Part 1

Description:

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 – PowerPoint PPT presentation

Number of Views:19
Avg rating:3.0/5.0
Date added: 11 October 2019
Slides: 239
Provided by: Chia160
Category:

less

Write a Comment
User Comments (0)
Transcript and Presenter's Notes

Title: Think Java: Java Programming Language Part 1


1
Think Java Java Programming Language Part 1
  • Chia James Chang
  • cjameschang_at_yahoo.com
  • Materials are based on Professor Allen B.
    Downeys Think Java How to Think Like a
    Computer Scientist
  • (10/16/2012 11/20/2012)
  • (Update 10/21/2012)

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.

3
Freely received, freely give
  • Freely you have received freely give.
  • Matthew 108 (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.

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. Its a free book!
  • This book about a way of thinking like a computer
    scientist.

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 Downeys 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, its all my fault for not being able to
    teach.

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

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)

8
References
  • Think Java How to Think Like a Computer
    Scientist by Allen B. Downey
  • http//greenteapress.com/thinkapjava/index.html
  • Think Java Class _at_ TSG of River of Life
    Foundation website
  • http//www.techsamaritan.org/courses/jameschang/ja
    va/java-1.html
  • GridWorld Case Study (College Board AP Computer
    Science Curriculum)
  • http//www.collegeboard.com/student/testing/ap/com
    psci_a/case.html
  • Java SE 7 JDK (Windows, Unix/Linux, and Mac)
  • http//www.oracle.com/technetwork/java/javase/down
    loads/index.html
  • The Java Tutorials
  • http//docs.oracle.com/javase/tutorial/index.html
  • Eclipse IDE for Java EE Developers
  • http//www.eclipse.org/downloads/

9
Chapter 1 The way of the program
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.

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.

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.

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

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

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 Doyles The Sign of Four).

16
Java! Java! Java!
17
Java
  • Java The World's Most Popular Programming
    Language
  • The TIOBE Programming Community Index
  • 3 Billion Devices Run Java
  • Oracle

18
Java Buzzwords

General-purpose High-level
Simple Architecture neutral
Object oriented Portable
Strong typed High performance
Multithreaded Robust
Dynamic Secure
The Java Language Environment , a white paper written by James Gosling and Henry McGilton (http//java.sun.com/docs/white/langenv/) The Java Language Environment , a white paper written by James Gosling and Henry McGilton (http//java.sun.com/docs/white/langenv/)
19
The first program
  • Hello, World. in Java
  • class HelloWorld
  • public static void main(String args)
  • System.out.println(Hello World!)
  • Java programs are made of class definitions
  • class CLASSNAME
  • public static void main(String args)
  • STATEMENTS

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!
21
Java Platform
  • Java Virtual Machine (JVM)
  • Java Application Programming Interface (API)

HelloWorld.java HelloWorld.java
API Java Platform
Java Virtual Machine Java Virtual Machine Java Platform
Hardware-Based Platform Hardware-Based Platform
22
Create and run Java program - 1
  • Create a source file
  • vi HelloWorld.java
  • Compile the source file into .class file
  • javac HelloWorld.java
  • Output file HelloWorld.class
  • Run the program
  • java classpath . HelloWorld
  • Output message Hello World!

23
Create and run Java program - 2
  • Use different Java IDEs or editors
  • In this class, Ill use Eclipse to create and run
    Java programs.
  • Demo

24
Summary Exercises
25
Chapter 2 Variables and types
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.

27
The first program
  • Hello, World. in Java
  • class HelloWorld
  • public static void main(String args)
  • System.out.println(Hello World!)

28
More printing
  • Hello, World. in Java
  • class Hello1
  • // Generates some simple output.
  • public static void main(String args)
  • System.out.println(Hello, world.) //
    print one line
  • System.out.println(How are your?) //
    print another
  • To display the output on one line, use print
  • class Hello2
  • // Generates some simple output.
  • public static void main(String args)
  • System.out.print(Goodbye, )
  • System.out.println(cruel world!)
  • // output Goodbye, cruel world!.

29
Variables
  • A variable is a named location that stores a
    value.
  • To declare or to create a variable
  • String bob
  • String firstName
  • String lastName
  • To declare multiple variables
  • int hour, minute

30
Primitive Data Types
data type size default
byte 8-bit signed 0
short 16-bit signed 0
int 32-bit signed 0
long 64-bit signed 0L
float 32-bit signed (single-precision) 0.0f
double 64-bit IEEE 754 (double-precision) 0.0d
boolean true and false false
char 16-bit Unicode char \u0000
31
Assignment
  • To store a variable with an assignment statement
  • bob Hello.
  • hour 11
  • minute 59
  • bob 123 // legal
  • bob 123 // not legal
  • When you declare a variable, you create a named
    storage location.
  • When you make an assignment to a variable, you
    give it a value.

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 1159.

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/nu
    tsandbolts/_keywords.html , provided by Oracle.

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

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.

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.

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 23-1 yields 5.
  • If the operators have the same precedence they
    are evaluated from left to right. So 59100/60
    yields 98.
  • Any time you want to override the rules of
    precedence you can use parentheses. So 2(3-1)
    yields 4.

38
Operators
Operators Precedence
Postfix expr expr--
Unary expr expr expr expr !
Multiplicative /
Additive -
Shift ltlt gtgt gtgtgt
Relational lt gt lt gt instanceof
Equality !
Bitwise AND
Bitwise exclusive OR
Bitwise inclusive OR
39
Operators
Operators Precedence
Logical AND
Logical OR
Tenary ?
Assignment - / ltlt gtgt gtgtgt
40
Operators for Strings
  • In general you cannot perform mathematical
    operations on Strings, even if the strings look
    like numbers. the following are illegal
  • bob 1 Hello/123 bob Hello
  • For Strings, the operator represents
    concatenation, which means joining up the two
    operands. So Hello, world. yields Hello,
    world.

41
Arithmetic operators
  • Addition (also used for String concatenation)
  • x 1 1
  • String helloWorld hello world!
  • - Subtraction
  • x 3 - 1
  • Multiplication
  • x 2 1
  • / Division
  • x 4 / 2
  • Remainder (Mode)
  • x 5 3

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

43
Equality operator
  • Equal to
  • if (x y)
  • System.out.println(x y)
  • ! Not equal to
  • if (x ! y)
  • System.out.println(x ! y)

44
Relational Operator
  • gt Greater than
  • if (x gt y) System.out.println(x gt y)
  • gt Greater than or equal to
  • if (x gt y) System.out.println(x gt y)
  • lt Less than
  • if (x lt y) System.out.println(x lt y)
  • lt Less than or equal to
  • if (x lt y) System.out.println(x lt y)

45
Conditional operator
  • Conditional-AND
  • if ((x 1) (y 1)
  • System.out.println(x is 1 AND y is 1)
  • Conditional-OR
  • if ((x 1) (y 1)
  • System.out.println(x is 1 OR y is 1)
  • ? Tenary (shorthand for an if-then-else)
  • int result (x gt y) ? x y
  • Short-circuiting behavior means that the second
    operand is evaluated only if needed.

46
Bitwise Operator
  • Unary bitwise complement
  • 00000000 ? 11111111
  • ltlt gtgt Signed left or right shift
  • x ltlt 2
  • y gtgt 2
  • gtgtgt Unsigned right shift (shifts a zero into the
    leftmost position)
  • Bitwise AND
  • Bitwise exclusive OR
  • Bitwise inclusive OR

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

48
Summary Exercises
49
Chapter 3 Void methods
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
    assignment
  • double pi 3.14159
  • Java distinguishes the integer value 1 from the
    floating-point value 1.0.
  • int x 1.1 // illegal
  • double y 1 // legal, Java automatically
    converts
  • double z 1 / 3 //whats the answer? 0.333333
    or 0?

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 doesnt 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

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

53
Adding new methods
  • Create your own method
  • public static void NAME(LIST OF PARAMETERS)
  • STATEMENTS
  • public static void newLine()
  • System.out.println()
  • public static void main(String args)
  • newLine()
  • newLine()
  • By convention, Java methods start with a lower
    case letter and use camel caps, jamming
    wordsTogetherLikeThis.

54
Parameters and arguments
  • Arguments values that you provide when you
    invoke the method
  • Parameters variables that store arguments
  • public static void printTwice(String s) //
    parameter
  • System.out.println(s)
  • System.out.println(s)
  • printTwice(Dont make me say this twice!.) //
    argument
  • String argument Never say never.
  • printTwice(argument) // correct
  • prinntTwice(17) // error

55
Methods with multiple parameters
  • Have to declare the type of every parameter
  • public static void printTime(int hour, int
    minute)
  • System.out.print(hour)
  • System.out.print()
  • System.out.println(minute)
  • Dont declare the types of arguments
  • int hour 11
  • int minute 59
  • printTime(int hour, int minute) // WRONG!
  • printTime(hour, minute) // correct

56
Methods that return values
  • Some methods, like Math methods, return values
  • Other methods, like println and newLine, dont
    return values
  • What happens if you invoke a method and you dont
    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)

57
Summary Exercises
58
Debugging with Eclipse
  • Review Chapter 3 Exercise ZoopExercise
  • Debugging with Eclipse
  • Demo

59
Chapter 15 Object-oriented programming
60
Object-oriented Concept
  • Encapsulation
  • Information hiding, the internal representation
    of an object is generally hidden from view
    outside of the objects 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/O
    bject-oriented_programming )

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/O
    bject-oriented_programming )

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.

63
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.

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.

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 objects 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_at_80cc807

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.Moun
    tainBike_at_6bbc4459
  • public String toString()
  • return ("height " height " ")
  • System.out.println(mtnBike) // height 10

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.

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

69
Naming Conventions http//en.wikipedia.org/wiki/Na
ming_convention_(programming)Java
70
Naming Conventions - Classes
  • Class names should be nouns in Upper CamelCase,
    with the first letter of every word capitalized.
  • Use whole words avoid acronyms and
    abbreviations (unless the abbreviation is much
    more widely used than the long form, such as URL
    or HTML).
  • class Bicycle

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

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

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

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

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

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

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

78
Access Level
Modifier 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
79
Choosing an Access Level
  • Use the most restrictive access level that makes
    sense for a particular member.
  • Use private unless you have a good reason not to.
  • Avoid public fields except for constants.
  • Public fields tend to link you to a particular
    implementation and limit your flexibility in
    changing your code.

80
Inheritance
  • Inheritance is the ability to define a new class
    that is a modified version of an existing class.
  • The existing class is called the parent class and
    the new class is called the child.
  • Advantage you can add methods and instance
    variables without modifying the parent.

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

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.

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, its
    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.

84
Object methods and class methods
  • printCard as a class method
  • public static void printCard(Card c)
  • System.out.println(This card is c.type)
  • print as an object method
  • public void print()
  • System.out.println(This card is type)

85
Bicycle in action
  • Bicycle
  • MountainBike

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

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

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

89
Implements Interface
  • public interface Bicycle
  • void changeGear(int newValue)
  • class MountainBike implements Bicycle
  • void changeGear(int newValue)
  • gear newValue

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

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

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

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

94
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.

95
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.

96
What do you mean by static in Java? (continued)
  • The static keyword can be used in
  • static variables
  • static methods
  • Constants
  • static blocks of code

97
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
    doesnt need any object
  • ClassName.variableName
  • Bicycle.numberOfBicycles

98
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
    doesnt need any object.
  • Can not refer to this or super keywords in
    anyway.
  • ClassName.methodName(args)
  • Bicycle.getNumberOfBicycles()

99
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 directlythey must use an object
    reference.
  • Class methods cannot use the this keyword as
    there is no instance for this to refer to.

100
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

101
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

102
HelloWorld in C
  • Java
  • public class HelloWorld
  • public static void main(String args)
  • System.out.println(Hello World!)
  • C
  • using System
  • namespace HelloWorld
  • public class HelloWorld
  • public static void Main(string args)
  • Console.WriteLine(Hello, world!)

103
Summary Exercises
104
Chapter 4 Conditionals and recursion
105
The modulus operator
  • The modulus operator works on integers (and
    integer expression) and yields the remainder when
    the first operand is divided by the second.
  • In Java, the modulus operator is a percent sign,
    .
  • int quotient 7 / 3 // 2
  • int remainder 7 3 // 1
  • The modulus operator turns out to be surprisingly
    useful. For example
  • check whether one number is divisible by another,
    e.g., if x y is zero, then x is divisible by y.
  • extract the rightmost digit or digits from a
    number, e.g., x 10 yields the rightmost digit
    of x.

106
Conditional execution
  • Conditional statements check conditions and
    change the behavior of the program accordingly.
  • if (x gt 0)
  • System.out.println(x is positive)
  • Relational (comparison) operators ( ! gt lt
    gt lt)
  • x y
  • is the assignment operator and is a
    comparison operator.

107
Alternative execution
  • Alternative execution there are two
    possibilities, and the condition determines which
    one gets executed.
  • if-else
  • public static void printParity(int x)
  • if (x2 0)
  • System.out.println(x is even)
  • else
  • System.out.println(x is odd)

108
Chained conditions
  • Chaining check a number of related conditions
    and choose one
  • if (x gt 0)
  • System.out.println(x is positive)
  • else if (x lt 0)
  • System.out.println(x is negative)
  • else
  • System.out.println(x is zero)

109
Nested conditions
  • Nest one conditional within another
  • if (x 0)
  • System.out.println(x is zero)
  • else
  • if (x gt 0)
  • System.out.println(x is positive)
  • else
  • System.out.println(x is negative)

110
The return statement
  • To terminate the execution of method before you
    reach the end.
  • public static void printLogarithm(double x)
  • if (x lt 0.0)
  • System.out.println(Positive numbers
    only, please)
  • return
  • double result Math.log(x)
  • System.out.println(The log of x is
    result)

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.

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)

113
Summary Exercises
114
Chapter 5 GridWorld Part 1
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/com
    psci_a/case.html
  • Unpack the code
  • GridWorldCode folder
  • projects/firstProject/BugRunner.java
  • Instructions http//www.collegeboard.com/prod_dow
    nloads/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_ap
    pends_v3.pdf.

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 (variable or field) 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.

117
Chapter 6 Value methods
118
Return values
  • Methods return results, e.g., Math functions
  • double sqrt Math.sqrt(16.0)
  • Methods return no value, void.
  • countdown(3)
  • Value methods methods return values
  • public static double area(double radius)
  • double area Math.PI radius radius
  • return area
  • //
  • area(10.0)

119
Overloading
  • Overloading having more than one method with the
    same name but different parameters.
  • calculate a circle area with radius
  • public static double area(double radius)
  • double area Math.PI radius radius
  • return area
  • calculate a circle area with two points
  • public static double area(double x1, double y1,
    double x2, double y2)
  • return area(distance(x1, y1, x2, y2))

120
Boolean expressions
  • Boolean true and false
  • boolean flag
  • flag true
  • boolean testResult false
  • The result of a conditional operator is a boolean
  • boolean evenFlag (n2 0)
  • boolean positiveFlag (x gt 0)

121
Logical operators
  • AND (), OR (), and NOT (!)
  • x gt 0 x lt 10
  • evenFlag n3 0
  • !evenFlag
  • Logical operators can simplify nested conditional
    statements.
  • if (x gt 0)
  • if (x lt 10)
  • System.out.println(x is a positive single
    digits.)
  • if (x gt 0 x lt 10)
  • System.out.println(x is a positive single
    digits.)

122
Boolean methods
  • Methods return boolean values
  • public static boolean isSingleDigit(int x)
  • if (x gt 0 x lt 10)
  • return true
  • else
  • return false
  • public static boolean isSingleDigit(int x)
  • return (x gt 0 x lt 10)
  • boolean bigFlag !isSingleDigit(17)

123
More recursion
  • factorial function
  • 0! 1
  • n! n . (n 1)! // 3! 321
  • public static int factorial(int n)
  • if (n 0)
  • return 1
  • else
  • int recurse factorial(n-1)
  • int result n recurse
  • return result

124
Summary Exercises
125
Chapter 7 Iteration and loops
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 gt 90)
  • grade A
  • else if (testScore gt 80)
  • grade B
  • else
  • grade C

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

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 gt 0)
  • System.out.println(n)
  • n n-1
  • System.out.println(Blastoff!)

129
do-while statement
  • 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 gt 0)
  • System.out.println(Blastoff!)

130
for statement
  • Iterate through all of the elements of an array
  • for (int i 0 i lt array.length i)
  • // within the loop,
  • // i is the index of the current member
  • // arrayi is the current element

131
for statement (continued)
  • Iterate through a range of values.
  • for (int i 0 i lt 10 i)
  • count i
  • Iterate through Collections and arrays.
  • int numbers 0,1,2,3
  • for (int item numbers)
  • count item
  • for (Object obj collection)
  • obj.method()

132
break statement
  • The break statement has two forms labeled and
    unlabeled.
  • loop for ()
  • ...
  • if (...)
  • break loop
  • ...

133
continue statement
  • The continue statement has two forms labeled and
    unlabeled.
  • loop for ()
  • ...
  • if (...)
  • continue loop
  • ...

134
return statement
  • The return statement has two forms one that
    returns a value, and one that doesnt.
  • return expression
  • or
  • return

135
Summary Exercises
136
Chapter 8 Strings and things
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.c
    om/javase/7/docs/api/java/lang/String.html

138
charAt
  • charAt extracts letters from a String
  • String fruit banana
  • char letter fruit.charAt(1)
  • System.out.println(letter)
  • zero-based
  • char letter fruit.charAt(0)

139
Length
  • Length returns the number of characters in the
    string.
  • String fruit banana
  • int strLength fruit.length()
  • To find the last letter of a string
  • int strLength fruit.length()
  • char lastChar fruit.charAt(strLength 1)

140
Traversal
  • Traversal start at the beginning, do some thing
    with it, and continue until the end.
  • int index 0
  • while (index lt fruit.length())
  • char letter fruit.charAt(index)
  • System.out.println(letter)
  • index index 1

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.StringIndexOu
    tOfBoundsException
  • String index out of range 6

142
The indexOf method
  • indexOf is the inverse of charAt
  • charAx takes an index and returns the character
    at the index
  • String fruit banana
  • char letter fruit.charAt(1)
  • indexOf takes a character and finds the index
    where that character appears
  • String fruit banana
  • int index fruit.indexOf(a)

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 lt length)
  • if (fruit.charAt(index) 'a')
  • count count 1
  • index index 1
  • System.out.println(count)

144
Increment and decrement operators
  • operator adds one to the current value and --
    operator subtracts one.
  • System.out.println(i)
  • System.out.println(j--)
  • Rewrite the previous letter-counter
  • while (index lt length)
  • if (fruit.charAt(index) 'a')
  • count count 1
  • index index 1

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

146
Strings are incomparable
  • Cant use and gt or lt 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)

147
Summary Exercises
148
Chapter 9 Mutable objects
149
Mutable objects
  • Strings are objects
  • They are immutable.
  • They have no attributes.
  • You dont have to use new to create one.
  • Two objects from Java libraries, Point and
    Rectangle.

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

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-gt

152
Instance variables
  • The pieces of data that make up an object are
    called instance variables.
  • boolean flag
  • flag true
  • boolean testResult false
  • The result of a conditional operator is a boolean
  • boolean evenFlag (n2 0)
  • boolean positiveFlag (x gt 0)

153
Objects as parameters
  • Pass objects as parameters in the usual way
  • public static void printPoint(Point p)
  • System.out.println(( p.x , p.y
    ))
  • public static double distance(Point p1, Point p2)
  • double dx (double)(p2.x p1.x)
  • double dy (double)(p2.y p2.y)
  • return Math.sqrt(dxdx dydy)

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)

155
Objects as return types
  • Methods can return objects
  • public static Point findCenter(Rectangle box)
About PowerShow.com