Week 1 - PowerPoint PPT Presentation

1 / 90
About This Presentation
Title:

Week 1

Description:

compiler. Java. compiler. Object-Oriented Programming ... Although it makes no difference to the compiler, proper indentation is crucial ' ... – PowerPoint PPT presentation

Number of Views:62
Avg rating:3.0/5.0
Slides: 91
Provided by: Tim8144
Category:

less

Transcript and Presenter's Notes

Title: Week 1


1
Week 1
  • Getting Started

2
Programming
  • We will be focusing more on the planning aspect
    of programming
  • New concepts are introduced, less syntax
  • But this course assumes you may have not had Java
    in Programming I so we will spend time going over
    Java basics as well.

3
The Labs
  • There will NOT be enough time during class lab
    time to complete the labs.
  • Hopefully, you will have worked on the labs so
    that during lab time you will concentrating on
    the sticky stuff.
  • Hopefully the whole pseudo-code structure
    will facilitate that
  • This is where the homework part of the course
    comes in
  • You can work from home
  • You can come in here and use the computers
  • You can work in the Ashland campus computer lab
  • Feel free to email me with questions, issues and
    frustrations

4
Whats the point?
  • Use a computer to solve problems
  • Algorithm Development
  • Make a plan
  • Get from where you are
  • To where you want to be
  • Use Java Programming language

5
The Central Processing Unit
  • I keep bringing this up because
  • You should be doing it!
  • This is how you play computer to see what your
    program is doing
  • Pretend you are a computer when looking at your
    code
  • Follow the fetch-decode-execute cycle

6
Java Program Structure
// comments about the class
class header
public class MyProgram

// comments about the method
public static void main (String args)
class body

method header
method body
Comments can be placed almost anywhere
7
Java Translation
Java source code
Java bytecode
Java compiler
Bytecode interpreter
Bytecode compiler
Machine code
8
Object-Oriented Programming
  • Java is an object-oriented programming language
  • As the term implies, an object is a fundamental
    entity in a Java program
  • Objects can be used effectively to represent
    real-world entities

9
Object Oriented Programming
  • Abstraction
  • Inheritance
  • Polymorphism
  • Encapsulation

10
Abstraction
  • That is the purpose of objects
  • You create classes/objects that solve small
    pieces of the issue at hand
  • Allows you to separate parts of a problem
  • Fix the individual parts and then forget about
    them

11
Objects
  • An object has
  • state - descriptive characteristics
  • behaviors - what it can do (or what can be done
    to it)
  • Note that the behavior of an object might change
    its state

12
Classes
  • An object is defined by a class
  • A class is the blueprint of an object
  • The class uses methods to define the behaviors of
    the object
  • A class represents a concept, and an object
    represents the embodiment of that concept
  • Multiple objects can be created from the same
    class

13
Classes
  • A class can contain data declarations and method
    declarations

Data declarations
Method declarations
14
Classes
  • The values of the data define the state of an
    object created from the class
  • The functionality of the methods define the
    behaviors of the object

15
Objects and Classes
16
Constructors
  • A constructor is a special method that is used to
    set up an object when it is initially created
  • A constructor has the same name as the class and
    no return value not even void

17
Method Header
  • A method declaration begins with a method header

char calc (int num1, int num2, String message)
method name
parameter list
The parameter list specifies the type and name of
each parameter The name of a parameter in the
method declaration is called a formal parameter
return type
18
Method Body
  • The method header is followed by the method body

char calc (int num1, int num2, String message)
int sum num1 num2 char result
message.charAt (sum) return result
sum and result are local data They are created
each time the method is called, and are destroyed
when it finishes executing
The return expression must be consistent with the
return type
19
The println Method
  • In the Lincoln program from Chapter 1, we invoked
    the println method to print a character string
  • The System.out object represents a destination
    (the monitor screen) to which we can send output

System.out.println ("Whatever you are, be a good
one.")
20
Methods have types too
  • // this add method MUST return an int
  • // because we declared that it does
  • public int add(int x, int y)
  • return x y

21
Methods have types too
  • // this add method MUST NOT return
  • // ANYTHING
  • public void setFilling(string strFilling)
  • filling strFilling

22
Creating Objects
  • A variable holds either a primitive type or a
    reference to an object
  • A class name can be used as a type to declare an
    object reference variable
  • String title
  • No object is created with this declaration
  • An object reference variable holds the address of
    an object
  • The object itself must be created separately

23
Creating Objects
  • Generally, we use the new operator to create an
    object

title new String ("Java Software Solutions")
This calls the String constructor, which is a
special method that sets up the object
  • Creating an object is called instantiation
  • An object is an instance of a particular class

24
Invoking Methods
  • We've seen that once an object has been
    instantiated, we can use the dot operator to
    invoke its methods
  • count title.length()
  • A method may return a value, which can be used in
    an assignment or expression
  • A method invocation can be thought of as asking
    an object to perform a service

25
Variables
  • A variable is a name for a location in memory
  • A variable must be declared by specifying the
    variable's name and the type of information that
    it will hold

int total
int count, temp, result
Multiple variables can be created in one
declaration
26
Primitive Data
  • There are eight primitive data types in Java
  • Four of them represent integers
  • byte, short, int, long
  • Two of them represent floating point numbers
  • float, double
  • One of them represents characters
  • char
  • And one of them represents boolean values
  • boolean

27
Increment and Decrement
  • The increment and decrement operators use only
    one operand
  • The increment operator () adds one to its
    operand
  • The decrement operator (--) subtracts one from
    its operand
  • The statement
  • count
  • is functionally equivalent to
  • count count 1

28
Assignment Operators
  • Often we perform an operation on a variable, and
    then store the result back into that variable
  • Java provides assignment operators to simplify
    that process
  • For example, the statement
  • num count
  • is equivalent to
  • num num count

29
Garbage Collection
  • When an object no longer has any valid references
    to it, it can no longer be accessed by the
    program
  • The object is useless, and therefore is called
    garbage
  • Java performs automatic garbage collection
    periodically, returning an object's memory to the
    system for future use
  • In other languages, the programmer is responsible
    for performing garbage collection

30
Data Scope
  • The scope of data is the area in a program in
    which that data can be referenced (used)
  • Data declared at the class level can be
    referenced by all methods in that class
  • Data declared within a method can be used only in
    that method
  • Data declared within a method is called local data

31
UML Diagrams
  • UML stands for the Unified Modeling Language
  • UML diagrams show relationships among classes and
    objects
  • A UML class diagram consists of one or more
    classes, each with sections for the class name,
    attributes (data), and operations (methods)
  • Lines between classes represent associations
  • A dotted arrow shows that one class uses the
    other (calls its methods)

32
UML Class Diagrams
  • A UML class diagram for the RollingDice program

33
Inheritance
  • One class can be used to derive another via
    inheritance
  • Classes can be organized into hierarchies

34
Encapsulation
  • We can take one of two views of an object
  • internal - the details of the variables and
    methods of the class that defines it
  • external - the services that an object provides
    and how the object interacts with the rest of the
    system
  • From the external view, an object is an
    encapsulated entity, providing a set of specific
    services
  • These services define the interface to the object

35
Encapsulation
  • One object (called the client) may use another
    object for the services it provides
  • The client of an object may request its services
    (call its methods), but it should not have to be
    aware of how those services are accomplished
  • Any changes to the object's state (its variables)
    should be made by that object's methods
  • We should make it difficult, if not impossible,
    for a client to access an objects variables
    directly
  • That is, an object should be self-governing

36
Encapsulation
  • An encapsulated object can be thought of as a
    black box -- its inner workings are hidden from
    the client
  • The client invokes the interface methods of the
    object, which manages the instance data

37
Visibility Modifiers
  • We've used the final modifier to define constants
  • Java has three visibility modifiers public,
    protected, and private
  • The protected modifier involves inheritance,
    which we will discuss later

38
Visibility Modifiers
  • Members of a class that are declared with public
    visibility can be referenced anywhere
  • Members of a class that are declared with private
    visibility can be referenced only within that
    class
  • Members declared without a visibility modifier
    have default visibility and can be referenced by
    any class in the same package

39
Visibility Modifiers
Enforce encapsulation
Violates encapsulation
Support other methods in the class
Provide services to clients
40
Accessors and Mutators
  • Because instance data is private, a class usually
    provides services to access and modify data
    values
  • An accessor method returns the current value of a
    variable
  • A mutator method changes the value of a variable
  • The names of accessor and mutator methods take
    the form getX and setX, respectively, where X is
    the name of the value
  • They are sometimes called getters and setters

41
Conditional Statements
  • A conditional statement lets us choose which
    statement will be executed next
  • Therefore they are sometimes called selection
    statements
  • Conditional statements give us the power to make
    basic decisions
  • The Java conditional statements are the
  • if statement
  • if-else statement
  • switch statement

42
The if Statement
  • The if statement has the following syntax

if ( condition ) statement
43
Boolean Expressions
  • A condition often uses one of Java's equality
    operators or relational operators, which all
    return boolean results
  • equal to
  • ! not equal to
  • lt less than
  • gt greater than
  • lt less than or equal to
  • gt greater than or equal to
  • Note the difference between the equality operator
    () and the assignment operator ()

44
The if Statement
  • An example of an if statement

if (sum gt MAX) delta sum -
MAX System.out.println ("The sum is " sum)
  • First the condition is evaluated -- the value of
    sum is either greater than the value of MAX, or
    it is not
  • If the condition is true, the assignment
    statement is executed -- if it isnt, it is
    skipped.
  • Either way, the call to println is executed next

45
Indentation
  • The statement controlled by the if statement is
    indented to indicate that relationship
  • The use of a consistent indentation style makes a
    program easier to read and understand
  • Although it makes no difference to the compiler,
    proper indentation is crucial

"Always code as if the person who ends up
maintaining your code will be a violent
psychopath who knows where you live." -- Martin
Golding
46
The if-else Statement
  • An else clause can be added to an if statement to
    make an if-else statement

if ( condition ) statement1 else
statement2
  • If the condition is true, statement1 is executed
    if the condition is false, statement2 is
    executed
  • One or the other will be executed, but not both

47
Block Statements
  • In an if-else statement, the if portion, or the
    else portion, or both, could be block statements

if (total gt MAX) System.out.println
("Error!!") errorCount else
System.out.println ("Total " total)
current total2
48
The switch Statement
  • The general syntax of a switch statement is

switch ( expression ) case value1
statement-list1 case value2
statement-list2 case value3
statement-list3 case ...
49
The switch Statement
  • An example of a switch statement

switch (option) case 'A' aCount
break case 'B' bCount
break case 'C' cCount break
50
The while Statement
  • A while statement has the following syntax

while ( condition ) statement
  • If the condition is true, the statement is
    executed
  • Then the condition is evaluated again, and if it
    is still true, the statement is executed again
  • The statement is executed repeatedly until the
    condition becomes false

51
The while Statement
  • An example of a while statement

int count 1 while (count lt 5)
System.out.println (count) count
  • If the condition of a while loop is false
    initially, the statement is never executed
  • Therefore, the body of a while loop will execute
    zero or more times

52
The do Statement
  • A do statement has the following syntax

do statement while ( condition )
  • The statement is executed once initially, and
    then the condition is evaluated
  • The statement is executed repeatedly until the
    condition becomes false

53
The do Statement
  • An example of a do loop

int count 0 do count
System.out.println (count) while (count lt 5)
  • The body of a do loop executes at least once

54
The for Statement
  • A for statement has the following syntax

for ( initialization condition increment )
statement
55
The for Statement
  • A for loop is functionally equivalent to the
    following while loop structure

initialization while ( condition )
statement increment
56
The for Statement
  • An example of a for loop

for (int count1 count lt 5 count)
System.out.println (count)
  • The initialization section can be used to declare
    a variable
  • Like a while loop, the condition of a for loop is
    tested prior to executing the loop body
  • Therefore, the body of a for loop will execute
    zero or more times

57
The for Statement
  • The increment section can perform any calculation

for (int num100 num gt 0 num - 5)
System.out.println (num)
  • A for loop is well suited for executing
    statements a specific number of times that can be
    calculated or determined in advance

58
The for Statement
  • Each expression in the header of a for loop is
    optional
  • If the initialization is left out, no
    initialization is performed
  • If the condition is left out, it is always
    considered to be true, and therefore creates an
    infinite loop
  • If the increment is left out, no increment
    operation is performed

59
JGrasp
  • Is really not so different from BlueJ
  • It has the quasi UML diagram to work from
  • Double click and it opens the file for editing
  • It is still not a production level IDE
  • You dont use this in the real world
  • No intelli-sense

60
JGrasp
  • A better editor
  • It has debugging!!
  • Woo-hoo!
  • IT has CSD
  • Control Structure Diagram
  • Right in the editor
  • This shows you a lot about your code
  • Helps keep track of braces for one thing.

61
JGrasp
  • Demonstrate
  • Projects
  • UML screen
  • Compiling
  • If you are on the UML screen
  • Compiles all
  • If you are in the edit screen
  • Only compiles the one you are looking at
  • Editing
  • CSD
  • Debugging

62
Poseidon
  • I (and probably all future programming
    instructors) require a UML diagram to accompany
    your completed labs
  • Ohhhh Nooooo!
  • But then, I have made it easy for you.
  • Demonstrate
  • http//www.uml.org

63
End Of Week 1
  • End of Week 1

64
Interfaces
  • A Java interface is a collection of abstract
    methods and constants
  • An abstract method is a method header without a
    method body
  • An abstract method can be declared using the
    modifier abstract, but because all methods in an
    interface are abstract, usually it is left off
  • An interface is used to establish a set of
    methods that a class will implement

65
Interfaces
None of the methods in an interface are given a
definition (body)
public interface Doable public void
doThis() public int doThat() public void
doThis2 (float value, char ch) public boolean
doTheOther (int num)
66
Interfaces
  • An interface cannot be instantiated
  • Methods in an interface have public visibility by
    default
  • A class formally implements an interface by
  • stating so in the class header
  • providing implementations for each abstract
    method in the interface
  • If a class asserts that it implements an
    interface, it must define all methods in the
    interface

67
Interfaces
public class CanDo implements Doable public
void doThis () // whatever
public void doThat () // whatever
// etc.
68
Polymorphism
  • The same method name can do different things
  • The method can do what is appropriate for that
    particular object
  • Println is an example

69
Method Overloading
  • Method overloading is the process of giving a
    single method name multiple definitions
  • If a method is overloaded, the method name is not
    sufficient to determine which method is being
    called
  • The signature of each overloaded method must be
    unique
  • The signature includes the number, type, and
    order of the parameters

70
Method Overloading
  • The compiler determines which method is being
    invoked by analyzing the parameters

float tryMe(int x) return x .375
float tryMe(int x, float y) return xy
71
Arrays
  • An array is an ordered list of values

0 1 2 3 4 5 6 7 8
9
An array of size N is indexed from zero to N-1
This array holds 10 values that are indexed from
0 to 9
72
Arrays
  • A particular value in an array is referenced
    using the array name followed by the index in
    brackets
  • For example, the expression
  • scores2
  • refers to the value 94 (the 3rd value in the
    array)
  • That expression represents a place to store a
    single integer and can be used wherever an
    integer variable can be used

73
Arrays
  • Another way to depict the scores array

74
Declaring Arrays
  • The scores array could be declared as follows
  • int scores new int10
  • The type of the variable scores is int (an
    array of integers)
  • Note that the array type does not specify its
    size, but each object of that type has a specific
    size
  • The reference variable scores is set to a new
    array object that can hold 10 integers

75
Declaring Arrays
  • Some other examples of array declarations
  • boolean flags
  • flags new boolean20
  • char codes new char1750

76
Using Arrays
  • The iterator version of the for loop can be used
    when processing array elements

for (int score scores) System.out.println
(score)
  • This is only appropriate when processing all
    array elements from top (lowest index) to bottom
    (highest index)

77
Bounds Checking
  • Once an array is created, it has a fixed size
  • An index used in an array reference must specify
    a valid element
  • That is, the index value must be in range 0 to
    N-1
  • The Java interpreter throws an ArrayIndexOutOfBoun
    dsException if an array index is out of bounds
  • This is called automatic bounds checking

78
Bounds Checking
  • For example, if the array codes can hold 100
    values, it can be indexed using only the numbers
    0 to 99
  • If the value of count is 100, then the following
    reference will cause an exception to be thrown
  • System.out.println (codescount)
  • Its common to introduce off-by-one errors when
    using arrays

for (int index0 index lt 100
index) codesindex index50 epsilon
79
Initializer Lists
  • An initializer list can be used to instantiate
    and fill an array in one step
  • The values are delimited by braces and separated
    by commas
  • Examples

int units 147, 323, 89, 933, 540,
269, 97, 114, 298, 476
char letterGrades 'A', 'B', 'C', 'D', F'
80
Arrays as Parameters
  • An entire array can be passed as a parameter to a
    method
  • Like any other object, the reference to the array
    is passed, making the formal and actual
    parameters aliases of each other
  • Therefore, changing an array element within the
    method changes the original
  • An individual array element can be passed to a
    method as well, in which case the type of the
    formal parameter is the same as the element type

81
Arrays of Objects
  • The elements of an array can be object references
  • The following declaration reserves space to store
    5 references to String objects
  • String words new String5
  • It does NOT create the String objects themselves
  • Initially an array of objects holds null
    references
  • Each object stored in an array must be
    instantiated separately

82
Arrays of Objects
  • The words array when initially declared
  • At this point, the following reference would
    throw a NullPointerException
  • System.out.println (words0)

83
Arrays of Objects
  • After some String objects are created and stored
    in the array

84
Arrays of Objects
  • A UML diagram for the Tunes program

85
Two-Dimensional Arrays
  • A one-dimensional array stores a list of elements
  • A two-dimensional array can be thought of as a
    table of elements, with rows and columns

86
Two-Dimensional Arrays
  • To be precise, in Java a two-dimensional array is
    an array of arrays
  • A two-dimensional array is declared by specifying
    the size of each dimension separately
  • int scores new int1250
  • A array element is referenced using two index
    values
  • value scores36
  • The array stored in one row can be specified
    using one index

87
Two-Dimensional Arrays
__ - -
88
Command-Line Arguments
  • The signature of the main method indicates that
    it takes an array of String objects as a
    parameter
  • These values come from command-line arguments
    that are provided when the interpreter is invoked
  • For example, the following invocation of the
    interpreter passes three String objects into
    main
  • gt java StateEval pennsylvania texas arizona
  • These strings are stored at indexes 0-2 of the
    array parameter of the main method

89
Object Oriented Programming
  • Abstraction
  • Inheritance
  • Polymorphism
  • Encapsulation
  • Now for something completely different.JGrasp

90
Sources
  • http//home.sandiego.edu/calvarado/COMP150/
  • http//www.ucl.ac.uk/SLAIS/rob-miller/lectures/INS
    TG004/LectureNotes/Notes1.html
  • http//duke.csc.villanova.edu/jss1/index.html
  • http//www.soi.city.ac.uk/casey/INM205/lecture1/l
    ecture1.ppt279,38,JAVA Programming Flow Chart
Write a Comment
User Comments (0)
About PowerShow.com