CSC 332 Algorithms and Data Structures - PowerPoint PPT Presentation

1 / 78
About This Presentation
Title:

CSC 332 Algorithms and Data Structures

Description:

http://www.yourdictionary.com/crossword/romanums.html ... We view objects as atomic units the parts cannot be dissected by the general ... – PowerPoint PPT presentation

Number of Views:42
Avg rating:3.0/5.0
Slides: 79
Provided by: acade124
Category:
Tags: csc | abc | algorithms | com | data | structures | the | view

less

Transcript and Presenter's Notes

Title: CSC 332 Algorithms and Data Structures


1
CSC 332 Algorithms and Data Structures
  • Java Overview

Dr. Paige H. Meeker Computer Science Presbyterian
College, Clinton, SC
2
Answers to previous assignment
  • Problem 1
  • Create a class called LeapYear that will accept
    console input from the user of a year and return
    a statement (true or false) if that year is a
    leap year.
  • Sample output
  • What year would you like to test?
  • ltuser inputgt 1984
  • It is true that 1984 is a leap year.

3
Calculating Leap Years
  • public boolean isLeap(int year)
  • if ((year 100) 0)
  • if ((year 400) 0) return true
  • else return false
  • if ((year 4) 0) return true
  • return false

4
Answers to previous assignment
  • Problem 2
  • Write a program to determine all pairs of
    positive integers, (a,b), such that
  • a lt b lt 1000
  • (a2 b2 1)/(ab) is an integer.

5
Positive Integer Calculation
  • for (int i 1 i lt 1000 i)
  • for (int j 1 j lt 1000 j)
  • if (i lt j)
  • int a ii
  • int b jj
  • if (((ab1)(ij)) 0)
  • System.out.println ("a "i" b
    "j)

6
Answers to previous assignment
  • Problem 3
  • Create a class called Roman that will accept
    console input from the user of an integer and
    return its Roman numeral equivalent.
  • For conversion information, see
  • http//www.yourdictionary.com/crossword/romanums.h
    tml
  • http//www.novaroma.org/via_romana/numbers.html

7
Roman Numeral Calculation
  • private static int numbers 1000, 900, 500,
    400, 100, 90, 50, 40, 10, 9, 5, 4, 1
  • private static String letters "M", "CM",
    "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V",
    "IV", "I"
  • public String convert(int arabic)
  • String roman ""
  • for (int i 0 i lt numbers.length i)
  • while (arabic gt numbersi)
  • roman lettersi
  • arabic - numbersi
  • return roman

8
Lecture 2 Java Overview
  • Primitive Java
  • Reference Types
  • Objects and Classes
  • Inheritance

9
Primitive Java
  • Conditional Statements
  • Relational and Equality Operators
  • Logical Operators
  • if
  • while
  • for
  • do
  • break and continue
  • Switch
  • Methods
  • Comments
  • main
  • Primitive Types
  • Constants
  • Declaration and Initialization of Primitive Types
  • Basic Operators
  • Assignment
  • Binary
  • Unary
  • Type Conversions

10
Reference Types
  • Define
  • Basics
  • Dot operator
  • Declaration
  • vs
  • Parameter passing
  • Strings
  • Arrays
  • Exceptions
  • I/O

11
Objects and Classes
  • Definition
  • Javadoc
  • Basic Methods
  • Constructors
  • Mutator/Accessor
  • toString(), equals()
  • main()
  • Static
  • this
  • instanceOf
  • Packages
  • Creating / Importing

12
Inheritance
  • Definition
  • Hierarchies
  • Type compatibility
  • Super and Final
  • Overriding vs Overloading
  • Abstract methods / Classes
  • Multiple Inheritance
  • Interface
  • Generic Components

13
Primitive Java Basics to Begin With
  • Java code lives in files that end in .java
  • Compiler is javac
  • javac generates bytecode found in .class files
  • Bytecodes are portable, interpreted by the Java
    interpreter java aka the Java Virtual Machine

14
Primitive Java Basics to Begin With
  • The name of the source file must match the name
    of the class, including case conventions.

15
Primitive JavaComments
  • // indicates a single line comment
  • / indicates a multi-line comment /
  • / indicates a comment that provides information
    to the javadoc utility to generate documentation
    from the comments /
  • Well commented code is the sign of a good
    programmer!!

16
Primitive JavaPrimitive Types
  • 8 primitive types
  • byte
  • short
  • int
  • long
  • float
  • double
  • char
  • boolean

17
Primitive JavaConstants
  • Integer constants can be represented in decimal,
    octal, or hexadecimal notation
  • Character constants are enclosed in single quotes
  • String constants are enclosed in double quotes

18
Primitive JavaDeclaration and Initialization of
Primitive Types
  • Variables declared by providing
  • Name
  • Type
  • (Hopefully) Initial Value
  • Name must be an identifier
  • Any combination of letters/digits/_ but cant
    start with a digit.
  • Reserved Words not allowed
  • Java is case-sensitive (age ! Age)

19
Primitive JavaDeclaration and Initialization of
Primitive Types
  • Naming Conventions
  • Typically, variables start with a lower case
    letter and new words start with an uppercase
    letter.
  • minimumWage
  • operatorTest
  • Etc

20
Primitive JavaBasic Operators
  • Assignment
  • , , -, , /
  • Binary Arithmetic Operators
  • ,-,,,
  • Unary Operators
  • -, , --
  • Type Conversions

21
Primitive JavaConditional Statements
  • Relational and Equality Operators
  • Equality Operators and !
  • Relational Operators lt, lt, gt, gt

22
Primitive JavaConditional Statements
  • Logical Operators
  • AND
  • OR
  • NOT !

23
Primitive JavaIf Statement
  • if (expression)
  • statements
  • Next statements
  • if (expression)
  • statements
  • else
  • more statements
  • Next statements

24
Primitive JavaWhile Statement
  • while (expression)
  • statements
  • Next statements

25
Primitive JavaFor Statement
  • for (initialization test update)
  • statements
  • Next statements

26
Primitive JavaDo Statement
  • do
  • statements
  • while (expression)
  • Next statements

27
Primitive Javabreak
  • outer
  • while ()
  • while ()
  • if (disaster) break outer
  • // Go to after outer labeled loop
  • Statement where break would go if no outer
  • //Control passes here after outer loop is exited.

28
Primitive Javacontinue
  • for (int i i lt 100 i)
  • if (i10 0) continue
  • System.out.println(i)

29
Primitive Javaswitch
  • The switch statement is used to select among
    several small integer (or character) values

30
Primitive JavaConditional Operator ?
  • Shorthand for simple if-else statements
  • testExpr ? yesExpr noExppr
  • Example
  • minVal xlty ? x y

31
Primitive Javamethods
  • Function or Procedure
  • Header
  • Name
  • Parameter List
  • Return Type
  • Overloading

32
Primitive JavaConstants
  • static
  • final

33
Reference TypesDefinition
  • Any type that is not one of the 8 primitive types
    is a reference type. This includes
  • Strings
  • Arrays
  • File Streams
  • Classes you Create

34
Reference TypesReference Variables
  • Variable that stores the memory address where an
    object resides
  • (see figure 2.1, p. 28)

35
Reference TypesReference Variables
  • Only operators allowed on references themselves
  • Assignment
  • Equality comparison or !
  • Operations allowed on object being referenced
  • Type conversion
  • Access internal field or call method (dot
    operator)
  • Use instanceof operator to verify stored object
    is of a certain type

36
Reference TypesBasics
  • dot operator (.)
  • Used to select a method that is applied to an
    object
  • Can access individual components of an object if
    they are viewable

37
Reference TypesBasics
  • Declaration of Objects
  • Declaration simply provides a name for an object,
    not the actual object.
  • Must construct the object using new
  • Construction can specify an initial state for the
    object

38
Reference TypesBasics
  • Garbage Collection
  • When a constructed object is no longer
    referenced by any variable, the memory it
    consumes is reclaimed and made available

39
Reference TypesBasics
  • Meaning of
  • Stored values are copied
  • lhs rhs
  • lhs now refers to the same object as rhs.
    Objects are not copied this way. If you need to
    copy, use the clone method

40
Reference TypesBasics
  • Parameter Passing
  • Call-by-value
  • Figure 2.3

41
Reference TypesBasics
  • Meaning of
  • lhs rhs if and only if they reference the same
    object. To compare the actual objects
    referenced, you need an equals method

42
Reference TypesStrings
  • Strings behave as reference types except that
    concatenation is allowed (using operators and
    )
  • RULES
  • Strings behave as objects except for the
    allowance of concatenation
  • Strings are immutable

43
Reference TypesStrings
  • Concatenation
  • this that //generates this that
  • abc5 //generates abc5
  • Comparison
  • Use equals() and compareTo() methods
  • Other methods
  • length - compute string length
  • charAt - get a single character
  • substring get a substring

44
Reference TypesStrings
  • toString() converts primitive types and object to
    Strings

45
Reference TypesArrays
  • A basic mechanism for storing a collection of
    identically typed entities
  • Each entity accessed via the array indexing
    operator
  • Arrays always start at 0

46
Reference TypesArrays
  • Declaration
  • int array1 new int 100
  • //creates array of 100 ints
  • int array2 3, 4, 5
  • Try to get the size right the first time
    expanding arrays involves copying each individual
    value over a sometimes costly process

47
Reference TypesArrayLists
  • ArrayList is used for expanding arrays
  • add method increases size by 1 and adds new item
    to array at appropriate position, expanding
    capacity if necessary
  • Can only add objects no primitive types allowed!

48
Reference TypesMultidimensional Arrays
  • Arrays accessed by more than one index an array
    of arrays!

49
Reference TypesException Handling
  • Exceptions are used to handle exceptional
    occurrences such as errors. A try block
    encloses code that might generate an exception,
    and a catch block processes the exception. If
    things must be cleaned up before the exception is
    completed, the finally clause is used.

50
Reference TypesException Handling finally
clause
  • Three ways finally is used 1. The try block
    executes without exception control will pass to
    finally block. This will be true even if try
    block exits prior to the last statement via a
    return, break, or continue.

51
Reference TypesException Handling finally
clause
  • Three ways finally is used
  • 2. An uncaught exception is encountered inside
    the try block control passes to the finally
    block. After executing the finally block, the
    exception propogates.

52
Reference TypesException Handling finally
clause
  • Three ways finally is used
  • 3. If caught exception encountered in try block,
    control passes to appropriate catch block. After
    the catch block is executed, the finally block is
    executed.

53
Reference TypesException Handling
  • Common Exceptions
  • Runtime exceptions
  • Checked exceptions
  • Errors

54
Reference TypesRuntime Exceptions
  • Do not have to be handled include events like
    divide-by-zero, illegal array access, etc. Do not
    have to be caught. Typically result in abnormal
    program termination.

55
Reference TypesChecked Exceptions
  • Must be handled programmer must include a catch
    block or a throws clause clause, allowing the
    exception to be passed back to a method that will
    handle it. Examples include end-of-file or
    file-not-found problems.

56
Reference TypesErrors
  • Errors are problems with the virtual machine.
    OutOfMemory or UnknownError are examples
    usually unrecoverable, should not be caught.

57
Reference TypesThrow and Throws
  • Throw clause used to throw an exception
  • Throws clause indicates propogated exceptions

58
Reference TypesI/O
  • java.io package contains many methods to
    input/output information. Includes
  • Stream operations
  • System.in, System.out, System.err
  • StringTokenizer
  • FileReader

59
Homework!!
  • Due Tuesday, Sept. 5
  • Assignment 2

60
Objects and Classes
  • Definition and creation
  • Public / Private sections
  • Specification vs. Implementation
  • Constructors
  • Accessors and Mutators
  • toString
  • equals
  • Packages
  • this
  • instanceof Operator
  • static class members
  • Design Patterns

61
Objects and ClassesDefinition and Creation
  • An object is a data type that has structure and
    state.
  • We view objects as atomic units the parts
    cannot be dissected by the general users of the
    object
  • Information hiding makes implementation details,
    including components of an object, inaccessible
  • Encaptulation is the grouping of data and the
    operations that apply to them to form an
    aggregate, while hiding the implementation of the
    agregate.

62
Objects and ClassesDefinition and Creation
  • Object oriented code supports reuse through
  • Generic code
  • Inheritance
  • Polymorphism

63
Objects and ClassesDefinition and Creation
  • An object is an instance of a class, which
    consists of fields that store data and methods
    that are applied to instances of the class

64
Objects and ClassesPublic vs Private
  • Public members are visible to non-class routines
  • Private members are not all data members should
    be private (in general)

65
Objects and ClassesFields and Methods
  • Field stores data
  • Method performs an action

66
Objects and ClassesClass Specification and
Javadoc
  • Class specification represents what can be done
    to an object while the implementation represents
    how these specifications are met
  • The javadoc program can be run to automatically
    generate documentation for classes in HTML format

67
Objects and ClassesClass Specification and
Javadoc
  • Comments that begin with / will be added to the
    documentation produced by the javadoc command
  • Special tags include _at_author, _at_param, _at_return,
    _at_throws

68
Objects and ClassesCommon Methods
  • Constructors
  • Accessors
  • Mutators
  • toString
  • equals
  • main

69
Objects and ClassesCommon Methods
  • Constructor
  • Tells how an object is declared and initialized.
  • Classes can have multiple constructors
  • Default constructor initializes primitive fields
    to 0 and reference fields to null. (Exists only
    if there are no other constructors written)
  • Constructors are methods with the same name as
    the class and no return type

70
Objects and ClassesCommon Methods
  • Mutators and Accessors
  • Accessors examine data of the class, but do not
    change it.
  • Mutators change the data of the class in a
    specified way.

71
Objects and ClassesCommon Methods
  • public String toString()
  • Method that returns a string based on the objects
    state. Default returns the objects memory
    location unless creator of the class overrides it.

72
Objects and ClassesCommon Methods
  • public boolean equals(Object a)
  • Method that tests to see if two objects hold the
    same value(s). The parameter to equals is an
    Object and must be checked to ensure it is an
    instanceOf the same class.

73
Objects and ClassesCommon Methods
  • public static void main
  • Method called when java .class files are run.

74
Objects and ClassesStatic Fields and Methods
  • Static methods do not need a controlling object
    called by using the class name instead of an
    object name. Some fields are also static and if
    static is used with the keyword final, the field
    is a constant.

75
Objects and Classesthis
  • this is a reference to the current object can
    be used to send the current object, as a unit, to
    some other method
  • Sometimes used to create default constructors
  • public Date()
  • this(1,1,2006)//call 3 parameter
    construtor

76
Objects and ClassesinstanceOf
  • Used to test if an expression is an instance of
    some class

77
Objects and ClassesPackages
  • Organizes a collection of classes
  • The import directive is used to provide shorthand
    for a fully qualified class name
  • The package statement indicates that a class is
    part of a package it precedes the class
    definition and the class is stored in a folder
    with that package name.

78
Inheritance
  • Definition
  • Hierarchies
  • Type compatibility
  • Super and Final
  • Overriding vs Overloading
  • Abstract methods / Classes
  • Multiple Inheritance
  • Interface
  • Generic Components
Write a Comment
User Comments (0)
About PowerShow.com