43
Some Java Fundamentals Chapter 2

Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Some Java Fundamentals

Chapter 2

Page 2: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Chapter Contents

Chapter Objectives2.1 Example: A Payroll Program2.2 Types, Variables, and ConstantsPart of the Picture: Data Representation2.3 Some Basic Program Features2.4 Java Documentation2.5 Introduction to GUIs: A GUI Greeter

Page 3: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Chapter ObjectivesObserve Java primitive types and their literalsExplain Java syntax rulesContrast primitive types and reference typesStudy variables and constantsInvestigate internal representation of primitive types

Page 4: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Chapter ObjectivesObserve the structure and declaration of classesDiscover need for import statementsNote how to use methodsStudy Java API organizationLook at designing and building simple GUI applications

Page 5: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

2.1 Example: A Payroll Program

Computerize the calculation of employee wages.

Employees are paid a fixed hourly rateThey can work any number of hoursNo overtime is paid

Use object-oriented designDescribe behaviorIdentify objectsIdentify operationsOrganize objects & operations in an algorithm

Page 6: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

BehaviorDisplay on the screen a prompt for …

hours workedhourly rate

Enter values via keyboardCompute wagesDisplay calculations with descriptive label

Page 7: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

ObjectsDescription of

objectType kind Name

the program ?? ?? ??

screen Screen variable theScreen

prompt for hrs and rate String constant none

number hrs worked double variable hoursWorked

hourly pay rate double variable hourlyRate

keyboard Keyboard variable theKeyboard

wages double variable wages

descriptive label String constant none

Page 8: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Operations

Display strings (prompts) on screenRead numbers for hours and rate (restrict to non negatives)Compute wagesDisplay real value (wages) and a string on screen

Page 9: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Algorithm1. Construct theScreen and theKeyboard2. Ask theScreen to display prompt for hours3. Ask theKeyboard to read value and store in

hoursWorked4. Ask theScreen to display prompt for rate5. Ask theKeyboard to read value and store in

hourlyRate6. Compute wages = hoursWorked x

hourlyRate7. Ask theScreen to display wages and

descriptive label

Page 10: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Coding, Testing, Maintenance

Note Figure 2.1CodeSample runs

MaintenanceEnhance to include overtime wagesDisplay output using $999.99 style format

Note revision Figure 2.2

Page 11: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

2.2 Types, Variables, and Constants

Types of objects must be declared before they are usedDeclaration of variables requires a certain syntaxIn declaration, the name of a variable is associated with a type

Page 12: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Types void

denotes the absence of any type String [ ]

in general, a sequence of characters Keyboard, Screen

associated to the Input and Output (I/O) devices normally used

doubleassociated with real (numbers with fractions) values

Page 13: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Primitive Types byte, short, int, and long

for integer values of various sizes float and double

for real (rational) values of differing accuracy

booleanfor logical (true/false) values

charfor individual characters

Page 14: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Reference TypesBuilt of other types

Example: String, Screen, KeyboardAlso considered “class types” Reference types

begin with uppercase letternot known to Java compiler, must be explained

Contrast primitive types begin with lower case letterare known to Java compiler

Page 15: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Literals – Examples Integers

4 19 -5 0 1000Doubles

3.14 0.0 -16.123Strings

"Hi Mom" "Enter the number : "Character

'A' 'X' '9' '$' '\n'Boolean

true false

Page 16: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

IdentifiersNames given to variables, objects, methodsMust not be a Java keyword

See Appendix B for list of keywordsMay begin with a letter or the underline character _Followed by any number of characters, digits, or _ (note, no blanks)Identifiers should be well chosen

use complete words (even phrases)this helps program documentation

Page 17: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Conventions for Identifiers

ClassesNames given in lowercase except for first letter of each word in the name

VariablesSame as classes, except first letter is lowercase

ConstantsAll caps with _ between words

Methodslike variable names but followed by parentheses

Page 18: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Declaration StatementsPurpose is to provide compiler with meaning of an identifierAccomplished in declaration statementSome declarations (classes and methods) are provided and must be importedimport ann.easyio.*;Variables to store values must be declared

they can be initialized at time of declarationinitialized with a literal or even with keyboard inputif not explicitly initialized, the default initial value is zero

Page 19: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Values Held by Variables

Primitive-type variablesstore a value of the specified type (int, double)

Reference-type variables store an address of memory location where value is storedthought of as a handle for the object that actually stores the values

Page 20: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Variable Declaration Syntax

Syntax:type variable_name;ortype variable_name = expression;Note

type must be known to the compiler variable_name must be a valid identifier expression is evaluated and assigned to variable_name location In the first form, a default value is given (0, false, or null, depending on type)

Page 21: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

ConstantsValue of object cannot be changed

for oft used math values such as PIfor values which will not change for a given programimprove readability of programfacilitate program maintenance

Declaration syntax:final type CONSTANT_NAME = expression;

final is a Java keyword, makes a constant type must be known by compiler CONSTANT_NAME must be valid identifier expression evaluated should be placed at beginning of class or method

Page 22: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Part of the Picture: Data

RepresentationHow literals of the primitive types are represented and stored in memory.

Page 23: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Representing IntegersBinary digits used to represent base 10 numbers58ten = 111010two

The 1s and 0s are stored as binary digits in specified number of bits (32 shown in text)

Negative numbers often stored in “two's complement” representation

Invert values, switch 1s for 0s and 0s for 1sLeading bit specifies the sign (0 for +, 1 for -)

If a number is too large for the number of bits allocated, the condition is overflow

Page 24: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Representing RealsConsider22.62510 = 10110.1012= 1.01101012 x 24

The 1.0110101 is stored as the “mantissa”The 4 is stored as the exponent or “characteristic”

IEEE formatLeftmost bit is sign for mantissa8 bits for exponentRightmost 23 bits store mantissa

Problems includeOverflow – number too large for exponentUnderflow – number too small for exponentRoundoff error – conversion between decimal & binary

Page 25: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Representing Characters

A numeric code is assigned to each symbol to be representedASCII uses 8 bits

Very common for programming languagesLimited to 128 characters

Unicode uses 16 bits newer, used by JavaAllows 65,536 different symbols

Page 26: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Representing Booleans

Only two possible values true and false

Only need two possible numbers, 0 and 1Single bit is all that is needed

Page 27: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

2.3 Some Basic Program Features

Comments and documentationClassesImporting packagesUsing Methods

Page 28: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Comments and Opening Documentation

Opening documentation should include:description of what program doesinput needed, resulting outputspecial techniques, algorithms usedinstructions for use of programName of programmer, date, modification history

Opening documentation is multiline between /* */ character pairs

Inline commentsfollowing // double slashes

Comments ignored by compiler

Page 29: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

ClassesClasses built for real world objects that cannot be represented using available typesA class is an “extension” of JavaDefinition of class: “a group or category of things that have a set of attributes in common.”In programming: a pattern, blueprint, or template for modeling real world objects which have similar attributes

Page 30: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Class DeclarationSyntax:class className extends existingClassName{ // Attributes (variables & constants)// and behaviors (methods) }Where

className is the name of a new reference type existingClassName is any class name known to the compiler

{ and } mark the boundaries of the declaration

Page 31: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Purpose of Class Declaration

Creates a new type that the compiler can use to create objectsThis new type inherits all attributes and behaviors of existingClassNameNote:

Object is often used for existingClassNamein this case the extends object may be omitted

Page 32: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Importing PackagesRelated classes grouped together into a container called a “package”

program specifies where to find a desired classFully-qualified namepackage_name1.ClassName orpackage_name1.package_name2.ClassNameBy using the import package_name1 the prefixes using the dot notation can be omitted Syntaximport package_name.* ; orimport package_name.ClassName;

where ClassName is any class stored with package_name

Page 33: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Using MethodsCall, invoke, or send a message to the method of an existing object theScreen.print(" … ");

theScreen is the object print( ) is the method being called

Syntax of the call:the name of the objectthe dot ‘.’the name of the methodarguments

Page 34: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Value Returning Methods

Some methods return a valueProgrammer must also do something with the value to be returned

assign the value to a variablevariable_name = objectName.methodName(arguments);

send the value to another method as the parameter

Page 35: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

2.4 Java Documentation – API

Note the sample programs so far …For several tasks, we found a Java method to solve itOther times the programmer writes the class and methods required

Java designers have provided over 1600 classes

Called the Java Application Programmer's Interface or APIEach class provides variety of useful methodsClasses grouped into packages

Page 36: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

API DocumentationFinding needed package or class Hypertext-based documentation system, accessible on World Wide WebFirst page of web site has 3 frames

Alphabetical list of packagesAlphabetical list of classesA “main” frame that initially lists the Java packages

Page 37: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Web Based Documentation

Clicking on the name of the package in the “main” frame produces a list of the classes in that packageClick on name of a class displays information about that class

List of fields (variables, constants)List of methods for the class

Click on a method for a detailed description of the methods

Page 38: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

2.5 Introduction to GUIs: A GUI Greeter

Problem ScenarioWrite a program with graphical user interface that

displays a window with prompt for namebox to enter nameOK and Cancel buttonsUser enters name, clicks OKSecond window gives greeting, uses name, displays a button for terminating program

Page 39: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

ObjectsDescription of Object

Type Kind Name

the program ?? ?? GUIgreeter

window for prompt input dialog

prompt for user’s name

String constant

window for greeting message dialog

user’s name String varying name

personalized greeting

String varying

Page 40: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

OperationsDisplay a window containing a prompt and a text boxRead a String from the window's text boxHide the windowDisplay second window with personalized greetingTerminate program

Page 41: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Coding in Java

Note source code in Figure 2.3Application GUIGreeterNote run of program

Window for prompt and inputWindow for Greeting

Note improved version, Figure 2.4

Page 42: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Input DialogInput dialogs are GUI widgets

used to get text input from userExampleshowInputDialog(prompt);

prompt can be a stringa graphic imageanother Java Object

Page 43: Some Java Fundamentals - University of New Mexicomaccabe/classes/152/SPR05/Chapt02.pdf2.4 Java Documentation – API Note the sample programs so far … For several tasks, we found

Message Dialog

A GUI widget for displaying informationExample

showMessageDialog(null, message, title, messageKind);

Message kindcan be: error, information, warning, question, or plainused by interface manager to display proper icon