Week 01 b - PowerPoint PPT Presentation

1 / 65
About This Presentation
Title:

Week 01 b

Description:

Used to store the value of an expression in a variable. Syntax: variable = expression ... 23.0 / 4.0 then 23/4 then 23%4. 33. Mixing Numeric Data Types ... – PowerPoint PPT presentation

Number of Views:28
Avg rating:3.0/5.0
Slides: 66
Provided by: davidh67
Category:

less

Transcript and Presenter's Notes

Title: Week 01 b


1
Week 01 - b
  • Primitive Data Types
  • String Methods
  • Simple I/O

2
Sample Programs Referenced(code located in
course folder)
  • objects.DataLabtwoscomp.SimpleBase2Labtwoscomp.T
    wosCompLab(AnimatedIllustrations)
  • BlueJ "Code Pad"
  • FloatPrecision
  • floating.FloatingPointLab(AnimatedIllustrations)
  • strings.StringLab(AnimatedIllustrations)
  • concat.ConCatLab(AnimatedIllustrations)
  • StringTest
  • LastNameInCaps

3
Review Lecture01-a
  • java simcom.SimComFrame
  • Scenario Add255
  • Enter a non-zero value into location 31,
    RunNote that we get the wrong answer! Why?

4
Review Lab 1
  • Main programs without "worker" class (e.g. HW 1,
    Lab 2A)
  • Two ways to Instantiate a class (create an
    object)
  • Client (application) program that uses it
    (normal)
  • Run main method
  • By "hand" BlueJ right-click (useful as teaching
    tool)
  • Comments
  • / / cannot have spaces between and /
  • Programs may have seemed like a lot of "mumbo
    jumbo" to some, but you have all now entered and
    run a complete java program
  • Today we will start explaining the details of the
    Java language

5
"antipasto" Server
  • You saved your lab project to drive H which
    turns out to be a "network drive" stored on the
    CS Dept. server named "antipasto".
  • To access the files, ftp the files to another PC
    using "ssh" program available from ITS (see Union
    College web site "resources")
  • You will need to do this to demo your HW
  • Demo ssh connection to antipasto

6
Questions on HW?
  • Everyone clear as to what you have to do, and how
    to do it???
  • You may demonstrate your HW anytime
  • You don't have to wait until Wednesday
  • (e.g. Stop by my office)
  • I'll be around most of the day tomorrow

7
Data Types
  • Data Type
  • Represents a particular kind of information and
    specifies the operations that can be performed on
    that information
  • Java has some built-in data types
  • Programmers can define their own as classes

8
Primitive Data Types
9
Literals
  • Numbers or character strings that appear in a
    program
  • int literals
  • 0, 1, -1, 2, -2, 3, -3,
  • double literals
  • 19203.45, -48.2, 33.0, 3.14159,
  • char literals 'A', '7', '?', '\n', '\u0041'
  • String literals
  • "George H.W. Bush", "Please enter "

10
Variables and Declarations
  • Variables
  • Used to reference objects (e.g. inner is an
    object of type Circle in Washer)
  • -OR-
  • Used to store primitive values in memory (e.g.
    thickness is of type double in Washer)
  • Declarations
  • Program instruction that tells the compiler the
    name and data type of a variable
  • Necessary to determine the amount of memory
  • Allows the compiler to detect erroneous
    operations on data

11
What happens in memory?
Java Code
Memory
int studentsInclass
20
25
studentsInclass 20
studentsInclass 25
12
Primitive Variables vs. Objects in Memory
double thickness 0.1
Circle inner new Circle()
java objects.DataLab (AnimatedIllustrations)
13
Declaration of Primitive Type Variables
  • Syntax (form)
  • typeName variableName value
  • Examples
  • int quantity
  • double radius
  • char firstLetter 'a'
  • boolean answer true

14
Numeric Data Types
  • int data type
  • Counting, pointing
  • Can test for equality
  • exact value
  • double data type
  • Measuring, approximations
  • weight (digital scale converts to int)
  • time (digital watch converts to int)
  • shouldn't test for equality
  • not exact

15
Primitive Type int
  • Positive and negative whole numbers
  • Literals do not contain commas, decimal points,
    percent signs or dollar signs
  • e.g. 1000000 (not 1,000,000)
  • Allowed operations include addition, subtraction,
    multiplication, and division

16
Primitive type double
  • Real numbers
  • Integer part
  • Fractional part
  • Separated by decimal point
  • Literals do not contain commas, percent signs or
    dollar signs
  • e.g. 1234.5 (not 1,234.50)
  • May use scientific notation
  • e.g. 0.0005 5.0e-4

17
Integer Arithmetic Operations
Watch Out!
18
Base-60 Arithmetic
  • If you add two times made up of hours, minutes
    and seconds, you can consider the values as
    base-60 numbers
  • 3 hrs 5 min 28 sec 18 hrs 4 min 36 sec
  • 28 36 seconds 64 seconds 1 min 4 sec
  • (64/60 quotient
    1, remainder 4)

0
45
15
30
19
Rules for Evaluating Expressions
  • Parenthesis rule
  • Expressions in parentheses evaluated separately.
  • Nested parentheses evaluated from the inside out.
  • Operator precedence rule
  • Operators in the same expression evaluated in
    order of precedence.
  • - (unary minus) highest
  • , /,
  • , - lowest
  • Left associative rule
  • Operators in the same expression and at the same
    precedence level are evaluated in left-to-right
    order.
  • See Self-Check exercises at the end of section 2.2

20
Precedence Examples
  • Example 1
  • 6 37 8 / 5 is the same as
  • 6 ((37 8) / 5)
  • 6 ( 5 / 5) 7
  • Example 2
  • 6 37 (8 / 5)
  • 6 37 1
  • 6 0 6
  • Evaluate Expressions using BlueJ "CodePad"

21
(No Transcript)
22
Example Code with Output
  • public class Primitives
  • public static void main(String args)
  • int i 10
  • System.out.println("int i " i)
  • System.out.println("Integer division\n"
  • "i/3 " (i / 3)
    "\n"
  • "i/11 " (i / 11))

If unsure, experiment!
23
Assignment Statements
  • Used to store the value of an expression in a
    variable
  • Syntax
  • variable expression
  • Effect (for primitive variables)
  • The expression is evaluated and the resulting
    value is stored in the memory location for the
    variable
  • Example
  • weight quantity volume
  • Invalid example
  • quantity volume weight

24
Primitive type char
  • Single character value
  • Letter, digit, punctuation mark, or special
    character
  • Unicode coding scheme (see Appendix B)
  • Each character assigned a unique16 bit binary
    code
  • May be translated into an integer
  • Literals are enclosed in apostrophes
  • E.g. 'a', 'A', '6', ''
  • Escape characters used to represent special
    characters
  • E.g '\n' is a new line and '\t' is a tab character

25
Characters
  • Any key you type on the keyboard generates a
    character which may or may not be displayed on
    the screen (e.g. nonprinting characters)
  • Characters are a primitive type in Java and are
    not equivalent to strings
  • char primitive data type used to represent single
    Unicode characters
  • Examples
  • char vitamin 'A',
  • chromosome 'y',
  • middleInitial 'W'

Note single quotes
26
Important Literal CharactersUNICODE Character
List
27
Characters as Integers
  • It is legal to assign a char to an int variable
  • int i 'a' // assigns 97 to i
  • It is legal to assign an int to an char variable
  • char c 97 // assigns 'a' to c
  • It is possible to perform arithmetic on char
    variables
  • char ch 'a'
  • ch ch 1 // assigns 'b' to ch

28
Encoding (int ? char)
  • Supposed we wanted to shift each letter in our
    name up one position in the alphabet
  • "HAL" would become "IBM"
  • 'H' is 72 73 is 'I'
  • 'A' is 65 66 is 'B'
  • 'L' is 76 77 is 'M'
  • Note what would happen to Z?
  • becomes '' (we need to "wrap around" using mod
    operator)
  • int code (oldLtr 'A' 1) 26
  • char newLtr (code 'A')
  • 'A' thru 'Z' are encoded as 0 thru 25, not 65
    thru 90
  • What if we wanted to shift by n positions?
  • still works...

29
8-bit Integers(AnimatedIllustrations)
  • Unsigned
  • java twoscomp.SimpleBase2Lab
  • Signed
  • java twoscomp.TwosCompLab

30
Internal Representations of Integers
  • Example 1310 8 4 0 1
  • 123 122 021
    120 11012
  • Assume 8 bits are used to represent an integer.
  • Predefined integer types in Java
  • byte (8 bits)
  • short (16 bits)
  • int (32 bits) Used for CSc-105
  • long (64 bits)

31
Real Numbers
  • Numbers with fractional parts
  • 3.14159, 7.12, 9.0, 0.5e001, -16.3e002
  • Declared using the type double
  • double pricePerPound 3.99,
  • taxRate 0.05,
  • shippingCost 5.55
  • The initialization part of the declaration is
    optional
  • Same operations as for integers (except no )

32
Integer vs. Real Division
  • How does integer division differ from real?
  • Back to primary school
    Teacher 4 goes into 23 how many times?
    Pupils 5 times with a remainder 3
  • The expression 23 / 4 returns the quotient.
  • The expression 23 4 returns the remainder.
  • BlueJ CodePad
  • 23.0 / 4.0 then 23/4 then 234

33
Mixing Numeric Data Types
  • Java will automatically convert int expressions
    to double values without loss of information
  • int i 5
  • double x i 10.5
  • To convert double expressions to int requires a
    typecasting operation and truncation will occur
  • i (int) (10.3 x)
  • To round-up instead of truncating add 0.5
  • i (int) (10.3 x 0.5)
  • There is a Math function that will do thismore
    later

34
Limitations of int Variables
  • Unlike the integers in mathematics the type int
    is not infinitely large
  • It is possible to compute a value incorrectly
    because the value is too large to be stored in an
    int variable storage location
  • See text self-check exercises

35
Overflow
  • What is the largest integer that can be
    represented in 8 bits?

27 - 1 127
  • Largest integer 2(number of bits -1) - 1
  • What happens if we try to store a larger number?
  • 1000000 1000000 yields -727379968
  • Try IntegerArithmetic during Break

36
Y2K and Y78 Bugs
  • Y2K
  • Years represented as 2-digit integers
  • Y78
  • DEC PDP-8 12 bit word size
  • Operating system represented date using 1 word
  • Year 1970 0 1971 1

37
Limitations of double Variables
  • Unlike the real numbers in mathematics the type
    double is not dense
  • It is not always possible to test double
    expressions for equality and obtain a correct
    result due to rounding errors in representations
  • See text self-check exercises

38
Range vs. Precision in double
  • Need to represent the whole number part and the
    fractional part (and sign)
  • e.g. 6.625, 1234567.89, -0.00001
  • Where should the decimal point be located?
  • How can we get
  • Large range?
  • Precision?
  • Use scientific notation
  • Independence of precision and range.

39
"Floating Point" Notation
  • Example 6.62510 110.1012
  • .625 1/2 1/8 12(-1)
    02(-2) 12(-3)
  • 110.1012 .1101012 23 (scientific
    notation)
  • Need to store
  • exponent (characteristic) and its sign
  • mantissa (fractional part) and the sign of the
    number
  • Memory cell is divided

sign
exponent
mantissa
40
Internal Representation
  • Exponent (characteristic) treated as an integer
  • overflow will result if characteristic is too
    large
  • Mantissa is stored from most significant to least
    significant bit
  • least significant digits may be truncated or
    rounded
  • e.g. .1101012 x 23

So, 6.625 is stored as 6.5
41
Internal Floating Point(Animated Illustrations)
  • java floating.FloatingFrame

42
Storing 0.110 in binary
  • 0.110 2-4 2-5 2-8 2-9 2-12 2-13
  • 0.0001100110011002 infinitely repeating 1100
  • If we had 4 bits for the mantissa we would get
    0.1100 2-3 .09375
  • If we had 8 bits for the mantissa we would get
    0.11001100 2-3 .099609375
  • If we had 12 bits for the mantissa we would get
    0.1100110011002-3 .0999755859375
  • The more bits we have the more accurate the
    result.
  • Note, however, that it will never be exact!

43
Representational Errors
  • Error depends on number of bits used for
    mantissa.
  • When is this a problem?
  • Dealing with very large and very small numbers in
    same program
  • 1.0E15 1.0E-5 - 1.0E15 yields 0.0 (should be
    1.0E-5)
  • Programs with thousands of iterations can magnify
    a small error into a big one

44
To the Computers...
  • Run BlueJ, then View "Code Pad"
  • Try evaluating expressions such as
  • 1/2/3
  • 1.0/2.0/3.0
  • "hello".length()
  • ltbe creative and try othersgt

45
Java BREAK
46
Introduction to Methods
  • Methods determine
  • what operations objects of a class may perform
  • operations that may be performed on objects of a
    class
  • Examples of methods
  • surroundNameInStars
  • computeWeight
  • main
  • println
  • Common types of operations performed by methods
  • To calculate a result
  • To retrieve a particular data item stored in an
    object
  • To change the state of an object
  • To display the result of an operation
  • To get data from the user

47
Calling a Method
  • Methods must be invoked or called in order to
    do their work
  • Methods are associated with objects (or a class)
  • Syntax of a method call
  • objectName.methodName(argumentList) -or-
  • ClassName.methodName(argumentList)
  • Examples
  • batchWeight quantity wash.computeWeight()
  • System.out.println(Hello)
  • System.out.println(you.surroundNameInStars())
  • NOTE System.out is an object representing the
    console window. It is automatically created when
    the program starts.

48
Object vs. Class Methods
  • Object (Instance) Methods
  • System.out.println()
  • x.doubleIt() see page 54
  • outer.computeArea() from Washer class
  • Class Methods
  • Math.sqrt(3.0)
  • JOptionPane.showInputDialog()
  • Double.parseDouble()

49
Method Arguments(sometimes known as parameters)
  • Purpose
  • provide needed information to the method
  • gives println the text to display
  • gives sqrt the number of which it should find the
    square root
  • Argument List
  • Arguments may be literals, variables, or
    expressions
  • Arguments must be of the correct data type
  • Methods may require more than one argument
  • Separate with commas
  • Order is important

50
The String Class
  • Purpose
  • Used to store and manipulate sequences of
    characters
  • (char used for single characters only)
  • Class provided in standard Java library
  • String variables reference objects that contain
    sequences of characters
  • System.out.println() uses a String argument

51
Declaration and Instantiation
  • Declaration
  • Syntax
  • String variableName
  • Example
  • String firstName
  • Creation (instantiation)
  • Syntax
  • variableName new String(stringLiteral)
  • Example
  • firstName new String("Mike")

52
Instantiating Objects
  • Declaration creates the variable
  • The process of creating an object is called
    instantiation
  • An object is an instance of a class
  • The new operator is used to create or instantiate
    an object
  • Instantiation creates the object and makes the
    variable reference the object
  • String firstName

firstName new String(Mike)
53
Combining Declaration and Instantiation
  • Can use a single statement to declare and
    instantiate an object
  • Syntax
  • ClassName variableName new ClassName(
    argumentList )
  • Example
  • String firstName new String(Mike)
  • Pitfall dont do both
  • String firstName
  • String firstName new String(Mike)

54
Special Properties of Strings
  • The String class is different from other classes
  • Can create a String object without using the new
    operator
  • String firstName Mike
  • Cannot change the characters stored in a String
    object
  • Strings are immutable

55
Operations with String Objects
  • Concatenation operator ?
  • Joins String objects
  • Example
  • String firstName Mike
  • String lastName Smith
  • The expression firstName lastName ? Mike
    Smith
  • Assignment examples
  • String wholeName firstName " " lastName
  • String streetAddress 12 " Main Street"
  • String numString "" 12
  • String charString "" a
  • See project String Test

56
Some String Methods
Note The text uses subString. This is an a
typo.
57
Using String Methods
  • String collegeName "Union College"
  • collegeName.length() ? 13
  • collegeName.charAt(0) ? 'U'
  • collegeName.charAt(1) ? 'n'
  • collegeName.indexOf("o") ? 3
  • collegeName.substring(6) ? "College"
  • collegeName.substring(0, 5) ? "Union"
  • collegeName.indexOf("x") ? -1
  • collegeName.charAt(20) ? run time error

58
Using the Result of a Method Call
  • Storing
  • Can assign the result to a variable of the
    correct type
  • Examples
  • int numChars collegeName.length()
  • char firstChar collegeName.charAt(0)
  • String firstWord collegeName.substring(0, 5)
  • Displaying
  • System.out.println(The first character is
    collegeName.charAt(0))

59
Last Name in Caps(What happens if middle
name/initials?)
  • import javax.swing.
  • public class LastNameInCaps
  • public void capIt()
  • String fullName
  • fullName JOptionPane.showInputDialog(
    "Please enter your full
    name")
  • int len fullName.length()
  • int space fullName.indexOf(' ')
  • fullName fullName.substring(0,space)
  • fullName.substring(space,len).toUpperCase(
    )
  • System.out.println(fullName)
  • // end of capIt method
  • // end of LastNameInCaps class

60
swing and JOptionPane
  • Libraries or packages of classes available
  • Reuse of code
  • swing is a library of classes for building GUIs
  • Libraries or packages must be imported
  • Import statement place at the beginning of the
    file that uses a class or classes from the
    package
  • Syntax import package
  • Examples
  • import javax.swing.
  • import javax.swing.JOptionPane

61
Reading Data with JOptionPane
  • The showInputDialog method of the JOptionPane
    class displays a dialog window with a text box
  • Takes a single String argument for the prompt.
  • Returns a String containing the text typed into
    the box
  • Example

String response JOptionPane.showInputDialog("Ent
er a word")
62
Reading Numeric Data
  • Must convert the String returned to a primitive
    numeric value
  • Use Integer.parseInt(aString) to convert a String
    to an int
  • Use Double.parseDouble(aString) to convert a
    String to a double
  • Example
  • int number
  • String answer
  • answer JOptionPane.showInputDialog(
  • How many students are in the class?)
  • number Integer.parseInt(answer)

63
Displaying Results with JOptionPane
  • The showMessageDialog method of the JOptionPane
    class displays a window with text
  • Takes two arguments
  • null (we will discuss this later)
  • A string with the text to display
  • The method is called for its effect (does not
    return a value)
  • Example

JOptionPane.showMessageDialog(null, "The word is
" response)
64
To the Computers...
  • Try the following program in BlueJ
  • LastNameInCaps
  • Getting project folders from the "course" folder
  • "computer science" Courses
  • "CSC105"
  • "CSc-105 Week 1"

65
Java BREAK
Write a Comment
User Comments (0)
About PowerShow.com