These notes are intended for use by students in CS0401 at the University of Pittsburgh and no one else - PowerPoint PPT Presentation

1 / 257
About This Presentation
Title:

These notes are intended for use by students in CS0401 at the University of Pittsburgh and no one else

Description:

* * * * * Demonstrate propagation on board * * * The recursive calls never stop! * Course Notes for CS 0401 Intermediate Programming (with Java) By John C. Ramirez ... – PowerPoint PPT presentation

Number of Views:319
Avg rating:3.0/5.0
Slides: 258
Provided by: peopleCs7
Category:

less

Transcript and Presenter's Notes

Title: These notes are intended for use by students in CS0401 at the University of Pittsburgh and no one else


1
(No Transcript)
2
  • These notes are intended for use by students in
    CS0401 at the University of Pittsburgh and no one
    else
  • These notes are provided free of charge and may
    not be sold in any shape or form
  • Material from these notes is obtained from
    various sources, including, but not limited to,
    the following
  • Starting Out with Java, From Control Structures
    through Objects, Third to Fifth Editions by
    Gaddis
  • Java Software Solutions, Fourth and Fifth
    Editions by Lewis and Loftus
  • Java By Dissection by Pohl and McDowell
  • The Java Tutorial, by Campione, Walrath and Huml
  • The Java home page and its many sub-links
  • http//www.oracle.com/technetwork/java/index.html

3
Lecture 1 Prerequisites
  • Students taking CS401 should already have some
    programming background
  • Previous experience with Java (ex CS 0007) is
    recommended, but Python, C, C and VB are also
    acceptable
  • Concepts that you are expected to be familiar
    with include
  • Basic program structure and syntax
  • How do we build programs and how do we get them
    to run
  • Primitive types and expressions
  • Numbers, characters, operators, precedence

4
Lecture 1 Prerequisites
  • Control Statements and Decisions
  • Boolean expressions
  • if and switch (or case) statements
  • Loops (for and while)
  • Methods (or functions) and parameters
  • Calling methods and flow of execution
  • Arguments and parameters
  • Arrays and their uses
  • One-dimensional only
  • If you do not have this background, you should
    consider taking CS 0007 before taking CS0401

5
Lecture 1 Goals of the Course
  • Goals for CS 0401 Course
  • To (quickly) cover the basics of the Java
    language (including items mentioned in the
    previous slide)
  • These will be covered more from a Java
    implementa-tion point of view than from a
    conceptual point of view
  • You should already be familiar with (most of) the
    concepts, so learning the Java implementations
    should be fairly straightforward
  • Also will touch on the foundations of
    object-oriented programming
  • This includes Chapters 1-5 of the Gaddis text
  • Those who have had CS 0007 should consider this
    to be an extended review!

6
Lecture 1 Goals of Course
  • To learn the principles of object-oriented
    programming and to see Java from an
    object-oriented point of view
  • Objects, methods and instance variables
  • References and their implications
  • Creating new classes
  • Syntax and logic required
  • Inheritance and composition
  • Building new classes from old classes
  • Polymorphism and dynamic binding
  • Accessing different objects in a uniform way
  • Chapters 6, 8-10 of Gaddis
  • We will focus a lot of attention on these chapters

7
Lecture 1 Goals of Course
  • Note that we are covering OOP concepts using Java
    as our language
  • However, the general principles of
    object-oriented programming apply to any
    object-oriented language
  • Ex C, Objective-C, C, Smalltalk, etc.
  • The more important goal here is to learn to
    program effectively in an object-oriented way
  • Understand why it is good and how to do it

8
Lecture 1 Goals of Course
  • To cover additional useful programming techniques
    and features of Java in order to become
    proficient programmers (using the Java language)
  • Array use and algorithms (sorting, searching)
    (Chapter 7)
  • Reading and Writing Files (Chapters 4, 11
    Notes)
  • Exception Handling (Chapter 11)
  • Graphical User Interfaces and Applications
    (Chapters 12, 13, 14)
  • Introduction to recursion (Chapter 15)

9
Lecture 2 Why Java?
  • Java
  • Java is an interpreted, platform-independent,
    object-oriented language
  • Interpreted, platform-independent
  • Source .java code is compiled into intermediate
    (byte) code
  • Byte code is executed in software via another
    program called an interpreter
  • Benefits
  • More safety features and run-time checks can be
    built into the language discuss
  • Code can be platform-independent
  • As long as the correct interpreter is installed,
    the same byte code can be executed on any platform

10
Lecture 2 Why Java?
JRE for Windows
Java Source Code (.java)
Java Byte Code (.class)
JRE for Linux
Java Compiler
Program Execution
JRE for Solaris
The same .class file can execute on any platform,
as long as the JRE is installed there
JRE for Mac
11
Lecture 2 Why Java?
  • Drawback
  • Interpreted code executes more slowly than
    regular compiled code
  • Since program is run in software rather than
    hardware, it cannot match the execution times of
    code that is compiled for specific hardware
  • Ex C, C code
  • No language is best for every application
  • However, Java implementations can use JIT
    compilation of bytecode to execute faster
  • Object-oriented
  • Primary mode of execution is interaction of
    objects with each other
  • We will discuss object-oriented programming in
    much more detail soon

12
Lecture 2 Getting Started with Java
  • How do we execute Java programs?
  • First we must compile our source (.java) code
    into the intermediate (.class) code
  • We do this with the Java Compiler
  • javac program
  • Next we must interpret our .class code to see the
    result
  • We do this with the Java Interpreter, or Java
    Run-time Environment (JRE)
  • java program

13
Lecture 2 Getting Started with Java
  • Both programs come with the Software Development
    Kit (SDK) for Java
  • This is installed on all of the lab PCs and the
    Mac Minis
  • The most recent version (1.7) can be easily
    downloaded and installed from the Oracle Web
    site
  • http//www.oracle.com/technetwork/java/index.html
  • It is free!
  • More on the basics of using the Java software
    development kit is shown in Lab 1
  • It is already online you will do it next week
  • But lets look at an ex. and talk more about Java
    basics
  • See ex1.java Carefully read the comments!

14
Lecture 2 Getting Started with Java
  • When you have a chance, try the following
  • Download ex1.java from the Web site onto a PC
    that has the SDK installed (yours or a lab PC)
  • Open a terminal (command prompt) window
  • Change to the correct directory
  • Compile the program javac ex1.java
  • Execute the program java ex1
  • Adding the .class extension is optional it is
    assumed even if you dont put it there
  • Show the directory to see that the .class file is
    now there
  • Also try the same thing from one of the Lab
    workstations during your first lab session

15
Lecture 2 Getting Started with Java
  • Note Most developers use an IDE (integrated
    development environment) for program devel.
  • Here are two possibilities
  • http//www.netbeans.org/
  • http//www.eclipse.org/
  • Both are available free
  • Eclipse is installed on the Mac Minis in the Java
    lab
  • These allow you to edit, compile and debug Java
    programs in an easy, integrated way
  • However, you should realize that the final
    program does NOT depend on the IDE, and you
    should be able to compile and run Java programs
    without the IDE
  • I will not be emphasizing these in lecture, but
    you are free to use one if you wish

16
Lecture 2 Java Basics
  • What fundamental entities / abilities do we need
    for any useful Java program?
  • A way to get data into and out of our program
  • I/O
  • A way to create / name / variables and constants
    to store our data
  • Identifiers and variables
  • A way to manipulate / operate on the data
  • Statements and Expressions
  • A way to make decisions and control our flow of
    execution
  • Control structures

17
Lecture 2 Java Basics
  • Output (we will defer input until after we
    discuss variables)
  • Java has a predefined object called System.out
  • This object has the ability to output data to the
    standard output stream, which is usually the
    console (display)
  • This ability is via methods (procedures)
  • Ex print, println
  • We pass information to the System.out object
    through methods and parameters, and the
    information is then shown on the display
  • For example
  • System.out.println(Hello Java Students!)

18
Lecture 2 Java Basics
  • We can output strings, values of variables and
    expressions and other information using
    System.out
  • We will see more on this once we discuss
    variables
  • We will understand how System.out works more
    precisely after we have discussed classes and
    objects later in the term

19
Lecture 2 Java Basics
  • Lexical elements groups of characters used in
    program code
  • These form all of the parts of the program code
  • Ex keywords, identifiers, literals, delimiters
  • We will discuss some of these in the Java
    language
  • Keywords
  • Lexical elements that have a special, predefined
    meaning in the language
  • Cannot be redefined or used in any other way in a
    program
  • Ex program, if, class, throws
  • See p. 10 in Gaddis for complete list

20
Lecture 2 Java Basics
  • Predefined Identifiers
  • Identifiers that were written as part of some
    class / package that are already integrated into
    the language
  • Ex System, Applet, JFrame class names
  • Ex println, start, close method names
  • Ex E, PI constant names
  • Programmers can use these within the context in
    which they are defined
  • In Java there are a LOT because Java has a large
    predefined class library

21
Lecture 2 Java Basics
  • Other Identifiers
  • Defined by programmer
  • used to represent names of variables, methods,
    classes, etc
  • Cannot be keywords
  • We could redefine predefined identifiers if we
    wanted to, but this is generally not a good idea
  • Java IDs must begin with a letter, followed by
    any num- ber of letters, digits, _ (underscore)
    or characters
  • Similar to identifier rules in most programming
    langs

22
Lecture 2 Java Basics
  • Important Note
  • Java identifiers are case-sensitive this means
    that upper and lower case letters are considered
    to be different be careful to be consistent!
  • Ex ThisVariable and thisvariable are NOT the
    same
  • Naming Convention
  • Many Java programmers use the following
    conventions
  • Classes start with upper case, then start each
    word with an upper case letter
  • Ex StringBuffer, BufferedInputStream,
    ArrayIndexOutOfBoundsException
  • Methods and variables start with lower case,
    then start each word with an upper case letter
  • Ex compareTo, lastIndexOf, mousePressed

23
Lecture 2 Java Basics
  • Literals
  • Values that are hard-coded into a program
  • They are literally in the code!
  • Different types have different rules for literal
    values
  • They are fairly intuitive and similar across most
    programming languages
  • Ex Integer
  • An optional /- followed by a sequence of digits
  • Ex String
  • A sequence of characters contained within double
    quotes
  • See Section 2.3 for more details on literals

24
Lecture 2 Java Basics
  • Statements
  • Units of declaration or execution
  • A program execution can be broken down into
    execution of the programs individual statements
  • Every Java statement must be terminated by a
    semicolon ()
  • Ex Variable declaration statement
  • int var1, var2
  • Ex Assignment statement
  • var1 100
  • Ex Method call
  • System.out.println(Answer is var1)
  • We will see many more statements later

25
Lecture 2 Java Basics
  • Variables
  • Memory locations that are associated with
    identifiers
  • Values can change throughout the execution of a
    program
  • In Java, must be specified as a certain type or
    class
  • The type of a variable specifies its properties
    the data it can store and the operations that can
    be performed on it
  • Ex int type discuss
  • Java is fairly strict about enforcing data type
    values
  • You will get a compilation error if you assign an
    incorrect type to a variable Ex int i
    hello

incompatible types found java.lang.String
required int int i "hello"

26
Lecture 2 Java Basics
  • Note For numeric types, you even get an error if
    the value assigned will lose precision if
    placed into the variable
  • Generally speaking this means we can place
    smaller values into larger variables but we
    cannot place larger values into smaller
    variables
  • Ex byte lt int lt long lt float lt double
  • Ex int i 3.5
  • Ex double x 100
  • This is ok

possible loss of precision found double
required int int i 3.5

27
Lecture 3 Java Basics
  • Floating point literals in Java are by default
    double
  • If you assign one to a float variable, you will
    get a loss of precision error as shown in the
    previous slide
  • If you want to assign a more precise value to a
    less precise variable, you must explicitly cast
    the value to that variable type

int i 5 int j 4.5 float x 3.5 float y
(float) 3.5 double z 100 i z y z z
i j (long) y j (byte) y
Error check each of the statements in the box
to the right
28
Lecture 3 Data and Expressions
  • In Java, variables fall into two categories
  • Primitive Types
  • Simple types whose values are stored directly in
    the memory location associated with a variable
  • Ex int var1 100
  • There are 8 primitive types in Java
  • byte, short, int, long, float, double, char,
    boolean
  • See Section 2.4 and ex3.java for more details on
    the primitive numeric types

var1
100
29
Lecture 3 Data and Expressions
  • Reference Types (or class types)
  • Types whose values are references to objects that
    are stored elsewhere in memory
  • Ex String s new String(Hello There)
  • There are many implications to using reference
    types, and we must use them with care
  • Different objects have different capabilities,
    based on their classes
  • We will discuss reference types in more detail
    later when we start looking at Objects

s
Hello There
30
Lecture 3 Data and Expressions
  • Rules for declaration and use
  • In Java, all variables must be declared before
    they can be used Ex x 5.0
  • This will cause an error unless x has previously
    been declared as a double variable
  • Java variables can be initialized in the same
    statement in which they are declared
  • Ex double x 5.0
  • However, keep in mind that two things are being
    done here declaration AND initialization

cannot resolve symbol symbol variable x

location class classname
x 5.0
31
Lecture 3 Data and Expressions
  • Multiple variables of the same type can be
    declared and initialized in a single statement,
    as long as they are separated by commas
  • Ex int i 10, j 20, k 45
  • Multiple variables of different types cannot be
    declared within a single declaration statement
  • See ex2.java

32
Lecture 3 Data and Expressions
  • Operators and Expressions
  • Numeric operators in Java include
  • , , , /,
  • These are typical across most languages
  • A couple points, however
  • If both operands are integer, / will give integer
    division, always producing an integer result
    discuss implications
  • The operator was designed integer operands and
    gives the remainder of integer division
  • However, can be used with floating point as
    well
  • int i, j, k, m
  • i 19 j 7
  • k i / j // answer?
  • m i j // answer?

33
Lecture 3 Data and Expressions
  • Precedence and Associativity
  • What do these mean?
  • Recall that the precedence indicates the order in
    which operators are applied in an expression
  • See Table 2-8
  • Recall that the associativity indicates the order
    in which operands are accessed given operators of
    the same precedence
  • General guidelines to remember for arithmetic
    operators
  • , /, same precedence, left to right
    associativity
  • , same (lower) precedence, also L to R
  • See Table 2-9

34
Lecture 3 More Operators
  • Java has a number of convenience operators
  • Allow us to do operations with less typing
  • Ex
  • X X 1 X
  • Y Y 5 Y 5
  • See Section 2.6 for more details
  • One point that should be emphasized is the
    difference between the prefix and postfix
    versions of the unary operators
  • What is the difference between the statements
  • X X
  • Discuss
  • See ex3.java

35
Lecture 4 Input and the Scanner Class
  • Input
  • Java has a predefined object called System.in
  • Analogous to System.out discussed previously
  • Allows data to be input from the standard input
    stream
  • By default this object allows us to read data
    from the console / keyboard

36
Lecture 4 Input and the Scanner Class
  • In JDK releases up to 1.4
  • Console text input was fairly complicated to use
  • Objects had to be created and exceptions had to
    be handled
  • Made it difficult to show students learning Java
    simple input and output
  • Consequently, textbook authors often created
    their own classes to make console I/O easier
  • But they weren't standard Java, so students would
    not find them useful after their courses ended
  • In JDK 1.5, the Scanner class was added

37
Lecture 4 Input and the Scanner Class
  • Scanner is a class that reads data from the
    standard input stream and parses it into tokens
    based on a delimiter
  • A delimiter is a character or set of characters
    that distinguish one token from another
  • By default the Scanner class uses white space as
    the delimiter
  • The tokens can be read in either as Strings
  • next()
  • Or they can be read as primitive types
  • Ex nextInt(), nextFloat(), nextDouble()

38
Lecture 4 Input and the Scanner Class
  • If read as primitive types, an error will occur
    if the actual token does not match what you are
    trying to read
  • Ex
  • Please enter an int hello
  • Exception in thread "main" java.util.InputMismatch
    Exception
  • at java.util.Scanner.throwFor(Unknown
    Source)
  • at java.util.Scanner.next(Unknown Source)
  • at java.util.Scanner.nextInt(Unknown
    Source)
  • at java.util.Scanner.nextInt(Unknown
    Source)
  • at ex3.main(ex3.java39)
  • These types of errors are run-time errors and in
    Java are called exceptions
  • Java has many different exceptions
  • We'll look at exceptions in more detail later
  • Let's look at ex4.java

39
Lecture 4 Control Statements
  • Java Statements
  • We already discussed some Java statements
  • Declaration statement
  • Assignment statement
  • Method call
  • One of the most important types of statements in
    programming is the control statement
  • Allows 2 very important types of execution
  • Conditional execution
  • Statements may or may not execute
  • Iterative execution
  • Statements may execute more than one time

40
Lecture 4 Control Statements
Linear Execution
Conditional Execution
Iterative Execution
41
Lecture 4 Boolean Expressions
  • Key to many control statements in Java are
    boolean expressions
  • Expressions whose result is true or false
  • true and false are predefined literals in Java
  • Can be created using one or more relational
    operators and logical operators
  • Relational operators
  • Used to compare (i.e. relate) two primitive
    values
  • Result is true or false based on values and the
    comparison that is asserted
  • Ex 6 lt 10 -- true because 6 IS less than 10
  • 7 ! 7 -- false because 7 IS NOT not
    equal to 7

42
Lecture 4 Boolean Expressions
  • Java has 6 relational operatorslt lt gt gt
    !
  • Some boolean expressions are more complicated
    than just a simple relational operation
  • These expressions require logical operators
  • Operate on boolean values, generating a new
    boolean value as a result
  • !
  • Recall their values from a truth table

43
Lecture 5 Boolean Expressions
  • Lets look at some examples
  • int i 10, j 15, k 20
  • double x 10.0, y 3.333333, z 100.0
  • i lt j j lt k x lt y
  • (i / 3) y
  • (x / 3) y
  • !(x ! i)

44
Lecture 5 if statement
  • The if statement is very intuitive
  • if (booleanexpression)
  • lttrue optiongt
  • else
  • ltfalse optiongt
  • Each of lttrue optiongt and ltfalse optiongt can be
    any Java statement, including a block
  • Java blocks are delimited by and can contain
    any number of statements
  • else ltfalse optiongt is optional
  • Note parens around booleanexpression - required

45
Lecture 5 if statement
  • Nested ifs
  • Since both lttrue optiongt and ltfalse optiongt can
    be any Java statement, they can certainly be if
    statements
  • This allows us to create nested if statements
  • We can nest on lttrue optiongt, on ltfalse optiongt
    or both
  • Show on board
  • Enables us to test multiple conditions and to
    have a different result for each possibility

46
Lecture 5 if statement
  • Dangling else
  • The structure of a Java if statement allows for
    an interesting special case
  • if (grade gt 95)
  • if (extraCredit)
  • System.out.println(A)
  • else
  • System.out.println(?)
  • Question is the ltfalse optiongt for condition1 or
    condition2?
  • As shown above it will ALWAYS be for condition2
  • Rule is that an else will always be associated
    with the closest unassociated, non-terminated if

47
Lecture 5 if statement
  • Thus, there is no problem for the computer
  • Problem is if the programmer does not understand
    the rule
  • Result is a LOGIC ERROR
  • Logic errors can be very problematic and
    difficult to correct
  • Unlike a syntax error, which prevents the program
    from being compiled, with a logic error the
    program may run and may seem fine
  • However, one or more errors in the programmers
    logic cause the result will be incorrect!
  • Compare on board SYNTAX ERROR, RUN-TIME ERROR,
    LOGIC ERROR
  • Luckily, in this case the problem is easy to
    correct
  • How?

48
Lecture 5 while loop
  • The while loop is also intuitive
  • while (booleanexpression)
  • ltloop bodygt
  • where ltloop bodygt can be any Java statement
  • Logic of while loop
  • Evaluate (booleanexpression)
  • If result is true, execute ltloop bodygt, otherwise
    skip to next statement after loop
  • Repeat
  • while loop is called an entry loop, because a
    condition must be met to get IN to the loop body
  • Implications of this?

49
Lecture 5 Example
  • Lets now use if and while in a simple program
  • User will enter some scores and the program will
    calculate the average
  • Lets do this together, trying to come up with a
    good solution
  • Consider some questions / issues
  • What is the acceptable range for the scores?
  • What do we do if a score is unacceptable?
  • How many scores are there?
  • Do we even know this in advance?
  • What to do if we do not know this in advance?

50
Lecture 5 Example
  • Are there any special cases that we need to
    consider?
  • What variables will we need to use?
  • And what will be their types?
  • Once we have a solution, lets look at two
    possible solutions
  • ex5a.java and ex5b.java
  • Note that for many programming problems, there
    are MANY possible solutions

51
Lecture 6 for loop
  • The for loop is more complicated
  • Its obvious use is as a counting loop
  • Goes through a specified number of iterations
  • for (int i 0 i lt max i)
  • // will iterate max times
  • However it is much more general than that
  • for (init_expr go_expr inc_expr)
  • // loop body
  • Lets talk about this a bit

52
Lecture 6 for loop
  • init_expr
  • Any legal Java statement expression
  • Evaluated one time, when the loop is FIRST
    executed
  • go_expr
  • Java Boolean expression
  • Evaluated PRIOR to each execution of the for loop
    body
  • If true, body is executed
  • If false, loop terminates
  • inc_expr
  • Any legal Java statement expression
  • Evaluated AFTER each execution of the for loop
    body
  • These expressions make the for loop extremely
    flexible

53
Lecture 6 for loop
  • Try some examples
  • For loop to sum the numbers from N to M
  • N (N1) (M-1) M
  • For loop to output powers of 2 less than or equal
    to K
  • See forexamples.java
  • In effect we can use a for loop as if it were a
    while loop if wed like
  • However, it is more readable and less prone to
    logic errors if you use it as a counting loop
  • Lets look at the programs from Example 5, but
    now with a for loop ex5c.java and ex5d.java

54
Lecture 6 for loop
  • In Java 1.5, there is an additional, new version
    of the for loop
  • for (type var iterator_obj)
  • ltloop bodygt
  • This version is called the "foreach" loop
  • In a lot of scripting languages such as Perl and
    PHP, so it was adopted into Java
  • However, to use it we need to understand
    something about objects and iterators
  • This version is really cool!
  • We will come back and talk about this shortly

55
Lecture 7 switch statement
  • We know that if can be used in a multiple
    alternative form
  • If we nest statements
  • Sometimes choices are simple, integral values
  • In these cases, it is easier and more efficient
    to use a more specialized statement to choose
  • This is where switch comes in handy
  • However it is kind of wacky so be careful to use
    it correctly!

56
Lecture 7 switch statement
  • switch (int_expr)
  • case constant_expr
  • case constant_expr
  • default // this is optional
  • int_expr is initially evaluated
  • constant_expr are tested against int_expr from
    top to bottom
  • First one to match determines where execution
    within the switch body BEGINS
  • However, execution will proceed from there to the
    END of the block

57
Lecture 7 switch statement
  • If we want the execution of the different cases
    to be exclusive of each other, we need to stop
    execution prior to the next case
  • We can do this using the break statement
  • Switch is actually passed down to Java from C
    it doesnt really fit too well with the spirit of
    the Java language, but it is there and can be
    used
  • Lets look at an example using switch
  • Program to rate movies
  • User enters a star value from 1-4 and the
    program comments back on the movie quality
  • See ex6.java
  • Handout also shows some formatting
  • See also ex6b.java

58
Lecture 7 Methods and Method Calls
  • If programs are short
  • We can write the code as one contiguous segment
  • The logic is probably simple
  • There are not too many variables
  • Not too likely to make a lot of errors
  • As programs get longer
  • Programming in a single segment gets more and
    more difficult
  • Logic is more complex
  • Many variables / expressions / control statements

59
Lecture 7 Methods and Method Calls
  • Chances of bugs entering code is higher
  • Isolating and fixing is also harder
  • If multiple people are working on the program, it
    is difficult to break up if written as one
    segment
  • If parts need to be modified or added, it is
    difficult with one large segment
  • If similar actions are taken in various parts of
    the program, it is inefficient to code them all
    separately
  • And can also introduce errors
  • Ex Draw a rectangle somewhere in a window
  • Most of these problems can be solved by breaking
    our program into smaller segments
  • Ex Break some sticks!

60
Lecture 7 Methods and Method Calls
  • Method (or function or subprogram)
  • A segment of code that is logically separate from
    the rest of the program
  • When invoked (i.e. called) control jumps from
    main to the method and it executes
  • Usually with parameters (arguments)
  • When it is finished, control reverts to the next
    statement after the method call
  • Show on board

61
Lecture 7 Functional Abstraction
  • Methods provide us with functional (or
    procedural) abstraction
  • We do not need to know all of the impl. details
    of the methods in order to use them
  • We simply need to know
  • What arguments (parameters) we must provide
  • What the effect of the method is (i.e. what does
    it do?)
  • The actual implementation could be done in
    several different ways
  • Ex Predefined method sort(Object a)
  • There are many ways to sort!
  • This allows programmers to easily use methods
    that they didnt write

62
Lecture 7 Return Value vs. Void
  • Java methods have two primary uses
  • To act as a function, returning a result to the
    calling code
  • In Java these methods are declared with return
    types, and are called within an assignment or
    expression
  • Ex X inScan.nextDouble()
  • Y (Math.sqrt(X))/2
  • To act as a subroutine or procedure, executing
    code but not explicitly returning a result
  • In Java these methods are declared to be void,
    and are called as separate stand-alone statements
  • Ex System.out.println(Wacky)
  • Arrays.sort(myData)

63
Lecture 7 Predefined Methods
  • There are MANY predefined methods in Java
  • Look in the online API
  • These are often called in the following way
  • ClassName.methodName(param_list)
  • Where ClassName is the class in which the method
    is defined
  • Where methodName is the name of the method
  • Where param_list is a list of 0 or more variables
    or expressions that are passed to the method
  • Ex Y Math.sqrt(X)
  • These are called STATIC methods or CLASS methods
  • They are associated with a class, not with an
    object

64
Lecture 7 Predefined Methods
  • Some are also called in the following way
  • ClassName.ObjectName.methodName(param_list)
  • Where ObjectName is the name of a static,
    predefined object that contains the method
  • Ex System.out.println(Hello There)
  • System is a predefined class
  • out is a predefined PrintStream object within
    System
  • println is a method within PrintStream
  • These are instance methods associated with an
    object we will discuss these shortly
  • For now we will concentrate on static methods

65
Lecture 7 Writing Static Methods
  • What if we need to use a method that is not
    predefined?
  • We will have to write it ourselves
  • Syntax
  • public static void methodName(param_list)
  • // method body
  • public static retval methodName(param_list)
  • // method body
  • Where retval is some Java type
  • When method is not void, there MUST be a return
    statement

66
Lecture 7 Writing Static Methods
  • Really simple example
  • public static void sayWacky()
  • System.out.println(Wacky)
  • Now in our main program we can have
  • sayWacky()
  • sayWacky()
  • for (int i 0 i lt 5 i)
  • sayWacky()
  • Note we are not using any parameters in this
    example

67
Lecture 7 Writing Static Methods
  • So what about the param_list?
  • It is a way in which we pass values into our
    methods
  • This enables methods to process different
    information at different points in the program
  • Makes them more flexible
  • In the method definition
  • List of type identifier pairs, separated by
    commas
  • Called formal parameters, or parameters
  • In the method call
  • List of variables or expressions that match 1-1
    with the parameters in the definition
  • Called actual parameters, or arguments

68
Lecture 7 Writing Static Methods
  • Ex
  • public static double area(double radius)
  • double ans Math.PI radius radius
  • return ans
  • double rad 2.0
  • double theArea area(rad)
  • Note If method is called in same class in which
    it was defined, we dont need to use the class
    name in the call

parameter argument
69
Lecture 7 Parameters
  • Parameters in Java are passed by value
  • The parameter is a copy of the evaluation of the
    argument
  • Any changes to the parameter do not affect the
    argument

answer calculated
method completed
answer returned
area method
Main Class
value passed from arg. to parameter
radius
rad
2.0
2.0
ans
12.566
result returned to main
theArea
12.566
double ans Math.PI radius radius
double theArea area(rad)
main calls area method
return ans
70
Lecture 8 More on Parameters
  • Effect of value parameters
  • Arguments passed into a method cannot be changed
    within the method, either intentionally or
    accidentally
  • Good result Prevents accidental side-effects
    from methods
  • Bad result What if we want the arguments to be
    changed?
  • Ex swap(A, B)
  • Method swaps the values in A and B
  • But with value parameters will be a no-op
  • - Discuss
  • We can get around this issue when we get into
    object-oriented programming

71
Lecture 8 Local variables and scope
  • Variables declared within a method are local to
    that method
  • They exist only within the context of the method
  • This includes parameters as well
  • Think of a parameter as a local variable that is
    initialized in the method call
  • We say the scope of these variables is point in
    the method that they are declared up to the end
    of the method
  • Show on board

72
Lecture 8 Local variables and scope
  • However, Java variables can also be declared
    within blocks inside of methods
  • In this case the scope is the point of the
    declaration until the end of that block
  • Show on board
  • Be careful that you declare your variables in the
    correct block
  • See Java Debug Help slides for more details
  • debug.ppt

73
Lecture 8 Local variables and scope
  • Note that either way, local variables cannot be
    shared across methods
  • In other words, a local variable declared in one
    method cannot be accessed in a different method
  • We can still get data from one method to another
  • How?
  • To share variables across methods, we need to use
    object-oriented programming
  • We will see this soon!
  • See ex7.java

74
Lecture 8 References and Reference Types
  • Recall from Slides 28-29 that Java has primitive
    types and reference types
  • Also recall how they are stored
  • With primitive types, data values are stored
    directly in the memory location associated with a
    variable
  • With reference types, values are references to
    objects that are stored elsewhere in memory

var1
100
s
Hello There
75
Lecture 8 References and Reference Types
  • What do we mean by references?
  • The data stored in a variable is just the
    address of the location where the object is
    stored
  • Thus it is separate from the object itself
  • Ex If I have a Contacts file on my PC, it will
    have the address of my friend, Joe Schmoe (stored
    as Schmoe, J.)
  • I can use that address to send something to Joe
    or to go visit him if I would like
  • However, if I change that address in my Contacts
    file, it does NOT in any way affect Joe, but now
    I no longer know where Joe is located
  • However, I can indirectly change the data in the
    object through the reference
  • Knowing his address, I can go to Joes house and
    steal his 90 inch 1080p 240Hz LED LCD 3D HDTV

76
Lecture 8 Classes and Objects
  • What do we mean by "objects"?
  • Let's first discuss classes
  • Classes are blueprints for our data
  • The class structure provides a good way to
    encapsulate the data and operations of a new type
    together
  • Instance data and instance methods
  • The data gives us the structure of the objects
    and the operations show us how to use them
  • Ex A String
  • Discuss

77
Lecture 8 Classes and Objects
  • User of the class knows the general nature of the
    data, and the public methods, but NOT the
    implementation details
  • But does not need to know them in order to use
    the class
  • Ex BigInteger
  • We call this data abstraction
  • Compare to functional abstraction discussed
    previously
  • Java classes determine the structure and behavior
    of Java objects
  • To put it another way, Java objects are instances
    of Java classes

78
Lecture 8 Classes and Objects
class Foo int x void f()
Class Foo definition
Foo object
x 10 f()
Declaring Foo variable Creating Foo object
Foo F F new Foo(10)
F
Foo reference
79
Lecture 8 More References
  • Back to references, let's now see some of the
    implications of reference variables
  • Declaring a variable does NOT create an object
  • We must create objects separately from declaring
    variables
  • StringBuilder S1, S2
  • Right now we have no actual StringBuilder objects
    just two variables that could access them
  • To get objects we must use the new operator or
    call a method that will create an object for us
  • S1 new StringBuilder("Hello")
  • S1 now references an instance of a StringBuilder
    object but S2 does not

80
Lecture 8 More References
  • So what value does S2 have?
  • For now we will say that we should not count on
    it to have any value we must initialize it
    before we use it
  • If we try to access it without initializing it,
    we will get an error
  • Multiple variables can access and alter the same
    object
  • S2 S1
  • Now any change via S1 or S2 will update the same
    object

S1
Hello
S2
81
Lecture 9 More References
  • Properties of objects (public methods and public
    instance variables) are accessed via "dot"
    notation
  • S1.append(" there Java maestros!")
  • S2 will also access the appended object
  • Comparison of reference variables compares the
    references, NOT the objects
  • StringBuilder S3
  • new StringBuilder("Hello there Java
    maestros!")
  • if (S1 S2) System.out.println("Equal") // yes
  • if (S1 S3) System.out.println("Equal") // no
  • What if we want to compare the objects?

82
Lecture 9 More References
  • We use the equals() method
  • This is generally defined for many Java classes
    to compare data within objects
  • We will see how to define it for our own classes
    soon
  • However, the equals() method is not (re)defined
    for the StringBuilder class, so we need to
    convert our StringBuilder objects into Strings in
    order to compare them
  • if (S1.toString().equals(S3.toString()))
  • System.out.println("Same value") // yes
  • We will also use the compareTo() method later
  • It seems complicated but it will make more sense
    when we get into defining new classes

83
Lecture 9 More references
  • Note the difference in the tests
  • The operator shows us that it is the same
    object
  • The equals method show us that the values are in
    some way the same (depending on how it is
    defined)
  • References can be set to null to initialize or
    reinitialize a variable
  • Null references cannot be accessed via the "dot"
    notation
  • If it is attempted a run-time error results
  • S1 null
  • S1.append("This will not work!")

84
Lecture 9 More references
  • Why?
  • The method calls are associated with the OBJECT
    that is being accessed, NOT with the variable
  • If there is no object, there are no methods
    available to call
  • Result is NullPointerException common error so
    remember it!
  • Let's take a look at ex8.java
  • Side note speaking of common errors
  • Take another look at debug.ppt it has some of
    the things we just mentioned

85
Lecture 9 Intro. to Object-Oriented Programming
(OOP)
  • Object-Oriented Programming consists of 3 primary
    ideas
  • Data Abstraction and Encapsulation
  • Operations on the data are considered to be part
    of the data type
  • We can understand and use a data type without
    knowing all of its implementation details
  • Neither how the data is represented nor how the
    operations are implemented
  • We just need to know the interface (or method
    headers) how to communicate with the object
  • Compare to functional abstraction with methods
  • We discussed this somewhat already

86
Lecture 9 Intro. to OOP
  • Inheritance
  • Properties of a data type can be passed down to a
Write a Comment
User Comments (0)
About PowerShow.com