Java Fundamentals
Java Fundamentals
Chapter 2
Chapter Contents
Chapter Objectives 2.1 Example: A Payroll Program 2.2 Types, Variables, and Constants Part of the Picture: Data Representation 2.3 Some Basic Program Features 2.4 Java Documentation 2.5 Introduction to GUIs: A GUI Greeter
Chapter Objectives
Observe
literals Explain Java syntax rules Contrast primitive types and reference types Study variables and constants Investigate internal representation of primitive types
Chapter Objectives
Observe
classes Discover need for import statements Note how to use methods Study Java API organization Look at designing and building simple GUI applications
Employees are paid a fixed hourly rate They can work any number of hours No overtime is paid
Describe behavior Identify objects Identify operations Organize objects & operations in an algorithm
Behavior
Display
hours
values via keyboard Compute wages Display calculations with descriptive label
Objects
Description of Object
the program screen prompt for hrs & rate
Type
??
Screen String double double Keyboard
Kind
?? variable constant
Name
??
theScreen
none
hoursWorked hourlyRate theKeyboard
variable
variable variable
wages
descriptive label
double
String
variable
constant
wages
none
Operations
Display
strings (prompts) on screen Read numbers for hours and rate (restrict to non negatives) Compute wages Display real value (wages) and a string on screen
Algorithm
1. 2. 3. 4. 5. 6. 7.
Construct theScreen and theKeyboard objects Ask theScreen to display prompt for hours Ask theKeyboard to read value and store in
hoursWorked Ask theScreen to display prompt for rate Ask theKeyboard to read value and store in hourlyRate Compute wages = hoursWorked x hourlyRate Ask theScreen to display wages and
descriptive label
Figure 2.1
runs
Code Sample
Maintenance
Enhance
Declaration
of variables requires a certain syntax declaration, the name of a variable is associated with a type
In
Types
void
String [ ]
Keyboard, Screen
double
Primitive Types
for integer values of various sizes for real (rational) values of differing accuracy for logical (true/false) values
boolean
char
Reference Types
begin with uppercase letter not known to Java compiler, must be explained
begin with lower case letter are known to Java compiler
Literals Examples
Integers
Doubles
Strings
Character
Boolean
true, false
Identifiers
May begin with a letter or the underline character _ Followed by any number of characters, digits, or _ (note, no blanks) Identifiers should be well chosen
Classes
Names given in lowercase except for first letter of each word in the name
Same as classes, except first letter is lowercase All caps with _ between words like variable names but followed by parentheses
Variables
Constants
Methods
Declaration Statements
Purpose is to provide compiler with meaning of an identifier Accomplished in declaration statement Some declarations (classes and methods) are provided and must be imported
import ann.easyio.*;
they can be initialized at time of declaration initialized with a literal or even with keyboard input if not explicitly initialized, the default initial value is zero
variables
Reference-type
store
variables
an address of memory location where value is stored thought of as a handle for the object that actually stores the values
Syntax:
type variable_name;
or
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)
Constants
for oft used math values such as PI for values which will not change for a given program improve readability of program facilitate 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
Representing Integers
The 1s and 0s are stored as binary digits in specified number of bits (32 shown in text)
All opposite values, switch 1s for 0s and 0s for 1s Leading bit specifies the sign (0 for +, 1 for -)
If a number is too large for the number of bits allocated, the condition is overflow
Representing Reals
The 1.0110101 is stored as the "mantissa" The 4 is stored as the exponent or "characteristic"
IEEE format
Leftmost bit is sign for mantissa 8 bits for exponent Rightmost 23 bits store mantissa
Overflow number too large for exponent Underflow number too small for exponent Roundoff error conversion between decimal & binary
Problems include
Representing Characters
A
uses 16 bits
Representing Booleans
Only Only
true
need two possible numbers, 0 and 1 Single bit is all that is needed
and documentation
description of what program does input needed, resulting output special techniques, algorithms used instructions for use of program Name of programmer, date, modification history
between /* */ character pairs
Inline comments
Classes
Classes built for real world objects that cannot be represented using available types A class is an "extension" of Java Definition 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
Class Declaration
Syntax:
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
Creates a new type that the compiler can use to create objects This new type inherits all attributes and behaviors of existingClassName Note:
Object is often used for existingClassName in this case the extends object may be omitted
Importing Packages
Fully-qualified name
package_name1.ClassName or package_name1.package_name2.ClassName By using the import package_name1 the prefixes using the dot notation can be omitted Syntax import package_name.* ; or import package_name.ClassName; where ClassName is any class stored with package_name
Using Methods
Call,
invoke, or send a message to the method of an existing object theScreen.print(" "); theScreen is the object print ( ) is the method being called of the call
of the object
the any name the
Syntax
dot .
methods return a value Programmer must also do something with the value to be returned
assign send
variable_name = objectName.methodName(arguments);
For several tasks, we found a Java method to solve it Other times the programmer writes the class and methods required
Called the Java Application Programmer's Interface or API Each class provides variety of useful methods Classes grouped into packages
API Documentation
Finding
needed package or class Hypertext-based documentation system, accessible on World Wide Web First page of web site has 3 frames
Alphabetical
list of packages Alphabetical list of classes A "main" frame that initially lists the Java packages
Clicking on the name of the package in the "main" frame produces a list of the classes in that package Click on name of a class displays information about that class
displays a window with prompt for name box to enter name OK and Cancel buttons User enters name, clicks OK Second window gives greeting, uses name, displays a button for terminating program
Objects
Description of Problem's Objects
the program window for prompt prompt for user's name window to display greeting user's name a personalized greeting inputdialog String message -dialog String String varying varying name constant
Type
Kind
Name
GUIGreeter
Operations
Display
a window containing a prompt and a text box Read a String from the window's text box Hide the window Display second window with personalized greeting Terminate program
Coding in Java
Note
Input Dialog
Input
used
Message Dialog
A
Message
can
kind
be: error, information, warning, question, or plain used by interface manager to display proper icon