Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Programming and the Java Language

Similar presentations


Presentation on theme: "Introduction to Programming and the Java Language"— Presentation transcript:

1 Introduction to Programming and the Java Language
Chapter 1 Introduction to Programming and the Java Language

2 Topics Basic Computer Concepts Data Representation
Introduction to Programming Languages Introduction to Programming Programming Basics Program Design with Pseudocode Developing a Java Application

3 Basic Computer Concepts
Hardware Central Processing Unit Memory and Storage Devices Operating Systems Application Software Computer Networks and the Internet

4 Hardware A typical computer consists of:
CPU: executes the instructions of the program Hard disk: stores instructions and data so program can be loaded into memory and executed Memory unit: stores the program instructions and data while executing Keyboard and mouse: used for data input Monitor: used to display output from a program Other accessories

5 Central Processing Unit (CPU)
Arithmetic Logic Unit: performs integer arithmetic and logical operations Floating-point Unit: performs floating-point operations Hardware registers: store data and memory addresses Instruction pointer: keeps track of current instruction to execute Examples: Intel Pentium 4, Sun Microsystems SPARC, IBM PowerPC

6 Processor Instruction Set
Move data from one location to another Perform a calculation Change the sequence of instructions to execute (the flow of control)

7 CPU Speed Rated in MHz or GHz In one clock cycle, a CPU
fetches an instruction from memory, decodes the instruction, or executes the instruction Pipelining allows overlap of operations to improve performance 2-Ghz CPU can execute 2 billion instructions per second

8 Memory or Storage Devices
Memory consists of cells that hold one bit. A bit's value can be 0 or 1 A byte is 8 binary digits (bits) Storage capacity is expressed as: Kilobytes (1,024 bytes) Megabytes (1,048,576 bytes) Gigabytes (1,073,741,824 bytes)

9 Operating System Software
boots when computer is turned on and runs continuously Controls the peripheral devices (disks, keyboard, mouse, etc.) Supports multitasking (multiple programs executing simultaneously) Allocates memory to each program Prevents one program from damaging another program Example: Microsoft Windows, Linux

10 Application Software Written to perform specific tasks
Runs "on top of" operating system Examples: word processor, spreadsheet, database management system, games, Internet browser, etc.

11 Computer Networks Networks connect two or more computers so they can share files or devices Local Area Network (LAN) : computers located geographically close to one another Servers provide services, such as: access to database, downloading of files, delivery Clients use these services. Most desktop computers are clients.

12 The Internet Evolved from ARPANET, a military research project
Web servers deliver Internet content (Web pages) to clients via a browser. Web pages identified using a URL (Uniform Resource Locator) Domain Name Servers (DNS) translate URL to Internet Protocol (IP) address, which identifies specific computer on the Internet

13 Data Representation Binary Numbers Hexadecimal Numbers
Expressed in base 2 system (two values are 0 and 1) Hexadecimal Numbers Base-16 system used as shorthand for binary numbers Representing Characters with the Unicode Character Set

14 Binary Equivalents of Decimal Numbers
Decimal Binary Equivalent

15 Powers of 2 Decimal Decimal 20 1 28 256 21 2 29 512 22 4 210 1024

16 Decimal (base 10) numbers
A decimal number can be represented as the sum of powers of 10 (the base) with coefficients in the base 10 alphabet (0 - 9) For example: 2485 = 2485 = 2 * * * * 1 2485 = 2 * * * * 100

17 Converting From Decimal to Binary
Just as a decimal number can be represented as a sum of powers of 10 (the base) with coefficients in the base 10 alphabet (0 to 9), A decimal number also can be represented as the sum of powers of 2 (the base of the binary system) with coefficients in the base 2 alphabet (0 and 1) So we need an algorithm to do that

18 Converting From Decimal to Binary
Find the largest power of 2 that is smaller than or equal to the decimal number Subtract that number from the decimal number Insert 1 in binary number for position equivalent to that power of 2 Repeat 1 - 3, until you reach 0

19 Example: convert 359 to binary
Largest power of 2 that is smaller than 359 is 256 (28) = 103 so 359 = 28* Largest power of 2 that is smaller than 103 is 64 (26) = 39 so 359 = 28*1 + 26*1 + 39 (continued on next slide)

20 Example: convert 359 to binary
Largest power of 2 that is smaller than 39 is 32 (25) = 7 so 359 = 28*1 + 26*1 + 25*1 + 7 Largest power of 2 that is smaller than 7 is 4 (22) 7 - 4 = 3 so 359 = 28*1 + 26*1 + 25*1 + 22*1 + 3 (continued on next slide)

21 Example: convert 359 to binary
Largest power of 2 that is smaller than 3 is 2 (21) 3 - 2 = 1 so 359 = 28*1 + 26*1 + 25*1 + 22*1 + 21*1 + 1 Largest power of 2 that is smaller than or equal to 1 is 1 (20) 1 - 1 = 0, so we are finished

22 Our results Finally, insert missing powers of 2 with coefficient 0.
Thus, 359 = 28*1 + 27*0 + 26*1 + 25*1 + 24*0 + 23*0 + 22*1 + 21*1 + 20*1 Removing powers of 2, we get: Or

23 Hexadecimal Numbers Base-16 number system
Uses digits and letters A - F One hexadecimal digit can express values from 0 to 15 For example: C represents 12 Thus, one hexadecimal digit can represent 4 bits

24 Hexadecimal - Binary Equivalents
Hex Binary Hex Binary A B C D E F

25 Examples Binary number: 0001 1010 1111 1001 Hex equivalent: 1 A F 9
Hex equivalent: B B E

26 The Unicode Character Set
Each character stored as 16-bits Maximum number of characters that can be represented: 65,536 (216) ASCII character set (used by many programming languages) stores each character as 7 bits (maximum number of characters is 128). For compatibility, first 128 characters of Unicode set represent the ASCII characters

27 Some Unicode Characters
Unicode Character Decimal Value * A B a b }

28 Programming Languages
Machine language Assembly language High-level languages

29 Machine & Assembly Languages
Machine language Written using CPU instruction set Difficult to write, and not portable Assembly language Written using mnemonics for instructions and symbolic names for variables Assembler converts code to machine language Easier to write, but still not portable

30 High-Level Languages Examples: Fortran, Perl, COBOL, C++, Java
Highly symbolic Portable among CPU architectures Languages can be designed for specific uses: Perl: Internet applications Fortran: scientific applications COBOL: business applications

31 High-Level Languages Compiled Interpreted
Compiler converts source code (instructions and data) into machine language, then program is executed Interpreted Interpreter converts instructions into machine language at run time as instructions are executed Usually executes more slowly than compiled program

32 Java Combination of compiler and interpreter
Compiler converts source code into byte codes (an instruction set for a virtual, machine-independent processor) At run time, the Java Virtual Machine (JVM) interprets the byte codes and converts them into the machine language on which the program is running.

33 Object-oriented Programming (OOP)
Class tool for encapsulating data and operations (methods) into one package defines a template or model for creating and manipulating objects Objects data created using the class and its methods an object is an instance of the class creating an object is instantiation

34 OOP Advantage: Reuse Well-written classes can be reused in new applications Shortens development time because programmers don't need to write new code Programs are more robust because the class code is already tested

35 The Java Language Created by Sun Microsystems in 1995
Syntax based on C++ Object-oriented Support for Internet applications Extensive library of prewritten classes Portability among platforms Built-in networking

36 Java Programs Applets Servlets Applications
Small programs designed to add interactivity to Web sites Downloaded with the Web page and launched by the Internet browser Servlets Run by Web server on the server Typically generate Web content Applications Programs that run standalone on a client

37 An Introduction to Programming
Programming Basics Program Design with Pseudocode Developing a Java Application

38 Programming Basics Programming is translating a problem into ordered steps consisting of operations a computer can perform: Input Calculations Comparisons of values Moving data Output The order of execution of instructions is called flow of control

39 Program Design with Pseudocode
Pronounced sue-dough-code English-like language for specifying the design of a program Programmer can concentrate on design of program without worrying about Java language rules (syntax) Then convert pseudocode into Java code

40 Four Types of Flow of Control
Sequential Processing Execute instructions in order Method Call Jump to code in method, then return Selection Choose code to execute based on data value Looping or Iteration Repeat operations for multiple data values

41 Sequential Processing
The pseudocode for calculating the sum of two numbers would look like this: read first number read second number set total to (first number second number) output total

42 Method Call Calling the method executes the method
Methods can take arguments (data to use) and return values Here is pseudocode for calculating the square root of an integer:   read an integer call the square root method, with integer as argument output the square root

43 Selection The pseudocode for determining if a number is positive or negative is: read a number if the number is greater than or equal to 0 write "Number is positive." else write "Number is negative."

44 Looping The pseudocode for finding the sum of a set of numbers is:
set total to 0 read a number while there was a number to read, add number to total read the next number write total

45 Developing a Java Application
Write the source code Using an Integrated Development Environment (IDE) or text editor Save in a .java file Compile the source code: javac ClassName.java Creates .class file Execute the application: java ClassName Run by the Java Virtual Machine

46 A First Application 1 // First program in Java 2 // FirstProgram.java
3 4 public class FirstProgram 5 { 6 public static void main( String [] args ) 7 { System.out.println( "Programming is not " " a spectator sport!" ); System.exit( 0 ); 11 } 12 }

47 Java is case-sensitive
Java is case-sensitive. The class name and the source filename must match exactly, including capitalization.

48 Program Errors Compiler errors Run-time errors Logic errors
Found by the compiler. Usually caused by incorrect syntax or spelling Run-time errors Reported by the JVM Usually caused by incorrect use of prewritten classes or invalid data Logic errors Found by testing the program Incorrect program design or incorrect execution of the design

49 Programming Building Blocks — Java Basics
Chapter 2 Programming Building Blocks — Java Basics

50 Java Basics Java Application Structure
Data Types, Variables, and Constants Expressions and Arithmetic Operators

51 Java Application Structure
All programs consist of at least one class. See Example 2.1 SkeletonApplication for standard form of Java application Java source code file must have same name as class with .java extension.

52 Identifiers - symbolic names
Identifiers are used to name classes, variables, and methods Identifier Rules: Must start with a "Java letter" A - Z, a - z, _, $, and Unicode letters Can contain essentially any number of Java letters and digits, but no spaces Case sensitive!! Number1 and number1 are different! Cannot be keywords or reserved words See Appendix A

53 Program Building Blocks
The Statement Performs some action Terminates with a semicolon (;) Can span multiple lines

54 Building Blocks - The Block
0, 1, or more statements Begins and ends with curly braces { } Can be used anywhere a statement is allowed.

55 Building Blocks - White Space
Space, tab, newline are white space characters At least one white space character is required between a keyword and identifier Any amount of white space characters are permitted between identifiers, keywords, operators, and literals

56 To increase readability of your code, surround operators and operands with white space and skip lines between logical sections of program

57 Building Blocks - Comments
Comments explain the program to yourself and others Block comments Can span several lines Begin with /* End with */ Compiler ignores all text between /* and */ Line comments Start with // Compiler ignores text from // to end of line

58 Include a block comment at the beginning of each source file
identify the author of the program briefly describe the function of the program

59 Data Types, Variables, and Constants
Declaring Variables Primitive Data Types Initial Values and Literals String Literals and Escape Sequences Constants

60 Data Types For all data, assign a name (identifier) and a data type
Data type tells compiler: How much memory to allocate Format in which to store data Types of operations you will perform on data Compiler monitors use of data Java is a "strongly typed" language Java "primitive data types" byte, short, int, long, float, double, char, boolean

61 Declaring Variables Variables hold one value at a time, but that value can change Syntax: dataType identifier; or dataType identifier1, identifier2, …; Naming convention for variable names: first letter is lowercase embedded words begin with uppercase letter

62 Don't skimp on characters, but avoid extremely long names
Names of variables should be meaningful and reflect the data they will store This makes the logic of the program clearer Don't skimp on characters, but avoid extremely long names Avoid names similar to Java keywords

63 Integer Types - Whole Numbers
Type Size Minimum Value Maximum Value in Bytes byte short , ,767 int , 147, 483, , 147, 483, 647 long ,223,372,036,854,775, ,223,372,036,854,775,807 Example declarations: int testGrade; int numPlayers, highScore, diceRoll; short xCoordinate, yCoordinate; byte ageInYears; long cityPopulation;

64 Floating-Point Data Types
Numbers with fractional parts Type Size Minimum Value Maximum Value in Bytes float E E38 double E E308 Example declarations: float salesTax; double interestRate; double paycheck, sumSalaries;

65 char Data Type One Unicode character (16 bits - 2 bytes)
Type Size Minimum Value Maximum Value in Bytes char character character encoded as encoded as FFFF Example declarations: char finalGrade; char newline, tab, doubleQuotes;

66 boolean Data Type Two values only:
true false Used for decision making or as "flag" variables Example declarations: boolean isEmpty; boolean passed, failed;

67 Assigning Values to Variables
Assignment operator = Value on the right of the operator is assigned to the variable on the left Value on the right can be a literal (text representing a specific value), another variable, or an expression (explained later) Syntax: dataType variableName = initialValue; Or dataType variable1 = initialValue1, variable2 = initialValue2, …;

68 Literals int, short, byte
Optional initial sign (+ or -) followed by digits 0 – 9 in any combination. long Optional initial sign (+ or -) followed by digits 0–9 in any combination, terminated with an L or l. ***Use the capital L because the lowercase l can be confused with the number 1.

69 Floating-Point Literals
Optional initial sign (+ or -) followed by a floating-point number in fixed or scientific format, terminated by an F or f. double Optional initial sign (+ or -) followed by a floating-point number in fixed or scientific format.

70 Commas, dollar signs, and percent signs (%) cannot be used in integer or floating-point literals

71 char and boolean Literals
Any printable character enclosed in single quotes A decimal value from 0 – 65535 '\m' , where \m is an escape sequence. For example, '\n' represents a newline, and '\t' represents a tab character. boolean true or false See Example 2.2 Variables.java

72 Assigning the Values of Other Variables
Syntax: dataType variable2 = variable1; Rules: 1. variable1 needs to be defined before this statement appears in the source code 2. variable1 and variable2 need to be compatible data types; in other words, the precision of variable1 must be lower than or equal to that of variable2.

73 Compatible Data Types Any type in right column can be assigned to type in left column: Data Type Compatible Data Types byte byte short byte, short int byte, short, int, char long byte, short, int, long, char float float, byte, short, int, long, char double float, double, byte, short, int, long, char boolean boolean char char

74 Sample Assignments This is a valid assignment: float salesTax = .05f;
double taxRate = salesTax; This is invalid because the float data type is lower in precision than the double data type: double taxRate = .05; float salesTax = taxRate;

75 String Literals String is actually a class, not a basic data type; String variables are objects String literal: text contained within double quotes. Example of String literals: "Hello" "Hello world" "The value of x is "

76 String Concatenation Operator (+)
Combines String literals with other data types for printing Example: String hello = "Hello"; String there = "there"; String greeting = hello + ' ' + there; System.out.println( greeting ); Output is: Hello there

77 Common Error Trap String literals must start and end on the same line. This statement: System.out.println( "Never pass a water fountain without taking a drink" ); generates these compiler errors: unclosed string literal ')' expected Break long Strings into shorter Strings and use the concatenation operator: System.out.println( "Never pass a water fountain" + " without taking a drink" );

78 Escape Sequences To include a special character in a String, use an escape sequence Character Escape Sequence Newline \n Tab \t Double quotes \" Single quote \' Backslash \\ Backspace \b Carriage return \r Form feed \f See Example 2.3 Literals.java

79 Declare a variable only once
Once a variable is declared, its data type cannot be changed. These statements: double twoCents; double twoCents = .02; generate this compiler error: twoCents is already defined

80 Once a variable is declared, its data type cannot be changed.
These statements: double cashInHand; int cashInHand; generate this compiler error: cashInHand is already defined

81 Constants Value cannot change during program execution Syntax:
final dataType constantIdentifier = assignedValue; Note: assigning a value when the constant is declared is optional. But a value must be assigned before the constant is used. See Example 2.4 Constants.java

82 Use all capital letters for constants and separate words with an underscore:
Example: final double TAX_RATE = .05; Declare constants at the top of the program so their values can easily be seen Declare as a constant any data that should not change during program execution

83 Expressions and Arithmetic Operators
The Assignment Operator and Expressions Arithmetic Operators Operator Precedence Integer Division and Modulus Division by Zero Mixed-Type Arithmetic and Type Casting Shortcut Operators

84 Assignment Operator Syntax: target = expression;
expression: operators and operands that evaluate to a single value --value is then assigned to target --target must be a variable (or constant) --value must be compatible with target's data type

85 Examples: The next statement is illegal
int numPlayers = 10; // numPlayers holds 10 numPlayers = 8; // numPlayers now holds 8 int legalAge = 18; int voterAge = legalAge; The next statement is illegal int height = weight * 2; // weight is not defined int weight = 20; and generates the following compiler error: illegal forward reference

86 Arithmetic Operators Operator Operation + addition - subtraction *
multiplication / division % modulus (remainder after division)

87 Example See Example 2.7 SimpleOperators.java

88 Operator Precedence Operator Order of evaluation Operation ( )
left - right parenthesis for explicit grouping * / % multiplication, division, modulus + - addition, subtraction = right - left assignment

89 Example You have 2 quarters, 3 dimes, and 2 nickels.
How many pennies are these coins worth? int pennies = 2 * * * 5; = = 90

90 Another Example Translate x into Java: => x * y 2 // correct 2y
// incorrect! double result = x / 2 * y; => x * y // correct double result = x / ( 2 * y );

91 Integer Division & Modulus
When dividing two integers: the quotient is an integer the remainder is truncated (discarded) To get the remainder, use the modulus operator with the same operands See Example 2.8 DivisionAndModulus.java

92 Division by Zero Integer division by 0: Example: int result = 4 / 0;
No compiler error, but at run time, JVM generates ArithmeticException and program stops executing Floating-point division by 0: If dividend is not 0, the result is Infinity If dividend and divisor are both 0, the result is NaN (not a number) See Example 2.9 DivisionByZero.java

93 Mixed-Type Arithmetic
When performing calculations with operands of different data types: Lower-precision operands are promoted to higher-precision data types, then the operation is performed Promotion is effective only for expression evaluation; not a permanent change Called "implicit type casting" Bottom line: any expression involving a floating-point operand will have a floating-point result.

94 Rules of Promotion Applies the first of these rules that fits:
If either operand is a double, the other operand is converted to a double. If either operand is a float, the other operand is converted to a float. If either operand is a long, the other operand is converted to a long. If either operand is an int, the other operand is promoted to an int If neither operand is a double, float, long, or an int, both operands are promoted to int.

95 Explicit Type Casting Syntax: (dataType)( expression )
Note: parentheses around expression are optional if expression consists of 1 variable Useful for calculating averages See Example 2.10, MixedDataTypes.java

96 Shortcut Operators ++ increment by 1 -- decrement by 1
Example: count++; // count = count + 1; count--; // count = count - 1; Postfix version (var++, var--): use value of var in expression, then increment or decrement. Prefix version (++var, --var): increment or decrement var, then use value in expression See Example 2.11 ShortcutOperators

97 More Shortcut Operators
Example Equivalent += a += 3; a = a + 3; -= a -= 10; a = a - 10; *= a *= 4; a = a * 4; /= a /= 7; a = a / 7; %= a %= 10; a = a % 10;

98 Common Error Trap No spaces are allowed between the arithmetic operator and the equals sign Note that the correct sequence is +=, not =+ Example: add 2 to a // incorrect a =+ 2; // a = +2; assigns 2 to 2 // correct a += 2; // a = a + 2;

99 Operator Precedence Operator Order of evaluation Operation ( )
left - right parenthesis for explicit grouping ++ -- right - left preincrement, predecrement postincrement, postdecrement * / % multiplication, division, modulus + - addition or String concatenation, subtraction = += -= *= /= %= assignment

100 Introduction to Object-Oriented Programming: Using Classes
Chapter 3 Introduction to Object-Oriented Programming: Using Classes

101 Topics Class Basics and Benefits Creating Objects Using Constructors
Calling Methods Using Object References Calling Static Methods and Using Static Class Variables Using Predefined Java Classes

102 Object-Oriented Programming
Classes combine data and the methods (code) to manipulate the data Classes are a template used to create specific objects All Java programs consist of at least one class. Two types of classes Application/Applet classes Service classes

103 Example Student class Student Object: student1
Data: name, year, and grade point average Methods: store/get the value of each piece of data, promote to next year, etc. Student Object: student1 Data: Maria Gonzales, Sophomore, 3.5

104 Some Terminology Object reference: identifier of the object
Instantiating an object: creating an object of a class Instance of the class: the object Methods: the code to manipulate the object data Calling a method: invoking a service for an object.

105 Class Data Instance variables: variables defined in the class and given values in the object Fields: instance variables and static variables (we'll define static later) Members of a class: the class's fields and methods Fields can be: any primitive data type (int, double, etc.) objects

106 Encapsulation Instance variables are usually declared to be private, which means users of the class must reference the data of an object by calling methods of the class. Thus the methods provide a protective shell around the data. We call this encapsulation. Benefit: the class methods can ensure that the object data is always valid.

107 Naming Conventions Class names: start with a capital letter
Object references: start with a lowercase letter In both cases, internal words start with a capital letter Example: class: Student objects: student1, student2

108 Reusability Reuse: class code is already written and tested, so you build a new application faster and it is more reliable Example: A Date class could be used in a calendar program, appointment-scheduling program, online shopping program, etc.

109 How To Reuse A Class You don't need to know how the class is written.
You do need to know the application programming interface (API) of the class. The API is published and tells you: How to create objects What methods are available How to call the methods

110 1. Declare an Object Reference
Syntax: ClassName objectReference; or ClassName objectRef1, objectRef2…; Object reference holds address of object Example: Date d1;

111 2. Instantiate an Object Objects MUST be instantiated before they can be used Call a constructor using new keyword Constructor has same name as class. Syntax: objectReference = new ClassName( arg list ); Arg list (argument list) is comma-separated list of initial values to assign to object data

112 Date Class Constructor Summary
Date Class API constructor: special method that creates an object and assigns initial values to data Date Class Constructor Summary Date( ) creates a Date object with initial month, day, and year values of 1, 1, 2000 Date( int mm, int dd, int yy ) creates a Date object with initial month, day, and year values of mm, dd, and yy

113 Instantiation Examples
Date independenceDay; independenceDay = new Date( 7, 4, 1776 ); Date graduationDate = new Date( 5, 15, 2008 ); Date defaultDate = new Date( ); See Example 3.1 Constructors.java

114 Objects After Instantiation

115 Calling a Method

116 Method Classifications
Accessor methods get… gives values of object data Mutator methods set… change values of object data

117 Date Class Methods Return value Method name and argument list int
getMonth( ) returns the value of month getDay( ) returns the value of day getYear( ) returns the value of year void setMonth( int mm ) sets the value of month to mm setDay( int dd ) sets the value of day to dd setYear( int yy ) sets the value of year to yy

118 The Argument List in an API
Pairs of dataType variableName Specify Order of arguments Data type of each argument Arguments can be: Any expression that evaluates to the specified data type

119 When calling a method, include only expressions in your argument list
When calling a method, include only expressions in your argument list. Including data types in your argument list will cause a compiler error. If the method takes no arguments, remember to include the empty parentheses after the method's name. The parentheses are required even if there are no arguments.

120 Method Return Values Can be a primitive data type, class type, or void
A value-returning method Return value is not void The method call is used in an expression. When the expression is evaluated, the return value of the method replaces the method call. Methods with a void return type Have no value Method call is complete statement (ends with ;)

121 Dot Notation Use when calling method to specify which object's data to use in the method Syntax: objectReference.methodName( arg1, arg2, … ) Note: no data types in method call; values only! See Example 3.2 Methods.java

122 Object Reference vs. Object Data
Object references point to the location of object data. An object can have multiple object references pointing to it. Or an object can have no object references pointing to it. If so, the garbage collector will free the object's memory See Example 3.3 ObjectReferenceAssignment.java

123 Two References to an Object
After Example 3.3 runs, two object references point to the same object

124 null Object References
An object reference can point to no object. In that case, the object reference has the value null Object references have the value null when they have been declared, but have not been used to instantiate an object. Attempting to use a null object reference causes a NullPointerException at run time. See Example 3.4 NullReference.java and Example 3.5 NullReference2.java

125 static Methods Also called class methods
Can be called without instantiating an object Might provide some quick, one-time functionality, for example, popping up a dialog box In method API, keyword static precedes return type

126 Calling static Methods
Use dot syntax with class name instead of object reference Syntax: ClassName.methodName( args ) Example: int absValue = Math.abs( -9 ); abs is a static method of the Math class that returns the absolute value of its argument (here, -9).

127 static Class Variables
Syntax: ClassName.staticVariable Example: Color.BLUE BLUE is a static constant of the Color class.

128 Using Java Predefined Classes
Java Packages The String Class Using System.out Formatting Output The Math Class The Wrapper Classes Dialog Boxes Console Input Using the Scanner Class

129 Java Predefined Classes
Included in the Java SDK are more than 2,000 classes that can be used to add functionality to our programs APIs for Java classes are published on Sun Microsystems Web site: Also see Appendix F

130 Java Packages Classes are grouped in packages according to functionality Package Categories of Classes java.lang Basic functionality common to many programs, such as the String class and Math class java.awt Graphics classes for drawing and using colors javax.swing User-interface components java.text Classes for formatting numeric output java.util The Scanner class and other miscellaneous classes

131 Using a Class From a Package
Classes in java.lang are automatically available to use Classes in other packages need to be "imported" using this syntax: import package.ClassName; or import package.*; Example import java.text.DecimalFormat; import java.text.*;

132 The String Class Represents a sequence of characters
String constructors: String( String str ) allocates a String object with the value of str, which can be String object or a String literal String( ) allocates an empty String

133 String Concatenation Operators
appends a String to another String. At least one operand must be a String += shortcut String concatenation operator See Example 3.6 StringDemo.java

134 The length Method String hello = "Hello"; Example:
int len = hello.length( ); The value of len is 5 Return type Method name and argument list int length( ) returns the number of characters in the String

135 The toUpperCase and toLowercase Methods
Example: String hello = "Hello"; hello = hello.toUpperCase( ); The value of hello is "HELLO" Return type Method name and argument list String toUpperCase( ) returns a copy of the String will all letters uppercase toLowerCase( ) returns a copy of the String will all letters lowercase

136 The indexOf Methods String hello = "Hello";
The index of the first character of a String is 0. Example: String hello = "Hello"; int index = hello.indexOf( 'e' ); The value of index is 1. Return type Method name and argument list int indexOf( String searchString ) returns the index of the first character of searchString or -1 if not found indexOf( char searchChar ) returns the index of the first character of searchChar or -1 if not found

137 The substring Method String hello = "Hello"; Example:
String lo = hello.substring( 3, hello.length( ) ); The value of lo is 'lo' Return type Method name and argument list String substring( int startIndex, int endIndex ) returns a substring of the String object beginning at the character at index startIndex and ending at the character at index ( endIndex – 1 )

138 Specifying a negative start index or a start index past the last character of the String will generate a StringIndexOutOfBoundsException. Specifying a negative end index or an end index greater than the length of the String will also generate a StringIndexOutOfBoundsException

139 Using System.out Example: Return type Method name and argument list
void print( anyDataType argument ) prints argument to the standard output device (by default, the Java console) println( anyDataType argument ) prints argument to the standard output device (Java console) followed by a newline character Example: System.out.print( "The answer is " ); System.out.println( 3 ); output is: The answer is 3

140 The toString Method All classes have a toString method
See Example 3.7 PrintDemo.java Return type Method name and argument list String toString( ) converts the object data to a String for printing

141 Formatting Numeric Output
The NumberFormat Class The DecimalFormat Class Both classes allow you to specify the number of digits to print and add dollar signs and percent signs to your output Both classes are in the java.text package

142 The NumberFormat Class
See Example 3.8 DemoNumberFormat.java Return type Method name and argument list NumberFormat getCurrencyInstance( ) static method that creates a format object for printing numbers as money getPercentInstance( ) static method that creates a format object for printing percentages String format( double number ) returns a formatted String representation of number

143 The DecimalFormat Class
Constructor: Pattern characters: required digit # optional digit, suppress if 0 decimal point , comma separator % multiply by 100 and display a percent sign See Example 3.9 DemoDecimalFormat DecimalFormat( String pattern ) instantiates a DecimalFormat object with the format specified by pattern

144 The Math Class Constants
Two static constants PI - the value of pi E - the base of the natural logarithm Example: System.out.println( Math.PI ); System.out.println( Math.E ); output is:

145 Methods of the Math Class
All methods are static See Examples 3.10 and 3.11 Return type Method name and argument list dataTypeOfArg abs( dataType arg ) returns the absolute value of the argument arg, which can be a double, float, int or long. double log( double a ) returns the natural logarithm (in base e) of its argument. sqrt( double a ) returns the positive square root of a pow( double base, double exp ) returns the value of base raised to the power of exp

146 The Math round Method Rounding rules:
Any factional part < .5 is rounded down Any fractional part .5 and above is rounded up See Example 3.12 MathRounding.java Return type Method name and argument list long round( double a ) returns the closest integer to its argument a

147 The Math min/max Methods
Find smallest of three numbers: int smaller = Math.min( num1, num2 ); int smallest = Math.min( smaller, num3 ); See Example 3.13 MathMinMaxMethods.java Return type Method name and argument list dataTypeOfArgs min( dataType a, dataType b ) returns the smaller of the two arguments. The arguments can be doubles, floats, ints, or longs. max( dataType a, dataType b ) returns the larger of the two arguments. The arguments can be doubles, floats, ints, or longs.

148 The Math random Method Return type Method name and argument list double random( ) returns a random number greater than or equal to 0 and less than 1 Generates a pseudorandom number (appearing to be random, but mathematically calculated) To generate a random integer between a and up to, but not including, b: int randNum = a + (int)( Math.random( ) * ( b - a ) ); See Example 3.14 MathRandomNumber.java

149 The Wrapper Classes "wraps" the value of a primitive data type into an object Useful when methods require an object argument Also useful for converting Strings to an int or double

150 Wrapper Classes Primitive Data Type Wrapper Class double Double float
long Long int Integer short Short byte Byte char Character boolean Boolean

151 Autoboxing and Unboxing
Automatic conversion between a primitive type and a wrapper object when a primitive type is used where an object is expected Integer intObject = 42; Unboxing Automatic conversion between a wrapper object and a primitive data type when a wrapper object is used where a primitive data type is expected int fortyTwo = intObject;

152 Integer and Double Methods
static Integer Methods static Double Methods See Example 3.15 DemoWrapper.java Return value Method Name and argument list int parseInt( String s ) returns the String s as an int Integer valueOf( String s ) returns the String s as an Integer object Return value Method Name and argument list double parseDouble( String s ) returns the String s as a double Double valueOf( String s ) returns the String s as a Double object

153 Using Dialog Boxes JOptionPane class is in the javax.swing package
static methods provided for input and output dialog boxes For input dialog boxes, return value is a String, so numeric input needs to be converted (using parseInt or parseDouble)

154 JOptionPane static Methods
See Examples 3.16 and 3.17 Return value Method name and argument list String showInputDialog( Component parent, Object prompt ) pops up an input dialog box, where prompt asks the user for input. void showMessageDialog( Component parent, Object message ) pops up an output dialog box with message displayed

155 Provide the user with clear prompts for input.
Prompts should use words the user understands and should describe the data requested and any restrictions on valid input values. Example: Enter your first and last name or Enter an integer between 0 and 10

156 Input Using the Scanner Class
Provides methods for reading byte, short, int,long, float, double, and String data types from the Java console Scanner is in the java.util package Scanner parses (separates) input into sequences of characters called tokens. By default, tokens are separated by standard white space characters (tab, space, newline, etc.)

157 A Scanner Constructor Example:
Scanner scan = new Scanner( System.in ); Scanner( InputStream source ) creates a Scanner object for reading from source. If source is System.in, this instantiates a Scanner object for reading from the Java console

158 Scanner next… Methods Return type Method name and argument list
dataType nextDataType( ) returns the next token in the input stream as a dataType. dataType can be byte, int, short, long, float, double, or boolean String next( ) returns the next token in the input stream as a String nextLine( ) returns the remainder of the line as a String

159 Prompting the User Unlike dialog boxes, the next… methods do not prompt the user for an input value Use System.out.print to print the prompt, then call the next… method. Example: Scanner scan = new Scanner( System.in ); System.out.print( "Enter your age > " ); int age = scan.nextInt( ); See Examples 3.18, 3.19

160 End your prompts with an indication that input is expected
Include a trailing space for readability

161 Introduction to Applets and Graphics
Chapter 4 Introduction to Applets and Graphics

162 Topics Applet Structure Executing an Applet
Drawing Shapes with Graphics Methods Using Colors

163 Applets A Java application is a stand-alone program with a main method (like the ones we've seen so far) A Java applet is a program that is intended to transported over the Web and executed using a web browser An applet also can be executed using the appletviewer tool of the Java Software Development Kit An applet doesn't have a main method Instead, there are several special methods that serve specific purposes

164 Applets Executed by a browser or applet viewer
Opens a window, as well as the Java console Applet viewer comes with Java Software Development Kit (SDK)

165 Java Translation & Execution
Java source code Across the Internet using HTML Java bytecode Java compiler Web browser Java interpreter Java interpreter Bytecode compiler Remote computer Local computer Machine code

166 Applet Structure Do not use main method
Two methods called automatically: init method Browser calls init when applet starts Use to initialize variables and objects paint method Browser calls after init and whenever window needs to be redrawn Use to draw to screen

167 Example 4.01 ShellApplet.java
import javax.swing.JApplet; import java.awt.Graphics; public class ShellApplet extends JApplet { // declare variables here public void init( ) // initialize data here } public void paint( Graphics g ) super.paint( g ); // include graphics code here

168 Executing an Applet A Web page tells the browser to run the applet
HTML tags come in pairs, data goes between start and end tags <HTML> </HTML> start and end of HTML code <HEAD> </HEAD> start and end of header <TITLE> </TITLE> text to display in title bar <BODY> </BODY> start and end of page content

169 <Applet> Tag <APPLET> CODE = Classname.class
CODEBASE = directory of class file WIDTH = nnn width of window in pixels HEIGHT = nnn height of window in pixels </APPLET>

170 Minimal HTML File <HTML> <HEAD>
<TITLE>TitleName</TITLE> </HEAD> <BODY> <APPLET CODE="ClassName.class" CODEBASE=. WIDTH=nnn HEIGHT=nnn> </APPLET> </BODY> </HTML>

171 HTML File for FirstApplet
<HEAD> <TITLE>My First Applet</TITLE> </HEAD> <BODY> <APPLET CODE="FirstApplet.class" CODEBASE=. WIDTH=400 HEIGHT=300> </APPLET> </BODY> </HTML>

172 Executing an Applet If HTML file is named FirstApplet.html, you can execute the applet using this command: appletviewer FirstApplet.html Many IDEs automatically create and launch the HTML file for running an applet

173 Applets in jGrasp To run an applet in jGrasp, just click on the “apple” button An applet viewer will automatically be opened

174 The Graphics Class Browser or appletviewer sends a Graphics object to the paint method The Graphics object represents the applet window, current font, and current color Provides methods to draw shapes and text on the window

175 The Graphics Coordinate System

176 Drawing Shapes Let's explore some of the methods of the Graphics class that draw shapes in more detail A shape can be filled or unfilled, depending on which method is invoked The method parameters specify coordinates and sizes Recall that the Java coordinate system has the origin in the top left corner Shapes with curves, like an oval, are usually drawn by specifying the shape’s bounding rectangle An arc can be thought of as a section of an oval

177 Graphics Class Methods
Methods are available for drawing lines, rectangles, ovals, and other shapes, and for setting the current color All methods have a void return type, so method calls are standalone statements draw… methods draw an outlined share fill… methods draw a solid shape

178 Displaying Text g.drawString( "Hello", x, y ); Example:
See Example 4.4 DrawingTextApplet.java Return type Method name and argument list void drawString (String s, int x, int y) displays the String s. The (x, y) coordinate is lower-left corner of first letter.

179 Drawing a Line See Example 4.5 LineDrawingApplet.java
g.drawLine( xStart, yStart, xEnd, yEnd ); See Example 4.5 LineDrawingApplet.java Return type Method name and argument list void drawLine( int xStart, int yStart, int xEnd, int yEnd ) draws a line starting at (xStart, yStart) and ending at (xEnd, yEnd)

180 Drawing a Line page.drawLine (10, 20, 150, 45); or
X Y 10 150 20 45 page.drawLine (10, 20, 150, 45); page.drawLine (150, 45, 10, 20); or

181 Drawing A Rectangle Return type Method name and argument list void
g.drawRect( x, y, width, height ); Return type Method name and argument list void drawRect( int x, int y, int width, int height ) draws an outlined rectangle with (x,y) as the upper-left corner and the width and height specified

182 Drawing a Rectangle X Y 50 20 40 100 page.drawRect (50, 20, 100, 40);

183 Drawing A Solid Rectangle
g.fillRect( x, y, width, height ); Return type Method name and argument list void fillRect( int x, int y, int width, int height ) draws a solid rectangle in the current color with (x,y) as the upper-left corner and the width and height specified

184 Drawing An Oval Return type Method name and argument list void
g.drawOval( x, y, width, height ); Return type Method name and argument list void drawOval( int x, int y, int width, int height ) draws an outlined oval within an invisible bounding rectangle.

185 Drawing an Oval bounding rectangle page.drawOval (175, 20, 50, 80);
X Y 175 20 80 bounding rectangle 50 page.drawOval (175, 20, 50, 80);

186 Drawing A Solid Oval Return type Method name and argument list void
g.fillOval( x, y, width, height ); Return type Method name and argument list void fillOval( int x, int y, int width, int height ) draws a solid oval in the current color inside an invisible bounding rectangle

187 Drawing Squares and Circles
To draw a square, use drawRect or fillRect with equal values for width and height. To draw a circle, use drawOval or fillOval with equal values for width and height

188 Example 4.6 ShapeDrawingApplet.java
public void paint( Graphics g ) { super.paint( g ); g.drawRect( 100, 50, 40, 100 ); // rectangle g.fillRect( 200, 70, 80, 80 ); // solid square g.fillOval( 100, 50, 40, 100 ); // oval inside the rectangle g.drawOval( 100, 200, 100, 40 ); // same-size oval rotated 90 degrees int centerX = 250, centerY = 225; int radius = 25; g.drawOval( centerX - radius, centerY - radius, radius * 2, radius * 2 ); // circle using radius and center }

189

190 When drawing a figure using Graphics methods, specify coordinate values as offsets from a starting (x,y) coordinate. This will make your figure easier to move or resize.

191 Example 4.7 Astronaut.java
import javax.swing.JApplet; import java.awt.Graphics; public class Astronaut extends JApplet { int sX, sY; // starting x and y coordinates public void init( ) sX = 95; sY = 20; }

192 public void paint( Graphics g )
{ super.paint( g ); // helmet g.drawOval( sX + 60, sY, 75, 75 ); g.drawOval( sX + 70, sY + 10, 55, 55 ); // face g.drawOval( sX + 83, sY + 27, 8, 8 ); g.drawOval( sX + 103, sY + 27, 8, 8 ); g.drawLine( sX + 97, sY + 35, sX + 99, sY + 43 ); g.drawLine( sX + 97, sY + 43, sX + 99, sY + 43 ); g.drawOval( sX + 90, sY + 48, 15, 6 ); // neck g.drawRect( sX + 88, sY + 70, 20, 10 ); // torso g.drawRect( sX + 65, sY + 80, 65, 85 );

193 // arms g.drawRect( sX, sY + 80, 65, 20 ); g.drawRect( sX + 130, sY + 80, 65, 20 ); // legs g.drawRect( sX + 70, sY + 165, 20, 80 ); g.drawRect( sX + 105, sY + 165, 20, 80 ); // flag g.drawLine( sX + 195, sY + 80, sX , sY ); g.drawRect( sX + 195, sY, 75, 45 ); g.drawRect( sX + 195, sY, 30, 25 ); // caption g.drawString( "One small step for man…", sX + 25, sY ); }

194

195 Representing Color A black and white picture can be stored using one bit per pixel (0 = white and 1 = black) A colored picture requires more information; there are several techniques for representing colors For example, every color can be represented as a mixture of the three additive primary colors Red, Green, and Blue (RGB system) In Java, each color is represented by three numbers between 0 and 255 that collectively are called an RGB value (one byte per color stored)

196 Using Color Every drawing surface has a background color
The Graphics context has a current foreground color Both can be set explicitly All drawing is done in current color; the current color is in effect until changed The default color is black. To use color, import the Color class from the java.awt package

197 The Color Class A color is defined in a Java program using an object created from the Color class The Color class also contains several static predefined colors, including: Object Color.black Color.blue Color.cyan Color.orange Color.white Color.yellow RGB Value 0, 0, 0 0, 0, 255 0, 255, 255 255, 200, 0 255, 255, 255 255, 255, 0

198 static Color Constants
Color.BLACK Color.GRAY Color.WHITE Color.ORANGE Color.RED Color.YELLOW Color.GREEN Color.PINK Color.BLUE Color.MAGENTA Color.CYAN Color.LIGHT_GRAY Color.DARK_GRAY

199 Setting the Current Color
Example: g.setColor( Color.RED ); Return value Method name and argument list void setColor( Color c) sets the current color to the Color c

200 Custom Colors Colors consist of red, green, and blue components (RGB).
Color constructor: Example: Color green = new Color( 0, 255, 0 ); Color( int rr, int gg, int bb ) creates a color consisting of the red (rr), green (gg), and blue (bb) values specified. rr, gg, and bb must be between 0 and 255

201 AstronautWithColor.java import javax.swing.JApplet;
import javax.swing.JOptionPane; import java.awt.Graphics; import java.awt.Color; public class AstronautWithColor extends JApplet { int sX, sY; Color spacesuit; public void init( ) spacesuit = new Color( 195, 175, 150 ); sX = Integer.parseInt( JOptionPane.showInputDialog ( null, "Enter the starting x position") ); sY = Integer.parseInt( JOptionPane.showInputDialog ( null, "Enter the starting y position") ); }

202 public void paint( Graphics g )
{ super.paint( g ); // helmet g.setColor( spacesuit ); g.fillOval( sX + 60, sY, 75, 75 ); g.setColor( Color.LIGHT_GRAY ); g.fillOval( sX + 70, sY + 10, 55, 55 ); // face g.setColor( Color.DARK_GRAY ); g.drawOval( sX + 83, sY + 27, 8, 8 ); g.drawOval( sX + 103, sY + 27, 8, 8 ); g.drawLine( sX + 97, sY + 35, sX + 99, sY + 43 ); g.drawLine( sX + 97, sY + 43, sX + 99, sY + 43 ); g.drawOval( sX + 90, sY + 48, 15, 6 ); // neck g.fillRect( sX + 88, sY + 70, 20, 10 );

203 // torso g.fillRect( sX + 65, sY + 80, 65, 85 ); // arms g.fillRect( sX, sY + 80, 65, 20 ); g.fillRect( sX + 130, sY + 80, 65, 20 ); // legs g.fillRect( sX + 70, sY + 165, 20, 80 ); g.fillRect( sX + 105, sY + 165, 20, 80 ); // flag g.setColor( Color.BLACK ); g.drawLine( sX + 195, sY + 80, sX , sY ); g.setColor( Color.RED ); g.fillRect( sX + 195, sY, 75, 45 ); g.setColor( Color.BLUE ); g.fillRect( sX + 195, sY, 30, 25 ); // caption g.drawString( "One small step for man...", sX + 25, sY ); }

204

205 Graphics class methods
void drawArc (int x, int y, int width, int height, int startAngle, int arcAngle) void drawLine (int x1, int y1, int x2, int y2) void drawOval (int x, int y, int width, int height) void drawRect (int x, int y, int width, int height) void drawString (String str, int x, int y) void fillArc (int x, int y, int width, int height, int startAngle, int arcAngle) void fillOval (int x, int y, int width, int height) void fillRect (int x, int y, int width, int height) Color getColor( ) void setColor (Color color)

206 Applet Methods In previous examples we've used the paint method of the Applet class to draw on an applet The Applet class has several methods that are invoked automatically at certain points in an applet's life The init method, for instance, is executed only once when the applet is initially loaded The start and stop methods are called when the applet becomes active or inactive The Applet class also contains other methods that generally assist in applet processing

207 Applet class methods void init ( ) void start ( ) void stop ( )
void destroy ( ) URL getCodeBase ( ) URL getDocumentBase ( ) AudioClip getAudioClip (URL url, String name) Image getImage (URL url, String name)

208 Flow of Control Part 1: Selection
Chapter 5 Flow of Control Part 1: Selection

209 Topics Forming Conditions if/else Statements
Comparing Floating-Point Numbers Comparing Objects The equals Method String Comparison Methods The Conditional Operator ( ?: ) The switch Statement

210 Flow of Control Sequential Method calls Selection Looping
Execute instructions in order Method calls Transfer control to method, execute instructions in method, then return with or without a value Selection Execute different instructions depending on data Looping Repeat a set of instructions for different data

211 Equality Operators Used to determine if values of two expressions are equal or not equal Result is true or false Equality operators Type (number of operands) Meaning = = binary is equal to != is not equal to

212 Examples If int variable age holds the value 32:
( age == 32 ) evaluates to true ( age != 32 ) evaluates to false Use the equality operators only with primitive types and object references, not to compare object data!

213 Do not confuse the equality operator (==) with the assignment operator (=).

214 Relational Operators Used to compare the values of two expressions
Result is true or false Relational Operators Type (number of operands) Meaning < binary is less than <= is less than or equal to > is greater than >= is greater than or equal to

215 Example If int variable age holds value 32:
( age < 32 ) evaluates to false ( age <= 32 ) evaluates to true ( age > 32 ) evaluates to false ( age >= 32 ) evaluates to true

216 Operands must be boolean expressions!
Logical Operators Logical Operator Type (number of operands) Meaning ! Unary NOT && Binary AND || OR Operands must be boolean expressions!

217 Logical Operators The NOT operator ( ! ) inverts the value of its operand. If the operand is true, the result will be false; and if the operand is false, the result will be true. The AND operator ( && ) takes two boolean expressions as operands; if both operands are true, the result will be true, otherwise it will be false. The OR operator ( || ) takes two boolean expressions as operands. If both operands are false, the result will be false; otherwise it will be true.

218 For operator precedence, see Appendix B
Truth Table a b !a a && b a || b true false For operator precedence, see Appendix B

219 Short-Circuit Evaluation
For any logical operator, the operands are evaluated left to right If the result of the logical operation can be determined after evaluating the first operand, the second operand is not evaluated. If the first operand of an || is true, the result will be true If the first operand of an && is false, the result will be false See Example 5.1 Logical Operators.java

220 Suppose we have three ints x, y, and z, and we want to test if x is less than both y and z. A common error is to express the condition this incorrect way: x < y && z // compiler error Each operand of a logical operator must be a boolean expression. This is correct: x < y && x < z

221 Simple if Statement Used when program should perform an operation for one set of data, but do nothing for all other data Syntax: if ( condition ) { // true block // executed if condition is true } Curly braces are optional if true block contains only one statement

222 Simple if Flow of Control

223 Indent the true block of the if statement for clarity
Line up the open and closing curly braces under the "i" in if

224 Simple if Example See Example 5.2 PassingGrade.java

225 if /else Used when data falls into two mutually exclusive categories and program should perform different operations for each set Sample uses: If password is correct, welcome user; otherwise, ask for reentry. If person is old enough to vote, issue a voting card; otherwise, refuse the request.

226 if/else Syntax if ( condition ) { // true block } else // false block Again, curly braces are optional for either block that consists of only one statement Note indentation of true and false blocks for readability

227 if/else Flow of Control

228 Example See Example 5.3 Divider.java

229 if/else if Used when data falls into multiple mutually exclusive categories and program should do different operations for each set Ex: Determine letter grade based on numeric grade Determine ticket price (different prices for child, adult, and senior)

230 if/else if Syntax if ( condition 1 ) { // true block for condition 1 }
else if (condition 2 ) // true block for condition 2 else // false block for all conditions

231 if/else if Flow of Control

232 if/else if Example See Example 5.4 LetterGrade.java

233 Finding the Smallest of Three Numbers
read number1 read number2 read number3 if number1 is less than number2 smallest is number1 else smallest is number2 if number3 is less than smallest smallest is number3 See Example 5.5 FindSmallest.java

234 Nested if Statements if statements can be written as part of the true or false block of another if statement. Typically, you nest if statements when more information is required beyond the results of the first if condition The compiler matches any else clause with the most previous if statement that doesn't already have an else clause. You can use curly braces to force a desired if/else pairing.

235 Example if ( x == 2 ) if ( y == x ) System.out.println( "x and y equal 2" ); else System.out.println( "x equals 2," + " but y does not" ); The else clause is paired with the second if , that is: if ( y == x )

236 Another Example if ( x == 2 ) { if ( y == x ) System.out.println( "x and y equal 2" ); } else System.out.println( "x does not equal 2" ); With curly braces added, the else clause is paired with the first if , that is: if ( x == 2 )

237 The "Dangling else" A dangling else is an else clause that cannot be paired with an if condition if ( x == 2 ) if ( y == x ) System.out.println( "x and y equal 2" ); else // paired with ( y == x ) System.out.println( "y does not equal 2" ); else // paired with ( x == 2 ) System.out.println( "x does not equal 2" ); else // no matching if! System.out.println( "x and y are not equal" ); Generates the compiler error: 'else' without 'if'

238 Example 5.6: Generate a Secret Number
First, generate a secret random number between 1 and 10 Then, prompt the user for a guess if guess is not between 1 and 10 print message else if guess equals the secret number print congratulations print the secret number if ( guess is within 3 numbers ) print "You were close" print "You missed by a mile" print "Better luck next time"

239 Testing Techniques Execution Path Testing Black Box Testing
Develop a test plan that includes running the program multiple times with data values that cause all true and false blocks to be executed. Check results against the program specifications Black Box Testing Treat program like a black box (we don't know how the code is written) Develop test data based on program specifications

240 When testing your program, develop input values that execute all possible paths and verify that the logic correctly implements the program specifications.

241 Comparing Objects The equality operator ( == ) compares object references. Example: If d1 and d2 are two Date object references, then ( d1 == d2 ) evaluates to true only if d1 and d2 point to the same object, that is, the same memory location. *** The equality operator does not compare the data (month, day, and year) in those objects.

242 Comparing Object Data To compare object data, use the equals method
Example (with d1 and d2 Date object references): d1.equals( d2 ) returns true if the month, day, and year of d1 equals the month, day, and year of d2. Return type Method name and argument list boolean equals( Object obj ) returns true if the data of the object obj is equal to the data in the object used to call the method

243 Comparing Date Objects
See Example 5.10 ComparingObjects.java

244 Do not use the equality operators (==,
Do not use the equality operators (==, !=) to compare object data; instead, use the equals method.

245 Comparing Strings Strings are objects
Thus to compare two Strings, use the equals method Example: s1 and s2 are Strings s1.equals( s2 ) returns true only if each character in s1 matches the corresponding character in s2 Another methods of the String class also can be used for comparing Strings: equalsIgnoreCase

246 The equalsIgnoreCase Method
Example: String s1 = "Exit", s2 = "exit"; if ( s1.equalsIgnoreCase( s2 ) ) System.exit( 0 ); Return type Method name and argument list boolean equalsIgnoreCase( String str ) compares the value of two Strings, treating uppercase and lowercase characters as equal. Returns true if the Strings are equal; returns false otherwise.

247 The Conditional Operator (?:)
The conditional operator ( ?: ) contributes one of two values to an expression based on the value of the condition. Some uses are handling invalid input outputting similar messages. Syntax: ( condition ? trueExp : falseExp ) If condition is true, trueExp is used in the expression If condition is false, falseExp is used in the expression

248 Equivalent Code See Example 5.12 DoorPrize.java
The following statement stores the absolute value of the integer a into the integer absValue. int absValue = ( a > 0 ? a : -a ); The equivalent statements using if/else are: int absValue; if ( a > 0 ) absValue = a; else absValue = -a; See Example 5.12 DoorPrize.java See Appendix B Operator Precedence

249 The switch Statement Sometimes the switch statement can be used instead of an if/else/if statement for selection. Requirements: we must be comparing the value of a character (char) or integer (byte, short, or int) expression to constants of the same types

250 Syntax of switch switch ( char or integer expression )
{ case constant1: // statement(s); break; // optional case constant2: // statement(s); break; // optional default: // optional statement(s); }

251 Operation of switch The expression is evaluated, then its value is compared to the case constants in order. When a match is found, the statements under that case constant are executed in sequence until either a break statement or the end of the switch block is reached. Once a match is found, if other case constants are encountered before a break statement, then the statements for these case constants are also executed.

252 Some Finer Points of switch
The break statements are optional. Their job is to terminate execution of the switch statement. The default label and its statements, are also optional. They are executed when the value of the expression does not match any of the case constants. The statements under the case constant are also optional, so multiple case constants can be written in sequence if identical operations will be performed for those values.

253 Example: a Simple Calculator
Prompt user for two doubles (num1, num2) and a char (operation), which can be 'a' for addition or 's' for subtraction switch ( operation ) { case 'a': result = num1 + num2; break; case 's': result = num1 - num2; }

254 A Case-Insensitive Calculator
switch ( operation ) { case 'a': case 'A': result = num1 + num2; break; case 's': case 'S': result = num1 - num2; } See Examples 5.13 and 5.14

255 Flow of Control Part 2: Looping
Chapter 6 Flow of Control Part 2: Looping

256 Topics Event-Controlled Loops Using while Looping Techniques
Type-Safe Input Using Scanner Constructing Loop Conditions Testing Techniques for while Loops Event-Controlled Loops Using do/while Count-Controlled Loops Using for Nested Loops

257 The Grocery Cashier A grocery cashier's job is to calculate the total costs of the items in the cart. The cashier starts with a total of $0.00. The cashier scans an item to get its price and adds the price to the total. The cashier scans the next item to get its price and adds the price to the total. When there are no more items to scan, the total is complete. Notice that the cashier is performing the same operations on each item!

258 Looping In computing, we often need to perform the same operations on multiple items. Typically, these tasks follow this pattern: initialize values (set total to 0) process items one at a time (add price to total) report results (report total) The flow of control that programmers use to complete jobs with this pattern is called looping, or repetition.

259 The while Loop The while loop is designed for repeating a set of operations on data items when we don't know how many data items there will be. We will get some signal when we have reached the end of the items to process. (For the grocery cashier, it's the divider bar) The end of data items could be indicated by a special input value called a sentinel value or by reaching the end of a file Receiving the signal is an event; we call this event-controlled looping

260 while Loop Flow of Control

261 while Loop Syntax //initialize variables
while ( boolean expression ) { // process data (loop body) } //process the results **Note: curly braces are optional if only one statement is in the loop body

262 Indent the body of a while loop to clearly illustrate the logic of the program.

263 Operation of the while Loop
If the condition evaluates to true, the loop body is executed, then the condition is re-evaluated. As long as the condition evaluates to true, we continue to repeat the loop body. The loop body must "update the loop condition"; that is, it must perform some operation that eventually will cause the loop condition to evaluate to false Typically, the loop update will be an attempt to read the next input value, in order to detect the sentinel value or the end of the file.

264 Some Definitions iteration loop update loop termination condition
one execution of the loop body loop update One or more statements that could cause the loop condition to evaluate to false (to end the looping) loop termination condition the event that causes the loop condition to evaluate to false

265 The Endless Loop also called an infinite loop
If the loop condition never evaluates to false, the loop body is executed continuously, without end If the loop body has no output, the endless loop makes the computer appear to hang. If the loop body produces output, the endless loop results in that output being repeatedly written without end. Aborting the program will interrupt the endless loop.

266 Pseudocode for the Grocery Cashier
set total to $0.00 reach for first item while item is not the divider bar { get price of item add price to total reach for next item // loop update } // if we get here, the item is the // divider bar output the total price

267 This code causes an endless loop: int i = 0;
Avoid putting a semicolon after the condition of a while loop. Doing so creates an empty loop body and could result in an endless loop. This code causes an endless loop: int i = 0; while ( i < 10 ); // empty loop body { i++; // not in the loop body } The semicolon indicates an empty loop body; i++ is never executed because it is not part of the loop body, so the condition is always true.

268 Sentinel-Controlled while Loop
initialize variables // priming read read the first data item while ( item is not the sentinel value ) { process the item // update read read the next data item } report the results

269 Omitting the update read may result in an endless loop. Example:
System.out.print( "Enter a value > " ); int input = scan.nextInt( ); while ( input != 10 ) // 10 is sentinel value { System.out.println( input ); } If the value entered for input is not 10, this is an endless loop because we never read a new value for input. Thus, the condition always evaluates to true.

270 Omitting the priming read can lead to incorrect results. Example:
int input, count = 0;; while ( input != 10 ) // 10 is sentinel value { System.out.print( "Enter an integer > " ); input = scan.nextInt( ); count++; } System.out.println( "Count is " + count ); If the user enters the values , then the output will be "Count is 3", which is incorrect. We should not process the sentinel value.

271 Example 6.1 EchoUserInput.java -1 is the sentinel value
We read integers from the user until the user enters -1 To process the data, we echo the user input to console

272 Reading from a Text File
initialize variables while ( there is more data in the file ) { read the next data item process the data } report the results

273 Setup for Reading from a File
File class ( java.io package ) constructor A Scanner constructor for reading from a file Example: File inputFile = new File( "input.txt" ); Scanner scan = new Scanner( inputFile ); File ( String pathname ) constructs a File object with the file name pathname Scanner( File file ) creates a Scanner object associated with a file

274 Scanner Class hasNext Method
Use this method to detect the end of the input values Eliminates the need for a priming read because the hasNext method looks ahead for input. An IOException may be generated if we encounter problems reading the file. Java requires us to acknowledge that these exceptions may be generated. One way to do this is to add this clause to the main definition throws IOException See Example 6.2 reading from a text file Return type Method name and argument list boolean hasNext( ) returns true if there is more data to read; returns false when the end of the file is reached

275 Looping Techniques There are standard patterns and techniques for performing these common operations: Accumulation Counting Items Finding an Average Finding Maximum or Minimum Values Animation

276 Accumulation Approach: the running total
We start by initializing a total variable to 0. Each time we read a value, we add it to the total. When we have no more values to read, the total is complete. Note that this is the same pattern used by the grocery cashier.

277 Accumulation Pseudocode
set total to 0 // very important! read a number // priming read while ( number is not the sentinel value ) { add the number to total read the next number // update read } output the total See Example 6.3 Calculator.java

278 Forgetting to initialize the total variable to 0 before beginning the loop will produce incorrect results.

279 Counting Items Approach: the running count
We start by initializing a count variable to 0. Each time we read a value, we check whether that value meets the criteria as something we want to count. If so, we increment the count variable by 1. When we are finishing reading values, the count is complete.

280 Counting Items Pseudocode
set count to 0 // very important!! read input // priming read while ( input is not the sentinel value ) { if ( input is what we want to count ) add 1 to count read the next input // update read } output count See Example 6.4 CountTestScores.java

281 Forgetting to initialize the count variable to 0 before beginning the loop will produce incorrect results.

282 Calculating an Average
Approach: combine accumulation and counting We start by initializing a total variable and count variable to 0. Each time we read an item, we add its value to the total variable and increment the count variable When we have no more items to read, we calculate the average by dividing the total by the count of items.

283 Calculating an Average Pseudocode
set total to 0 set count to 0 read a number while ( number is not the sentinel value ) { add the number to total add 1 to the count read the next number } set average to total / count output the average See Example 6.5 AverageTestScore.java

284 In floating-point division, if the divisor is 0:
Forgetting to check whether the denominator is 0 before performing division is a logic error. In integer division, if the divisor is 0, an ArithmeticException is generated. In floating-point division, if the divisor is 0: If the dividend is also 0, the result is NaN If the dividend is not 0, the result is Infinity

285 Correct Calculation Remember that if we declare total and count as integers, then average will be calculated using integer division, which truncates the remainder. To get a floating-point average, we need to type cast one of the variables (either total or count) to a double or a float to force the division to be performed as floating point. Example: double average = (double) ( total ) / count;

286 Finding Maximum/Minimum Values
Approach: the running maximum or minimum For the maximum (minimum is similar): Read the first item and save its value as the current maximum Each time we read a new value, we compare it to the current maximum. If the new value is greater than the current maximum, we replace the current maximum with the new value. When we have no more items to read, the current maximum is the maximum for all values.

287 Finding Maximum Value Pseudocode for Reading From a File
read a number make that number the maximum while ( there is another number to read ) { read the next number if ( number > maximum ) set maximum to number } output the maximum See Example 6.6

288 Initializing a maximum or a minimum to an arbitrary value, such as 0 or 100, is a logic error and could result in incorrect results. For example, if we initialize the maximum to 0 and all the values read are less than 0, then we will incorrectly report 0 as the maximum. Similarly, if we initialize the minimum to 0 and all the values read are greater than 0, then we will incorrectly report 0 as the minimum.

289 Input Problems What happens if the user does not enter the data type we request? The Scanner next… method generates an InputMismatchException Program is terminated; remaining statements are not executed. See Example 6.9 ReadInteger.java

290 Solving the Input Problem
We can check before we read, that the next token matches our expected input. The Scanner class provides hasNext… methods for doing this. The hasNext… methods return true if the next token can be read as the data type specified.

291 Scanner Class hasNext… Methods
Each method returns true if the next token in the input stream can be read as the data type requested, and false otherwise. Return type Method name and argument list boolean hasNextInt( ) hasNextDouble( ) hasNextFloat( ) hasNextByte( ) hasNextShort( ) hasNextLong( ) hasNextBoolean( ) hasNext( )

292 Reprompting for Valid Input
If the hasNext method returns false, we need to notify the user that the value typed is not valid and reprompt for new input. First we need to flush the invalid input using the nextLine method of the Scanner class. Then we just ignore that input.

293 Scanner nextLine Method
Pseudocode for type-safe input: prompt for input while ( input does not match type requested ) { flush input reprompt } perform read See Example 6.10 TypeSafeReadInteger.java Return type Method name and argument list String nextLine( ) returns the remaining input on the line as a String

294 Constructing Loop Conditions
The loop body is executed as long as the loop condition evaluates to true So if we want to stop executing the loop when the sentinel value is read, the loop condition has to check that the value is NOT the sentinel Thus, the loop continuation condition is the inverse of the loop termination condition.

295 Example: Menu Program Two sentinel values ( 's' or 'S' )
We are inclined to form this **incorrect** condition: while ( option != 'S' || option != 's' ) This causes an endless loop because one of the conditions is always true

296 Constructing a Loop Condition
1. Define the loop termination condition, that is, define the condition that will make the loop stop executing. 2. Create the loop continuation condition – the condition that will keep the loop executing – by applying the Logical NOT operator ( ! ) to the loop termination condition. 3. Simplify the loop continuation condition by applying DeMorgan's Laws, where possible.

297 DeMorgan's Laws (see Chapter 5)
Set of rules to help develop logical expressions that are equivalent NOT( A AND B ) is equivalent to ( NOT A ) OR ( NOT B ) NOT( A OR B ) is equivalent to ( NOT A ) AND ( NOT B )

298 According to DeMorgan's Laws:
!( a && b ) is equivalent to ( !a ) || ( !b ) !( a || b ) !a && !b

299 Negating Expressions expression ! (expression ) a = = b a != b

300 The Menu Condition Revisited
Define the loop termination condition: ( option == 'S' || option == 's' ) Create the loop continuation condition by applying the ! operator:   ! ( option == 'S' || option == 's' ) Simplify by applying DeMorgan's Laws: ( option != 'S' && option != 's' ) This condition is correct! See Example 6.11 CellService.java

301 Do not check for the sentinel value inside a while loop
Do not check for the sentinel value inside a while loop. Let the while loop condition detect the sentinel value. Note in Example 6.11 that no code in the loop checks for 's' or 'S'. Because the while loop condition does the checking, the option variable can never have the value 's' or 'S' inside the loop body. This is true because we use a priming read and an update read.

302 A Compound Loop Condition
Suppose we want to animate the ball so that it rolls diagonally. In this case, we will have two possible events: the ball has passed the horizontal border the ball has passed the vertical border

303 Develop the Loop Condition
1. Loop termination (ball is out of bounds) ( ball.getX( )+ diameter > windowWidth || ball.getY( )+ diameter > windowHeight ) 2. Loop continuation (ball is not out of bounds) ! ( ball.getX( )+ diameter > windowWidth 3. Simplify (ball is in bounds) ( ball.getX( )+ diameter <= windowWidth && ball.getY( )+ diameter <= windowHeight ) See Example 6.12 RollABall3.java

304 Testing Techniques Does the program produce correct results with a set of known input values? Does the program produce correct results if the sentinel value is the first and only input? Does the program deal appropriately with invalid input?

305 Testing Technique 1 Does the program produce correct results with known input? To verify, select input values, calculate by hand, and compare output to hand-calculated values Check boundary values Such as lowest or highest expected values Check "edge" values of if statements For Example, with this if condition: ( age >= 18 ) we should test the program with values 17, 18, and 19

306 Testing Techniques 2 and 3
2. Does the program produce correct results if the sentinel value is the first and only input? Result: the while loop is not executed; will reported results be correct? Test: Enter sentinel value at first prompt 3. Does the program deal appropriately with invalid input? Possible results: an Exception is generated or an incorrect action is performed Test: Enter invalid data

307 The do/while Loop Unlike the while loop, the condition for the do/while loop is evaluated at the end of the loop Thus, do/while loop executes at least once Some uses for a do/while loop: Validate user input Ask if user wants to repeat an operation

308 do/while Syntax //initialize variables do { // body of loop
} while ( condition ); //process the results

309 do/while Flow of Control

310 Example:Validate User Input
Prompt user inside the do/while loop Condition is true if user entered invalid data, so looping continues until user enters valid data. See Example 6.13 ValidateInput.java

311 Do not use an if statement to validate input because it will catch invalid values entered the first time only. A do/while loop will continue to prompt the user until the user enters a valid value.

312 To Repeat an Operation Example code to prompt user to play again. do {
// code to play a game System.out.print( "play again? ") String answer = scan.next( ); } while ( answer.equalsIgnoreCase( "yes" ) );

313 The for Loop Ideal when you know the number of iterations to perform before the loop begins Examples: Find the sum of 5 numbers Find the maximum of 20 numbers Print the odd numbers from 1 to 10

314 The for Loop Syntax Notes:
for ( initialization; loop condition; loop update ) { // loop body } Notes: semicolons separate terms in the loop header no semicolon follows the loop header curly braces are required only if more than one statement is in the loop body

315 for Loop Flow of Control

316 for Loop Flow of Control
The initialization statement is executed (once only). The loop condition is evaluated. If the condition is true, the loop body is executed. The loop update statement is executed, and the loop condition is reevaluated (#2). And so on, until the condition is false.

317 Using a Loop Control Variable
A loop control variable is usually used for counting. We set its initial value in the initialization statement We check its value in the loop condition We increment or decrement its value in the loop update statement

318 Example: Find Sum of 5 Integers
set total to 0 for i = 1 to 5 by 1 { read integer add integer to total } print the total See Example 6.15 Sum5Numbers.java

319 Update Increment Can Be > 1
Print the even numbers from 0 to 20 set output to an empty String for i = 0 to 20 by 2 { append i and a space to output } print the output String See Example 6.16 PrintEven.java

320 Loop Control Variable Scope
When a loop control variable is declared inside the for loop header, it cannot be referenced after the loop for ( int i = 0; i < 3; i++ ) { System.out.println( i ); // ok } System.out.println( i ); // error: i undefined

321 To Reference i After the Loop
int i; // declare i before loop for ( i = 0; i < 3; i++ ) { System.out.println( i ); } System.out.println( i ); // ok

322 Decrementing the Loop Variable
Print a string backwards: set backwards to an empty String read a sentence  for i = ( length of sentence – 1 ) to 0 by –1 { get character at position i append character to backwards } print backwards See Example 6.17 Backwards.java

323 Drawing a Bull's Eye Target
Draw 10 concentric circles All circles have the same center point Each circle has a different diameter To alternate colors (black & red), we use a toggle variable variable alternates between two values We must draw the circles from the largest to the smallest to avoid covering the smaller circles.

324 Pseudocode for Bull's Eye
initialize color to black for diameter = 200 to 20 by –20 { instantiate a circle draw the circle if color is black set color to red else set color to black } See Example Bullseye.java

325 Testing for Loops An important test for for loops is that the starting and ending values of the loop variable are set correctly. For example, to iterate 5 times, use this header: for ( int i = 0; i < 5; i++ ) or this header: for ( int i = 1; i <= 5; i++ )

326 Processing a String (named word)
Forward direction: Correct: for ( int i = 0; i < word.length( ); i++ ) Incorrect: for ( int i = 0; i <= word.length( ); i++ ) Reverse direction: for ( int i = word.length( ) - 1; i >= 0; i-- ) for ( int i = word.length( ); i >= 0; i-- ) for ( int i = word.length( ) - 1; i > 0; i-- )

327 Testing for Loops Test with data that causes for loop to execute 0 times (no iterations). Example: Test Example 6.17 Backwards.java with an empty sentence.

328 Nested Loops Loops can be nested inside other loops; that is, the body of one loop can contain another loop. A while loop can be nested inside another while loop or a for loop can be nested inside another for loop. A for loop can be nested inside a while loop and a while loop can be nested inside a for loop.

329 Example: Grocery Checkout
look for a customer in line while ( there is a customer in line ) { set total to $0.00 reach for first item while item is not the divider bar { add price to total reach for next item } output the total price look for another customer in line }

330 Nested for Loop Execution
Inner loop executes all its iterations for each single iteration of the outer loop Example: how can we print this? 1 1 2 1 2 3

331 Analysis The highest number we print is the same as the line number.
for line = 1 to 5 by 1 { for number = 1 to line by 1 print number and a space } print a new line See Example 6.19 NestedForLoops.java

332 Finding Factors We'll let the user enter positive integers, with a 0 being the sentinel value. For each number, we'll find all its factors; that is, we will find all the integers that are evenly divisible into the number We will not process 1 or the number itself. If a number is evenly divisible by another, the remainder after division will be 0. Thus, the modulus operator (%) will be useful.

333 Finding Factors (con't)
To find all the factors of a number, we can test all integers from 1 up to the number, counting all those whose remainder after division is 0. But: The number 1 is a factor for every number. So we can begin testing at 2. And because 2 is the smallest possible factor, there's no need to test integers higher than number / 2. Thus, our range of integers to test will be from 2 to number / 2.

334 Finding Factors Pseudocode
read first number // priming read while number is not 0 { print "The factors for number are " for factor = 2 to ( number / 2 ) by 1 if number % factor is 0 print factor and a space } print a new line  read next number // update read

335 Finding Factors (con't)
If no factors are found, the number is prime. We need a flag variable We set the flag to false before starting the for loop that checks for factors. Inside the for loop, we set the flag to true when we find a factor. After the for loop terminates, we check the value of the flag. If it is still false, we did not find any factors and the number is prime. See Example 6.20 Factors.java

336 Object-Oriented Programming Part 2: User-Defined Classes
Chapter 7 Object-Oriented Programming Part 2: User-Defined Classes

337 Topics Defining a Class Defining Instance Variables Writing Methods
The Object Reference this The toString and equals Methods static Members of a Class Graphical Objects enum Types Creating Packages Documentation Using Javadoc

338 Why User-Defined Classes?
Primitive data types (int, double, char, .. ) are great … … but in the real world, we deal with more complex objects: products, Web sites, flight records, employees, students, .. Object-oriented programming enables us to manipulate real-world objects.

339 User-Defined Classes Combine data and the methods that operate on the data Advantages: Class is responsible for the validity of the data. Implementation details can be hidden. Class can be reused. Client of a class A program that instantiates objects and calls methods of the class

340 Syntax for Defining a Class
accessModifier class ClassName { // class definition goes here }

341 Software Engineering Tip
Use a noun for the class name. Begin the class name with a capital letter.

342 Important Terminology
Fields instance variables: data for each object class data: static data that all objects share Members fields and methods Access Modifier determines access rights for the class and its members defines where the class and its members can be used

343 Access Modifiers Access Modifier Class or member can be referenced by…
public methods of the same class, and methods of other classes private methods of the same class only protected methods of the same class, methods of subclasses, and methods of classes in the same package No access modifier (package access) methods in the same package only

344 public vs. private Classes are usually declared to be public
Instance variables are usually declared to be private Methods that will be called by the client of the class are usually declared to be public Methods that will be called only by other methods of the class are usually declared to be private APIs of methods are published (made known) so that clients will know how to instantiate objects and call the methods of the class

345 Defining Instance Variables
Syntax: accessModifier dataType identifierList; dataType can be primitive date type or a class type identifierList can contain: one or more variable names of the same data type multiple variable names separated by commas initial values Optionally, instance variables can be declared as final

346 Examples of Instance Variable Definitions
private String name = ""; private final int PERFECT_SCORE = 100, PASSING_SCORE = 60; private int startX, startY, width, height;

347 Software Engineering Tips
Define instance variables for the data that all objects will have in common. Define instance variables as private so that only the methods of the class will be able to set or change their values. Begin the identifier name with a lowercase letter and capitalize internal words.

348 The Auto Class public class Auto { private String model;
private int milesDriven; private double gallonsOfGas; }

349 Writing Methods Syntax:
accessModifier returnType methodName( parameter list ) // method header { // method body } parameter list is a comma-separated list of data types and variable names. To the client, these are arguments To the method, these are parameters Note that the method header is the method API.

350 Software Engineering Tips
Use verbs for method names. Begin the method name with a lowercase letter and capitalize internal words.

351 Method Return Types The return type of a method is the data type of the value that the method returns to the caller. The return type can be any of Java's primitive data types, any class type, or void. Methods with a return type of void do not return a value to the caller.

352 Value-Returning Methods
Use a return statement to return the value Syntax: return expression;

353 Method Body The code that performs the method's function is written between the beginning and ending curly braces. Unlike if statements and loops, these curly braces are required, regardless of the number of statements in the method body. In the method body, a method can declare variables, call other methods, and use any of the program structures we've discussed, such as if/else statements, while loops, for loops, switch statements, and do/while loops.

354 Constructors Special methods that are called when an object is instantiated using the new keyword. A class can have several constructors. The job of the class constructors is to initialize the instance variables of the new object.

355 Defining a Constructor
Syntax: public ClassName( parameter list ) { // constructor body } Note: no return value, not even void! Each constructor must have a different number of parameters or parameters of different types Default constructor: a constructor that takes no arguments. See Examples 7.1 and 7.2, Auto.java and AutoClient.java

356 Default Initial Values
If the constructor does not assign values to the instance variables, they are auto-assigned default values depending on the instance variable data type. Data Type Default Value byte, short, int, long float, double 0.0 char space boolean false Any object reference (for example, a String) null

357 Common Error Trap Do not specify a return value for a constructor (not even void). Doing so will cause a compiler error in the client program when the client attempts to instantiate an object of the class.

358 Class Scope Instance variables have class scope
Any constructor or method of a class can directly refer to instance variables. Methods also have class scope Any method or constructor of a class can call any other method of a class (without using an object reference).

359 Local Scope A method's parameters have local scope, meaning that:
a method can directly access its parameters. a method's parameters cannot be accessed by other methods. A method can define local variables which also have local scope, meaning that: a method can access its local variables. a method's local variables cannot be accessed by other methods.

360 Summary of Scope A method in a class can access:
the instance variables of its class any parameters sent to the method any variable the method declares from the point of declaration until the end of the method or until the end of the block in which the variable is declared, whichever comes first any methods in the class

361 Accessor Methods Clients cannot directly access private instance variables, so classes provide public accessor methods with this standard form: public returnType getInstanceVariable( ) { return instanceVariable; } (returnType is the same data type as the instance variable)

362 Accessor Methods Example: the accessor method for model. return model;
public String getModel( ) { return model; } See Examples 7.3 Auto.java & 7.4 AutoClient.java

363 Mutator Methods Allow client to change the values of instance variables public void setInstanceVariable( dataType newValue ) { // validate newValue, // then assign to instance variable }

364 Mutator Methods Example: the mutator method for milesDriven
public void setMilesDriven( int newMilesDriven ) { if ( newMilesDriven >= 0 ) milesDriven = newMilesDriven; else System.err.println( "Miles driven " + "cannot be negative." ); System.err.println( "Value not changed." ); } See Examples 7.5 Auto.java & 7.6 AutoClient.java

365 Software Engineering Tip
Write the validation code for the instance variable in the mutator method and have the constructor call the mutator method to validate and set initial values This eliminates duplicate code and makes the program easier to maintain

366 Common Error Trap Do not declare method parameters.
Parameters are defined already and are assigned the values sent by the client to the method. Do not give the parameter the same name as the instance variable. The parameter has name precedence so it "hides" the instance variable. Do not declare a local variable with the same name as the instance variable. Local variables have name precedence and hide the instance variable.

367 Data Manipulation Methods
Perform the "business" of the class. Example: a method to calculate miles per gallon: public double calculateMilesPerGallon( ) { if ( gallonsOfGas != 0.0 ) return milesDriven / gallonsOfGas; else return 0.0; } See Examples 7.7 Auto.java & 7.8 AutoClient.java

368 The Object Reference this
How does a method know which object's data to use? this is an implicit parameter sent to methods and is an object reference to the object for which the method was called. When a method refers to an instance variable name, this is implied Thus: variableName model is understood to be is understood to be this.variableName this.model

369 Using this in a Mutator Method
public void setInstanceVariable( dataType instanceVariableName ) { this.instanceVariableName = instanceVariableName; } Example: public void setModel( String model ) this.model = model; this.model refers to the instance variable. model refers to the parameter.

370 The toString Method Returns a String representing the data of an object Client can call toString explicitly by coding the method call. Client can call toString implicitly by using an object reference where a String is expected. Example client code: Auto compact = new Auto( ); // explicit toString call System.out.println( compact.toString( ) ); // implicit toString call System.out.println( compact );

371 The toString API Return value Method name and argument list
returns a String representing the data of an object

372 Auto Class toString Method
public String toString( ) { DecimalFormat gallonsFormat = new DecimalFormat( "#0.0" ); return "Model: " + model + "; miles driven: " + milesDriven + "; gallons of gas: " + gallonsFormat.format( gallonsOfGas ); }

373 The equals Method Determines if the data in another object is equal to the data in this object Example client code using Auto references auto1 and auto2: if ( auto1.equals( auto2 ) ) System.out.println( "auto1 equals auto2" ); Return value Method name and argument list boolean equals( Object obj ) returns true if the data in the Object obj is the same as in this object; false otherwise.

374 Auto Class equals Method
public boolean equals( Auto autoA ) { if ( model.equals( autoA.model ) && milesDriven == autoA.milesDriven && Math.abs( gallonsOfGas autoA.gallonsOfGas ) < ) return true; else return false; } See Examples 7.10 Auto.java & 7.11 AutoClient.java

375 static Variables accessSpecifier static dataType variableName;
Also called class variables One copy of a static variable is created per class static variables are not associated with an object static constants are often declared as public To define a static variable, include the keyword static in its definition: Syntax: accessSpecifier static dataType variableName; Example: public static int countAutos = 0;

376 static Methods Also called class methods
Often defined to access and change static variables static methods cannot access instance variables: static methods are associated with the class, not with any object. static methods can be called before any object is instantiated, so it is possible that there will be no instance variables to access.

377 Rules for static and Non-static Methods
See Examples 7.12 and 7.13 static Method Non-static Method Access instance variables? no yes Access static class variables? Call static class methods? Call non-static instance methods? Use the object reference this?

378 Creating Packages A package is a collection of related classes that can be imported into a program. Packages allow reuse of classes without needing the class in the same directory as the other source files. To include a class in a package, precede the class definition with the package statement: package packageName;

379 A Reusable Class For example, we can create a class that provides type-safe reading of input from the console that can be reused by our programs. We will name this class ConsoleIn.java See Example 7.20

380 Naming Packages To avoid name collisions, which can occur when multiple programmers define packages, we use this naming convention: Use the reverse of the domain name, excluding "www". For example, for a domain name: the package name would begin with: com.jbpub then add the package name: com.jbpub.af

381 Create the Directory Structure
For the package com.jbpub.af, we create three directories and place ConsoleIn.java into the af directory and compile it:

382 Modify the CLASSPATH The CLASSPATH environment variable tells the compiler where to look for packages. Set the CLASSPATH to include the directory in which you created the com directory for your package. On Windows, if com is created in My Documents, the CLASSPATH might be: .;c:\documents and settings\user\My Documents On Linux, if com is created in myClasses in your home directory, the CLASSPATH might be: .;/usr/local/java/jre/lib;/home/user/myClasses

383 Client Use of Package To reuse the classes in a package, use the import statement. import com.jbpub.af.ConsoleIn; See Example 7.21 ConsoleInClient.java

384 Javadoc Documentation
The Java class library documentation on Sun's Web site ( helps us learn how to instantiate objects and call methods for the classes. This documentation was generated using Javadoc, a tool provided in the Java Software Development Toolkit (SDK). We can also use Javadoc to generate Web pages that provide documentation on our class's fields and methods.

385 To Use Javadoc We need to add Javadoc comments and special tags to our classes. Javadoc comments begin with /** and end with */ (Note that this is similar to a Java block comment, but with an extra * in the opening syntax.) Example: /** Auto class * Anderson, Franceschi */

386 Block Tags Identify parameters and return values
HTML tags can be used in the descriptions For example, <BR> to insert a new line Tag Common syntax @param @param variableName description @return @return description

387 Sample equals Method Documentation
/** * equals method:<BR> * Compares the fields of two Auto objects a1 another Auto object a boolean, true if this object * has the same field values as the parameter a1 */ public boolean equals( Auto a1 ) { return ( model.equals( a1.model ) && milesDriven == a1.milesDriven && Math.abs( gallonsOfGas - a1.gallonsOfGas ) < ); }

388 Executing Javadoc javadoc.exe is located in the bin directory of the Java SDK To generate documentation for a class: javadoc Class.java Example: javadoc Auto.java To generate documentation for all classes in a directory: javadoc *.java See Example 7.22

389 Sample Javadoc Documentation

390 Single-Dimensional Arrays
Chapter 8 Single-Dimensional Arrays

391 Topics Declaring and Instantiating Arrays Accessing Array Elements
Writing Methods Aggregate Array Operations Using Arrays in Classes Searching and Sorting Arrays Using Arrays as Counters ArrayLists

392 Arrays An array is a sequence of variables of the same data type.
The data type can be any of Java's primitive types (int, short, byte, long, float, double, boolean, char) or a class. Each variable in the array is an element. We use an index to specify the position of each element in the array.

393 Declaring and Instantiating Arrays
Arrays are objects, so creating an array requires two steps: declaring the reference to the array instantiating the array To declare a reference to the array, use this syntax: datatype [] arrayName; To instantiate an array, use this syntax: arrayName = new datatype[ size ]; where size is an expression than evaluates to an integer and specifies the number of elements.

394 Examples Declaring arrays: Instantiating these arrays:
double [] dailyTemps; // elements are doubles String [] cdTracks; // elements are Strings boolean [] answers; // elements are booleans Auto [] cars; // elements are Auto references int [] cs101, bio201; // two integer arrays Instantiating these arrays: dailyTemps = new double[365]; // 365 elements cdTracks = new String[15]; // 15 elements int numberOfQuestions = 30; answers = new boolean[numberOfQuestions]; cars = new Auto[3]; // 3 elements cs101 = new int[5]; // 5 elements bio201 = new int[4]; // 4 elements

395 Default Values for Elements
When an array is instantiated, the elements are assigned default values according to the array data type. Array data type Default value byte, short, int, long float, double 0.0 char space boolean false Any object reference (for example, a String) null

396 Combining the Declaration and Instantiation of Arrays
Syntax: datatype [] arrayName = new datatype[size]; Examples: double [] dailyTemps = new double[365]; String [] cdTracks = new String[15]; int numberOfQuestions = 30; boolean [] answers = new boolean[numberOfQuestions]; Auto [] cars = new Auto[3]; int [] cs101 = new int[5], bio201 = new int[4];

397 Assigning Initial Values to Arrays
Arrays can be instantiated by specifying a list of initial values. Syntax: datatype [] arrayName = { value0, value1, … }; where valueN is an expression evaluating to the data type of the array and is the value to assign to the element at index N. Examples: int nine = 9; int [] oddNumbers = { 1, 3, 5, 7, nine, nine + 2, 13, 15, 17, 19 }; Auto sportsCar = new Auto( "Ferrari", 0, 0.0 ); Auto [] cars = { sportsCar, new Auto( ), new Auto("BMW", 100, 15.0 ) };

398 An initialization list can be given only when the array is declared.
Common Error Trap An initialization list can be given only when the array is declared. Attempting to assign values to an array using an initialization list after the array is instantiated will generate a compiler error. The new keyword is not used when an array is instantiated using an initialization list. Also, no size is specified for the array; the number of values in the initialization list determines the size of the array.

399 Accessing Array Elements
To access an element of an array, use this syntax: arrayName[exp] where exp is an expression that evaluates to an integer. exp is the element's index -- its position within the array. The index of the first element in an array is 0. length is a read-only integer instance variable that holds the number of elements in the array and is accessed using this syntax: arrayName.length

400 Common Error Trap Attempting to access an element of an array using an index less than 0 or greater than arrayName.length – 1 will generate an ArrayIndexOutOfBoundsException at run time. Note that for an array, length – without parentheses – is an instance variable, whereas for Strings, length( ) – with parentheses – is a method. Note also that the array's instance variable is named length, rather than size.

401 Accessing Array Elements
See Example 8.1 CellBills.java Element Syntax Element 0 arrayName[0] Element i arrayName[i] Last element arrayName[arrayName.length - 1]

402 cellBills Array When instantiated: After assigning values:

403 Instantiating an Array of Objects
To instantiate an array with a class data type: 1. instantiate the array 2. instantiate the objects Example: // instantiate array; all elements are null Auto [] cars = new Auto[3]; // instantiate objects and assign to elements Auto sportsCar = new Auto( "Miata", 100, 5.0 ); cars[0] = sportsCar; cars[1] = new Auto( ); // cars[2] is still null See Example 8.2 AutoArray.java

404 Aggregate Array Operations
We can perform the same operations on arrays as we do on a series of input values. calculate the total value find the average value find a minimum or maximum value, etc. To perform an operation on all elements in an array, we use a for loop to perform the operation on each element in turn.

405 Standard for Loop Header for Array Operations
for ( int i = 0; i < arrayName.length; i++ ) initialization statement ( int i = 0 ) creates index i and sets it to the first element ( 0 ). loop condition ( i < arrayName.length ) continues execution until the end of the array is reached. loop update ( i++ ) increments the index to the next element, so that we process each element in order. Inside the for loop, we reference the current element as: arrayName[i]

406 Printing All Elements of an Array
Example: This code prints each element in an array named cellBills, one element per line (assuming that cellBills has been instantiated): for ( int i = 0; i < cellBills.length; i++ ) { System.out.println( cellBills[i] ); } See Example 8.3 PrintingArrayElements.java

407 Reading Data Into an Array
Example: this code reads values from the user into an array named cellBills, which has previously been instantiated: Scanner scan = new Scanner( System.in ); for ( int i = 0; i < cellBills.length; i++ ) { System.out.print( "Enter bill > " ); cellBills[i] = scan.nextDouble( ); } See Example 8.4 ReadingDataIntoAnArray.java

408 Summing the Elements of an Array
Example: this code calculates the total value of all elements in an array named cellBills, which has previously been instantiated: double total = 0.0; // initialize total for ( int i = 0; i < cellBills.length; i++ ) { total += cellBills[i]; } System.out.println( "The total is " + total ); See Example 8.5 SummingArrayElements.java

409 Finding Maximum/Minimum Values
Example: this code finds the maximum value in an array named cellBills: // make first element the current maximum double maxValue = cellBills[0]; // start for loop at element 1 for ( int i = 1; i < cellBills.length; i++ ) { if ( cellBills[i] > maxValue ) maxValue = cellBills[i]; } System.out.println( "The maximum is " maxValue ); See Example 8.6 MaxArrayValue.java

410 Copying Arrays Suppose we want to copy the elements of an array to another array. We could try this code: double [] billsBackup = new double [6]; billsBackup = cellBills; // incorrect! Although this code compiles, it is logically incorrect!We are copying the cellBills object reference to the billsBackup object reference. We are not copying the array data. The result of this code is shown on the next slide.

411 Copying Array References
billsBackup = cellBills; has this effect:

412 Copying Array Values Example: this code copies the values of all elements in an array named cellBills to an array named billsBackup, both of which have previously been instantiated with the same length: for ( int i = 0; i < cellBills.length; i++ ) { billsBackup[i] = cellBills[i]; } The effect of this for loop is shown on the next slide. See Example 8.7 CopyingArrayElements.java

413 Copying Array Values

414 Changing an Array's Size
An array's length instance variable is constant. that is, arrays are assigned a constant size when they are instantiated. To expand an array while maintaining its original values: Instantiate an array with the new size and a temporary name. Copy the original elements to the new array. Point the original array reference to the new array. Assign a null value to the temporary array reference.

415 Expanding the Size of an Array
This code will expand the size of the cellBills array from 6 to 12 elements: //instantiate new array double [] temp = new double [12];   // copy all elements from cellBills to temp for ( int i = 0; i < cellBills.length; i++ ) { temp[i] = cellBills[i]; // copy each element } // point cellBills to new array cellBills = temp; temp = null;

416 Comparing Arrays for Equality
To compare whether the elements of two arrays are equal: Determine if both arrays have the same length. Compare each element in the first array with the corresponding element in the second array. To do this, we'll use a flag variable and a for loop.

417 Comparing cellBills1 to cellBills2
boolean isEqual = true; if ( cellBills1.length != cellBills2.length ) isEqual = false; // sizes are different else { for ( int i = 0; i < cellBills1.length && isEqual; i++ ) if ( Math.abs( cellBills1[i] - cellBills2[i] ) > ) isEqual = false; // elements are not equal } See Example 8.8 ComparingArrays.java

418 Using Arrays in Classes
In a user-defined class, an array can be an instance variable a parameter to a method a return value from a method a local variable in a method

419 Methods with Array Parameters
To define a method that takes an array as a parameter, use this syntax: accessModifier returnType methodName( dataType [] arrayName ) To define a method that returns an array, use this syntax: accessModifier dataType [] methodName( parameterList ) To pass an array as an argument to a method, use the array name without brackets: methodName( arrayName )

420 Common Error Trap If you think of the brackets as being part of the data type of the array, then it's easy to remember that brackets are included in the method header (where the data types of parameters are given) brackets are not included in method calls (where the data itself is given).

421 Arrays as Instance Variables
Because arrays are objects, the name of an array is an object reference. Methods must be careful not to share references to instance variables with the client. Otherwise, the client could directly change the array elements using the reference to the array instance variable. See Examples 8.11 & 8.12

422 Array Instance Variables
A constructor (or mutator) that accepts an array as a parameter should instantiate a new array for the instance variable and copy the elements from the parameter array to the instance variable array. // constructor public CellPhone( double [] bills ) { // instantiate array with length of parameter cellBills = new double [bills.length]; // copy parameter array to cellBills array for ( int i = 0; i < cellBills.length; i++ ) cellBills[i] = bills[i]; }

423 Accessors for Arrays Similarly, an accessor method for the array instance variable should return a copy of the array. public double [] getCellBills( ) { // instantiate temporary array double [] temp = new double [cellBills.length]; // copy instance variable values to temp for ( int i = 0; i < cellBills.length; i++ ) temp[i] = cellBills[i]; // return copy of array return temp; }

424 Software Engineering Tip
Sharing array references with the client violates encapsulation. To accept values for an instance variable array as a parameter to a method, instantiate a new array and copy the elements of the parameter array to the new array. Similarly, to return an instance variable array, a method should copy the elements of the instance variable array to a temporary array and return a reference to the temporary array.

425 Retrieving Command Line Arguments
The syntax of an array parameter for a method might look familiar. We've seen it repeatedly in the header for the main method: public static void main( String [] args ) main receives a String array as a parameter. That array holds the arguments, if any, that the user sends to the program from the command line. For example, command line arguments might be: the name of a file for the program to use configuration preferences

426 Printing Command Line Arguments
public static void main( String [] args ) { System.out.println( "The number of parameters " + " is " + args.length ); for ( int i = 0; i < args.length; i++ ) System.out.println( "args[" + i + "]: " + args[i] ); } See Example 8.13 CommandLineArguments.java

427 Sequential Search A Sequential Search can be used to determine if a specific value (the search key) is in an array. Approach is to start with the first element and compare each element to the search key: If found, return the index of the element that contains the search key. If not found, return -1. Because -1 is not a valid index, this is a good return value to indicate that the search key was not found in the array.

428 Code to Perform a Sequential Search
public int findWinners( int key ) { for ( int i = 0; i < winners.length; i++ ) if ( winners[i] == key ) return i; } return -1; See Examples 8.14 and 8.15

429 Sorting an Array When an array's elements are in random order, our Sequential Search method needs to look at every element in the array before discovering that the search key is not in the array. This is inefficient; the larger the array, the more inefficient a Sequential Search becomes. We could simplify the search by arranging the elements in numeric order, which is called sorting the array. Once the array is sorted, we can use various search algorithms to speed up a search.

430 Selection Sort In a Selection Sort, we select the largest element in the array and place it at the end of the array. Then we select the next-largest element and put it in the next-to-last position in the array, and so on. To do this, we consider the unsorted portion of the array as a subarray. We repeatedly select the largest value in the current subarray and move it to the end of the subarray, then consider a new subarray by eliminating the elements that are in their sorted locations. We continue until the subarray has only one element. At that time, the array is sorted.

431 The Selection Sort Algorithm
To sort an array with n elements in ascending order: 1.  Consider the n elements as a subarray with m = n elements. 2.  Find the index of the largest value in this subarray. 3.  Swap the values of the element with the largest value and the element in the last position in the subarray. 4.  Consider a new subarray of m = m - 1 elements by eliminating the last element in the previous subarray 5.  Repeat steps 2 through 4 until m = 1.

432 Selection Sort Example
In the beginning, the entire array is the unsorted subarray: We swap the largest element with the last element:

433 Selection Sort Example (continued)
Again, we swap the largest and last elements: When there is only 1 unsorted element, the array is completely sorted:

434 Swapping Values To swap two values, we define a temporary variable to hold the value of one of the elements, so that we don't lose that value during the swap. To swap elements a and b: define a temporary variable, temp. assign element a to temp. assign element b to element a. assign temp to element b.

435 Swapping Example This code will swap elements 3 and 6 in an int array named array: int temp; // step 1 temp = array[3]; // step 2 array[3] = array[6]; // step 3 array[6] = temp; // step 4 See Examples 8.16 & 8.17

436 Bubble Sort The basic approach to a Bubble Sort is to make multiple passes through the array. In each pass, we compare adjacent elements. If any two adjacent elements are out of order, we put them in order by swapping their values. At the end of each pass, one more element has "bubbled" up to its correct position. We keep making passes through the array until all the elements are in order.

437 Bubble Sort Algorithm To sort an array of n elements in ascending order, we use a nested loop: The outer loop executes n – 1 times. For each iteration of the outer loop, the inner loop steps through all the unsorted elements of the array and does the following: Compares the current element with the next element in the array. If the next element is smaller, it swaps the two elements.

438 Bubble Sort Pseudocode
for i = 0 to last array index – 1 by 1 { for j = 0 to ( last array index – i - 1 ) by 1 if ( 2 consecutive elements are not in order ) swap the elements }

439 Bubble Sort Example At the beginning, the array is:
We compare elements 0 (17) and 1 (26) and find they are in the correct order, so we do not swap.

440 Bubble Sort Example (con't)
The inner loop counter is incremented to the next element: We compare elements 1 (26) and 2 (5), and find they are not in the correct order, so we swap them.

441 Bubble Sort Example (con't)
The inner loop counter is incremented to the next element: We compare elements 2 (26) and 3 (2), and find they are not in the correct order, so we swap them. The inner loop completes, which ends our first pass through the array.

442 Bubble Sort Example (2nd pass)
The largest value in the array (26) has bubbled up to its correct position. We begin the second pass through the array. We compare elements 0 (17) and 1 (5) and swap them.

443 Bubble Sort Example (2nd pass)
We compare elements 1 (17) and 2 (2) and swap. This ends the second pass through the array. The second-largest element (17) has bubbled up to its correct position.

444 Bubble Sort (3rd pass) We begin the last pass through the array.
We compare element 0 (5) with element 1 (2) and swap them.

445 Bubble Sort ( complete )
The third-largest value (5) has bubbled up to its correct position. Only one element remains, so the array is now sorted.

446 Bubble Sort Code See Examples 8.18 & 8.19
for ( int i = 0; i < array.length - 1; i++ ) { for ( int j = 0; j < array.length – i - 1; j++ ) if ( array[j] > array[j + 1] ) // swap the elements int temp = array[j + 1]; array[j + 1] = array[j]; array[j] = temp; } } // end inner for loop } // end outer for loop See Examples 8.18 & 8.19

447 Sorting Arrays of Objects
In arrays of objects, the array elements are object references. Thus, to sort an array of objects, we need to sort the data of the objects. Usually, one of the instance variables of the object acts as a sort key. For example, in an object, the sort key might be the date received.

448 Example Code to sort an array of Auto objects using model as the sort key: for ( int i = 0; i < array.length - 1; i++ ) { for ( int j = 0; j < array.length - i - 1; j++ ) if ( array[j].getModel( ).compareTo( array[j + 1].getModel( ) ) > 0 ) Auto temp = array[j + 1]; array[j + 1] = array[j]; array[j] = temp; } end if statement } // end inner for loop } // end outer for loop

449 Sequential Search of a Sorted Array
When the array is sorted, we can implement a more efficient algorithm for a sequential search. If the search key is not in the array, we can detect that condition when we find a value that is higher than the search key. All elements past that position will be greater than the value of that element, and therefore, greater than the search key.

450 Sample Code public int searchSortedArray( int key ) {
for ( int i = 0; i < array.length && array[i] <= key; i++ ) if ( array[i] == key ) return i; }   return –1; // end of array reached without // finding key or // an element larger than // the key was found }

451 Using Arrays as Counters
To count multiple items, we can use an array of integers. Each array element is a counter. Example: we want to throw a die and count the number of times each side is rolled. We set up an array of 6 integer counters, initialized to 0. For each roll, we use ( roll - 1 ) as the index of the array element to increment.

452 Example Code See Examples 8.22, 8.23, & 8.24
// instantiate array of counters int [] rollCount = new int [6]; // roll the die NUMBER_OF_ROLLS times for ( int i = 1; i <= NUMBER_OF_ROLLS; i++ ) { // roll the die int roll = (int) Math.random( ) * 6 + 1; // increment the corresponding counter rollCount[roll - 1]++; } See Examples 8.22, 8.23, & 8.24

453 The ArrayList Class Arrays have a fixed size once they have been instantiated. What if we don't know how many elements we will need? For example, if we are reading values from a file returning search results We could create a very large array, but then we waste space for all unused elements. A better idea is to use an ArrayList, which stores elements of object references and automatically expands its size, as needed.

454 The ArrayList Class Package: java.util
All ArrayList elements are object references, so we could have an ArrayList of Auto objects, Book objects, Strings, etc. To store primitive types in an ArrayList, use the wrapper classes (Integer, Double, Character, Boolean, etc.)

455 Declaring an ArrayList
Use this syntax: ArrayList<E> arrayListName; E is a class name that specifies the type of object references that will be stored in the ArrayList For example: ArrayList<String> listOfStrings; ArrayList<Auto> listOfCars; ArrayList<Integer> listOfInts; The ArrayList is a generic class. The ArrayList class has been written so that it can store object references of any type specified by the client.

456 ArrayList Constructors
Constructor name and argument list ArrayList<E> constructs an ArrayList object of type E with an initial capacity of 10 ArrayList<E>( int initialCapacity ) constructs an ArrayList object of type E with the specified initial capacity The capacity of an ArrayList is the total number of elements allocated to the list. The size of an an ArrayList is the number of those elements that are used.

457 Instantiating an ArrayList
This list has a capacity of 10 Astronaut references, but a size of 0. ArrayList<Astronaut> listOfAstronauts = new ArrayList<Astronaut>( ); This list has a capacity of 5 Strings, but has a size of 0. ArrayList<String> listOfStrings = new ArrayList<String>( 5 );

458 ArrayList Methods Return value Method name and argument list boolean
add( E element ) appends element to the end of the list void clear( ) removes all the elements in the list int size( ) returns the number of elements E remove( int index ) removes the element at the specified index position

459 More ArrayList Methods
Return value Method name and argument list E get( int index ) returns the element at the specified index position; the element is not removed from the list. set( int index, E element ) replaces the element at the specified index position with the specified element void trimToSize( ) sets the capacity of the list to its current size

460 Processing Array Lists
Using a standard for loop: ClassName currentObject; for ( int i = 0; i < arrayListName.size( ); i++ ) { currentObject = arrayListName.get( i ); // process currentObject } Example: Auto currentAuto; for ( int i = 0; i < listOfAutos.size( ); i++ ) currentAuto = listOfAutos.get( i ); // process currentAuto

461 The Enhanced for Loop Simplifies processing of lists
The standard form is: for ( ClassName currentObject : arrayListName ) { // process currentObject } This enhanced for loop prints all elements of an ArrayList of Strings named list: for ( String s : list ) System.out.println( s ); See Example 9.12 ArrayListOfIntegers.java

462 Using an ArrayList We want to write a program for a bookstore that allows users to search for books using keywords. We will have three classes in this program: A Book class, with instance variables representing the title, author, and price A BookStore class that stores Book objects in an ArrayList and provides a searchForTitle method A BookSearchEngine class, which provides the user interface and the main method See Examples 9.13, 9.14, & 9.15

463 Graphical User Interfaces
Chapter 12 Graphical User Interfaces

464 Topics GUI Applications with JFrame GUI Components JLabel
Event Handling Text Fields Command Buttons, Radio Buttons, and Checkboxes

465 Introduction GUIs enable the user to
select the next function to be performed enter data set program preferences, such as colors or fonts. GUIs also make the program easier to use a GUI is a familiar interface to users. Users can learn quickly to operate your program, in many cases, without consulting documentation or requiring extensive training.

466 The JFrame Class The JFrame class, in the javax.swing package, allows you to display a window. JFrame is a Component, a graphical object that can be displayed Container, a component that holds other objects Window, a basic window Frame, a framed window

467 JFrame Constructors Constructor
constructs a JFrame object, initially invisible, with no text in the title bar JFrame( String titleBarText ) constructs a JFrame object, initially invisible, with titleBarText displayed in the window's title bar

468 Useful Methods of the JFrame Class
Return value Method name and argument list Container getContentPane( ) returns the content pane object for this window void setDefaultCloseOperation( int operation ) sets the default operation when the user closes this window, that is, when the user clicks on the X icon in the top-right corner of the window setSize( int width, int height ) sizes the window to the specified width and height in pixels setVisible( boolean mode ) displays this window if mode is true; hides the window if mode is false Applications extending JFrame inherit these methods.

469 A Shell GUI Application
See Example 12.1 ShellGUIApplication.java Our application inherits from JFrame public class ShellGUIApplication extends JFrame The main method instantiates an instance of our application: ShellGUIApplication basicGui = new ShellGUIApplication( ); Specifies that the application should terminate when the user closes the window: basicGui.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

470 Example 12.1 ShellGuiApplication.java
import javax.swing.JFrame; import java.awt.Container; // other import statements here as needed public class ShellGUIApplication extends JFrame { private Container contents; // declare other instance variables public ShellGUIApplication( ) // constructor super( "A Shell GUI Application" ); // call JFrame constructor with title bar text contents = getContentPane( ); // get container for components // set the layout manager // instantiate GUI components and other instance variables // add GUI components to the content pane setSize( 300, 200 ); // set original size of window setVisible( true ); // make window visible }

471 Example 12.1 ShellGuiApplication.java
public static void main( String [ ] args ) { ShellGUIApplication basicGui = new ShellGUIApplication( ); basicGui.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); }

472 A Shell GUI Application (con't)
The GUI application's constructor's job is to: call the constructor of the JFrame superclass get an object reference to the content pane container. We will add our GUI components to the content pane. set the layout manager. Layout managers arrange the GUI components in the window. instantiate each component add each component to the content pane set the size of the window display the window.

473 Common Error Trap Be sure to call the setSize method to set the initial dimensions of the window and call the setVisible method to display the window and its contents. Omitting the call to the setSize method will create a default JFrame consisting of a title bar only. If you omit the call to the setVisible method, the window will not open when the application begins.

474 GUI Components A component performs at least one of these functions:
displays information collects data from the user allows the user to initiate program functions The Java class library provides a number of component classes in the javax.swing package

475 AWT Versus Swing Java supports two implementations of GUI components: AWT (Abstract Window Toolkit) and swing. AWT components: the original implementation of Java components AWT hands off some of the display and behavior of the component to the native windowing system called heavyweight components Disadvantage: because of the inconsistencies in the look-and-feel of the various windowing systems, an application may behave slightly differently on one platform than on another.

476 AWT Versus Swing Swing Components Benefits:
second generation of GUI components developed entirely in Java to provide a consistent look and feel from platform to platform referred to as lightweight components Benefits: Applications run consistently across platforms, which makes maintenance easier. The swing architecture has its roots in the model-view-controller paradigm, which facilitates programming. An application can take on the look-and-feel of the platform on which it is running, if desired.

477 Java Swing Components, part 1
Component/ Java Class Purpose Label / JLabel Displays an image or read-only text. Labels are often paired with text fields to identify the contents of the text field. Text field / JTextField A single-line text box for displaying information and accepting user input Text area / JTextArea Multiple-line text field for data entry or display Password field / JPasswordField Single-line text field for accepting passwords without displaying the characters typed.

478 Java Swing Components, part 2
Component/ Java Class Purpose Button / JButton Command button that the user clicks to signal that an operation should be performed Radio Button / JRadioButton Toggle button that the user clicks to select one option in the group. Checkbox / JCheckBox Toggle button that the user clicks to select 0, 1, or more options in a group. List / JList List of items that the user clicks to select one or more items Drop-down List / JComboBox Drop-down list of items that the user clicks to select one item

479

480 Useful JComponent Methods
Return value Method name and argument list void setVisible( boolean mode ) makes the component visible if mode is true; hides the component if mode is false. The default is visible. setToolTipText( String toolTip ) sets the tool tip text to toolTip. When the mouse lingers over the component, the tool tip text will be displayed. setForeground( Color foreColor ) sets the foreground color of the component to foreColor. setBackground( Color backColor ) sets the background color of the component to backColor.

481 More Useful JComponent Methods
Return value Method name and argument list void setOpaque( boolean mode ) sets the component's background to opaque if mode is true; sets the component's background to transparent if mode is false. If opaque, the component's background is filled with the component's background color; if transparent, the component's background is filled with the background color of the container on which it is placed. The default is transparent. setEnabled( boolean mode ) enables the component if mode is true, disables the component if mode is false. An enabled component can respond to user input.

482 Useful Container Methods
We use these methods to set up the organization of the components and to add and remove components from the window: Return value Method name and argument list void setLayout( LayoutManager mgr ) sets the layout manager of the window to mgr Component add( JComponent component ) adds the component to the window, using the rules of the layout manager. Returns the argument. removeAll( ) removes all components from the window

483 The FlowLayout Layout Manager
The FlowLayout layout manager arranges components in rows from left to right in the order in which the components are added to the container. Whenever a newly added component does not fit into the current row, the FlowLayout layout manager starts a new row. We will discuss other layout managers later FlowLayout Constructor FlowLayout( ) creates a FlowLayout layout manager that centers components in the container.

484 The JLabel Component A JLabel label component does not interact with a user The JLabel displays some information, for example: a title an identifier for another component an image Example 12.2 Dinner.java in jGrasp

485 JLabel Constructors Constructor
JLabel( String text ) creates a JLabel object that displays the specified text JLabel( String text, int alignment ) creates a JLabel object that displays the specified text. The alignment argument specifies the alignment of the text within the label component. The alignment value can be any of the following static int constants from the SwingConstants interface: LEFT, CENTER, RIGHT, LEADING, or TRAILING. By default, the label text is left-adjusted. JLabel( Icon image ) creates a JLabel object that displays the image.

486 Common Error Trap As for any object reference, you must instantiate a component before using it. Forgetting to instantiate a component before adding it to the content pane will result in a NullPointerException at run time when the JVM attempts to display the component.

487 Common Error Trap Be sure to place the call to the setVisible method as the last statement in the constructor. If you add components to the window after calling setVisible, those components will not be displayed until the window contents are refreshed, that is, not until the window is repainted.

488 Event Handling GUI programming uses an event-driven model of programming. The program responds to events caused by the user interacting with a GUI component. For example, we might display some text fields, a few buttons, and a selectable list of items. Then our program will "sit back" and wait for the user to do something. When the user enters text into a text field, presses a button, or selects an item from the list, our program will respond, performing the function that the user has requested, then sit back again and wait for the user to do something else.

489 Handling Events When the user interacts with a GUI component, the component fires an event. To allow a user to interact with our application through a GUI component, we need to perform the following functions:  1.   write an event handler class (called a listener) 2.   instantiate an object of that listener 3.   register the listener on one or more components An application can instantiate more than one event handler.

490 Listener Interfaces A typical event handler class implements a listener interface. The listener interfaces, which inherit from the EventListener interface, are supplied in the java.awt.event or javax.swing.event package. A listener interface specifies one or more abstract methods that an event handler class needs to override. The listener methods receive as a parameter an event object, which represents the event that was fired.

491

492 Event Objects Event classes are subclasses of the EventObject class and are in the java.awt.event and javax.swing.event packages. From the EventObject class, event classes inherit the getSource method. With simple if .. else if statements, an event handler can identify which of its registered components fired the event. Return value Method name and argument list Object getSource( ) returns the object reference of the component that fired the event

493 Events and Listeners JComponent User Activity Event Object
Listener Interface to Implement JTextField Pressing Enter ActionEvent ActionListener JTextArea JButton Pressing the button JRadioButton Selecting a radio button ItemEvent ItemListener JCheckBox Selecting a checkbox

494 More Events and Listeners
JComponent User Activity Event Object Listener Interface to Implement JList Selecting an item ListSelection-Event ListSelection-Listener JComboBox ItemEvent ItemListener Any component Pressing or releasing mouse buttons MouseEvent MouseListener Moving or dragging the mouse MouseMotion-Listener

495 Pattern for Event Handling
Constructor: public ClassName1( ) // constructor { // call JFrame constructor // get content pane // set the layout manager // instantiate components // add components to the content pane // instantiate event handler objects // register event handlers on components // set window size // make window visible }

496 Registering a Listener
In the constructor, we instantiate an object of our event handler class. Then we register that event handler on a component by calling an add…Listener method. add…Listener APIs void addActionListener( ActionListener handler ) void addItemListener( ItemListener handler ) void addListSelectionListener( ListSelectionListener handler ) void addMouseListener( MouseListener handler ) void addMouseMotionListener( MouseMotionListener handler )

497 Common Error Trap If you do not register a listener on a component, the user will still be able to interact with the component (type into a text field, for example), but the component will not fire an event. Thus, even though you provided an event handler, it will never execute.

498 Event Handler Pattern Event handler as a private inner class.
private class EventHandlerName implements ListenerName { // implement the listener interface methods // to process the events } A private inner class is defined within the public class and has access to all the members of the public class. When an event is fired on a registered component, the appropriate listener methods executes automatically.

499 Text Fields We will write a GUI program that simulates a login. We will use these components: JTextField (a single line of text) for the User ID JPasswordField (a single line of text that echoes a special character for each character typed by the used) for the password JTextArea (multiple lines of text) to display a legal warning to potential hackers

500 JTextField and JPasswordField Constructors
JTextField( String text ) creates a text field initially filled with text JTextField( int numberColumns ) constructs an empty text field with the specified number of columns JPasswordField JPasswordField( int numberColumns ) constructs an empty password field with the specified number of columns

501 JTextArea Constructors
JTextArea( String text ) constructs a text area initially filled with text JTextArea( int numRows, int numColumns ) constructs an empty text area with the number of rows and columns specified by numRows and numColumns JTextArea( String text, int numRows, int numColumns ) constructs a text area initially filled with text, and with the number of rows and columns specified by numRows and numColumns

502 Methods Common to JTextField, JTextArea, & JPasswordField
Return value Method name and argument list void setEditable( boolean mode ) sets the properties of the text component as editable or noneditable, depending on whether mode is true or false. The default is editable. setText( String newText ) sets the text of the text component to newText String getText( ) returns the text contained in the text component

503 Additional Methods of the JPasswordField Class
Return value Method name and argument list void setEchoChar( char c ) sets the echo character of the password field to c char [] getPassword( ) returns the text entered in this password field as an array of chars. Note: this method is preferred over the getText method for retrieving the password typed by the user.

504 The ActionListener Interface
An event handler that implements the ActionListener interface provides code in this method to respond to the ActionEvent fired by any registered components. public void actionPerformed( ActionEvent event ) Example 12.3 Login.java in jGrasp

505 Common Error Trap Be sure that the header of the listener method you override is coded correctly. Otherwise, your method will not override the abstract method, as required by the interface. For example, misspelling the actionPerformed method name as in this header: public void actionperformed( ActionEvent a ) will generate a compiler error: Login.TextFieldHandler is not abstract and does not override abstract method actionPerformed(java.awt.event.ActionEvent) in java.awt.event.ActionListener

506 Common Error Trap The java.awt.event package is not imported with the java.awt package. You will need both of these import statements: import java.awt.*; import java.awt.event.*;

507 JButton A JButton component implements a command button.
Clicking on a button generates an ActionEvent, so our listener needs to implement the ActionListener interface. Example 12.4 SimpleMath.java in jGrasp JButton Constructor JButton( String buttonLabel ) creates a command button labeled with buttonLabel


Download ppt "Introduction to Programming and the Java Language"

Similar presentations


Ads by Google