Download presentation
Presentation is loading. Please wait.
1
Introduction to Java Programming, 4E
First Class: Introduction, Prerequisites, Advices, Syllabus Lab 1: Create a Java Project, Compile, and Run. Show syntax errors Print program Capture screen shots, and save it in Word, and print it. Homework One: Check in the class randomly. Y. Daniel Liang
2
Introduction Course Objectives Organization of the Book
3
Course Objectives Upon completing the course, you will understand
Create, compile, and run Java programs Primitive data types Java control flow Methods Arrays (for teaching Java in two semesters, this could be the end) Object-oriented programming Core Java classes (Swing, exception, internationalization, multithreading, multimedia, I/O, networking, Java Collections Framework)
4
Course Objectives, cont.
You will be able to Develop programs using Forte Write simple programs using primitive data types, control statements, methods, and arrays. Create and use methods Develop a GUI interface and Java applets Write interesting projects Establish a firm foundation on Java concepts
5
Book Chapters Part I: Fundamentals of Programming
Chapter 1 Introduction to Java Chapter 2 Primitive Data Types and Operations Chapter 3 Control Statements Chapter 4 Methods Chapter 5 Arrays
6
Book Chapters, cont. Part II: Object-Oriented Programming
Chapter 6 Objects and Classes Chapter 7 Strings Chapter 8 Class Inheritance and Interfaces Chapter 9 Object-Oriented Software Development
7
Book Chapters, cont. Part III: GUI Programming
Chapter 10 Getting Started with GUI Programming Chapter 11 Creating User Interfaces Chapter 12 Applets and Advanced GUI
8
Book Chapters, cont. Part IV: Developing Comprehensive Projects
Chapter 13 Exception Handling Chapter 14 Internationalization Chapter 15 Multithreading Chapter 16 Multimedia Chapter 17 Input and Output Chapter 18 Networking Chapter 19 Java Data Structures
9
Chapter 1 Introduction to Java and Forte
What Is Java? Getting Started With Java Programming Create, Compile and Running a Java Application
10
What Is Java? History Characteristics of Java
11
History James Gosling and Sun Microsystems Oak
Java, May 20, 1995, Sun World HotJava The first Java-enabled Web browser JDK Evolutions J2SE, J2ME, and J2EE (not mentioned in the book, but could discuss here optionally)
12
Characteristics of Java
Java is simple Java is object-oriented Java is distributed Java is interpreted Java is robust Java is secure Java is architecture-neutral Java is portable Java’s performance Java is multithreaded Java is dynamic
13
JDK Versions JDK 1.02 (1995) JDK 1.1 (1996)
Java 2 SDK v 1.2 (a.k.a JDK 1.2, 1998) Java 2 SDK v 1.3 (a.k.a JDK 1.3, 2000) Java 2 SDK v 1.4 (a.k.a JDK 1.4, 2002)
14
JDK Editions Java Standard Edition (J2SE)
J2SE can be used to develop client-side standalone applications or applets. Java Enterprise Edition (J2EE) J2EE can be used to develop server-side applications such as Java servlets and Java ServerPages. Java Micro Edition (J2ME). J2ME can be used to develop applications for mobile devices such as cell phones. This book uses J2SE to introduce Java programming.
15
Java IDE Tools Forte by Sun MicroSystems Borland JBuilder
Microsoft Visual J++ WebGain Café IBM Visual Age for Java
16
Getting Started with Java Programming
A Simple Java Application Compiling Programs Executing Applications
17
A Simple Application Example 1.1
//This application program prints Welcome //to Java! package chapter1; public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } Source Run NOTE: To run the program, install slide files on hard disk.
18
Creating and Compiling Programs
On command line javac file.java
19
Executing Applications
On command line java classname
20
Example javac Welcome.java java Welcome output:...
21
Compiling and Running a Program
Where are the files stored in the directory?
22
Anatomy of a Java Program
Comments Package Reserved words Modifiers Statements Blocks Classes Methods The main method
23
Comments In Java, comments are preceded by two slashes (//) in a line, or enclosed between /* and */ in one or multiple lines. When the compiler sees //, it ignores all text after // in the same line. When it sees /*, it scans for the next */ and ignores any text between /* and */.
24
Package The second line in the program (package chapter1;) specifies a package name, chapter1, for the class Welcome. Forte compiles the source code in Welcome.java, generates Welcome.class, and stores Welcome.class in the chapter1 folder.
25
Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program. For example, when the compiler sees the word class, it understands that the word after class is the name for the class. Other reserved words in Example 1.1 are public, static, and void. Their use will be introduced later in the book.
26
Modifiers Java uses certain reserved words called modifiers that specify the properties of the data, methods, and classes and how they can be used. Examples of modifiers are public and static. Other modifiers are private, final, abstract, and protected. A public datum, method, or class can be accessed by other programs. A private datum or method cannot be accessed by other programs. Modifiers are discussed in Chapter 6, "Objects and Classes."
27
Statements A statement represents an action or a sequence of actions. The statement System.out.println("Welcome to Java!") in the program in Example 1.1 is a statement to display the greeting "Welcome to Java!" Every statement in Java ends with a semicolon (;).
28
Blocks A pair of braces in a program forms a block that groups components of a program.
29
Classes The class is the essential Java construct. A class is a template or blueprint for objects. To program in Java, you must understand classes and be able to write and use them. The mystery of the class will continue to be unveiled throughout this book. For now, though, understand that a program is defined by using one or more classes.
30
Methods What is System.out.println? It is a method: a collection of statements that performs a sequence of operations to display a message on the console. It can be used even without fully understanding the details of how it works. It is used by invoking a statement with a string argument. The string argument is enclosed within parentheses. In this case, the argument is "Welcome to Java!" You can call the same println method with a different argument to print a different message.
31
main Method The main method provides the control of program flow. The Java interpreter executes the application by invoking the main method. The main method looks like this: public static void main(String[] args) { // Statements; }
32
Displaying Text in a Message Dialog Box
you can use the showMessageDialog method in the JOptionPane class. JOptionPane is one of the many predefined classes in the Java system, which can be reused rather than “reinventing the wheel.” Source Run
33
The showMessageDialog Method
JOptionPane.showMessageDialog(null, "Welcome to Java!", "Example 1.2", JOptionPane.INFORMATION_MESSAGE));
34
The exit Method Use Exit to terminate the program and stop all threads. NOTE: When your program starts, a thread is spawned to run the program. When the showMessageDialog is invoked, a separate thread is spawned to run this method. The thread is not terminated even you close the dialog box. To terminate the thread, you have to invoke the exit method.
35
Chapter 2 Primitive Data Types and Operations
Introduce Programming with an Example Identifiers, Variables, and Constants Primitive Data Types byte, short, int, long, float, double, char, boolean Expressions Operators, Precedence, Associativity, Operand Evaluation Order: ++, --, *, /, %, +=, -=, *=, /=, %=, ^, &, |, +, -, Getting Input from Input Dialog Boxes Case Studies (Computing Mortgage, and Computing Changes) Style and Documentation Guidelines Syntax Errors, Runtime Errors, and Logic Errors
36
Introducing Programming with an Example
Example 2.1 Computing the Area of a Circle This program computes the area of the circle. ComputeArea Run
37
Identifiers An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. An identifier cannot be a reserved word. (See Appendix A, “Java Keywords,” for a list of reserved words). An identifier cannot be true, false, or null. An identifier can be of any length.
38
Variables // Compute the first area radius = 1.0;
area = radius*radius* ; System.out.println("The area is “ + area + " for radius "+radius); // Compute the second area radius = 2.0;
39
Declaring Variables int x; // Declare x to be an // integer variable;
double radius; // Declare radius to // be a double variable; char a; // Declare a to be a // character variable;
40
Assignment Statements
x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a;
41
Declaring and Initializing in One Step
int x = 1; double d = 1.4; float f = 1.4; Is this statement correct?
42
Constants final datatype CONSTANTNAME = VALUE;
final double PI = ; final int SIZE = 3;
43
Numerical Data Types byte 8 bits short 16 bits int 32 bits
long bits float bits double bits
44
Operators +, -, *, /, and % 5/2 yields an integer 2.
5.0/2 yields a double value 2.5 5 % 2 yields 1 (the remainder of the division)
45
NOTE Calculations involving floating-point numbers are approximated because these numbers are not stored with complete accuracy. For example, System.out.println( ); displays , not 0.5, and System.out.println( ); displays , not 0.1. Integers are stored precisely. Therefore, calculations with integers yield a precise integer result.
46
Number Literals A literal is a constant value that appears directly in the program. For example, 34, 1,000,000, and 5.0 are literals in the following statements: int i = 34; long l = ; double d = 5.0;
47
Integer Literals An integer literal can be assigned to an integer variable as long as it can fit into the variable. A compilation error would occur if the literal were too large for the variable to hold. For example, the statement byte b = 1000 would cause a compilation error, because 1000 cannot be stored in a variable of the byte type. An integer literal is assumed to be of the int type, whose value is between -231 ( ) to 231–1 ( ). To denote an integer literal of the long type, append it with the letter L or l. L is preferred because l (lowercase L) can easily be confused with 1 (the digit one).
48
Floating-Point Literals
Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double type value. For example, 5.0 is considered a double value, not a float value. You can make a number a float by appending the letter f or F, and make a number a double by appending the letter d or D. For example, you can use 100.2f or 100.2F for a float number, and 100.2d or 100.2D for a double number.
49
Scientific Notation Floating-point literals can also be specified in scientific notation, for example, e+2, same as e2, is equivalent to , and e-2 is equivalent to E (or e) represents an exponent and it can be either in lowercase or uppercase.
50
Arithmetic Expressions
is translated to (3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
51
Shortcut Assignment Operators
Operator Example Equivalent += i+=8 i = i+8 -= f-=8.0 f = f-8.0 *= i*=8 i = i*8 /= i/=8 i = i/8 %= i%=8 i = i%8
52
Increment and Decrement Operators
53
Increment and Decrement Operators, cont.
54
Increment and Decrement Operators, cont.
Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to read. Avoid using these operators in expressions that modify multiple variables, or the same variable for multiple times such as this: int k = ++i + i.
55
Assignment Expressions and Assignment Statements
Prior to Java 2, all the expressions can be used as statements. Since Java 2, only the following types of expressions can be statements: variable op= expression; // Where op is +, -, *, /, or % ++variable; variable++; --variable; variable--;
56
Numeric Type Conversion
Consider the following statements: byte i = 100; long k = i*3+4; double d = i*3.1+k/2; int x = k; //(Wrong) long k = x; //(fine,implicit casting)
57
Type Casting double float long int short byte
58
Type Casting, cont. Implicit casting double d = 3; (type widening)
Explicit casting int i = (int)3.0; (type narrowing) What is wrong? int x = 5/2.0;
59
Character Data Type char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII) char letter = '\u0041'; (Unicode) char numChar = '\u0034'; (Unicode) Special characters char tab = ‘\t’;
60
Unicode Format Description Escape Sequence Unicode Backspace \b \u0008
Tab \t \u0009 Linefeed \n \u000a Carriage return \r \u000d
61
Appendix B: ASCII Character Set
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
62
ASCII Character Set, cont.
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
63
Casting between char and Numeric Types
int i = 'a'; // Same as int i = (int)'a'; char c = 97; // Same as char c = (char)97;
64
The boolean Type and Operators
boolean lightsOn = true; boolean lightsOn = false; boolean b = (1 > 2); && (and) (1 < x) && (x < 100) || (or) (lightsOn) || (isDayTime) ! (not) !(isStopped)
65
Comparison Operators Operator Name < less than
<= less than or equal to > greater than >= greater than or equal to == equal to != not equal to
66
Boolean Operators Operator Name ! not && and || or ^ exclusive or
67
Truth Table for Operator !
Operand !Operand true false false true
68
Truth Table for Operator &&
Operand1 Operand2 Operand1 && Operand2 false false false false true false true false false true true true
69
Truth Table for Operator ||
Operand1 Operand2 Operand1 || Operand2 false false false false true true true false true true true true
70
Truth Table for Operator ^
Operand1 Operand2 Operand1 ^ Operand2 false false false false true true true false true true true false
71
The & and | Operators &&: conditional AND operator
&: unconditional AND operator ||: conditional OR operator |: unconditional OR operator exp1 && exp2 (1 < x) && (x < 100) (1 < x) & (x < 100)
72
The & and | Operators If x is 1, what is x after this expression?
(x > 1) & (x++ < 10) (1 > x) && ( 1 > x++) How about (1 == x) | (10 > x++)? (1 == x) || (10 > x++)?
73
Operator Precedence How to evaluate 3 + 4 * 4 > 5 * (4 + 3) - ++i
74
Operator Precedence var++, var--
+, - (Unary plus and minus), ++var,--var (type) Casting ! (Not) *, /, % (Multiplication, division, and modulus) +, - (Binary addition and subtraction) <, <=, >, >= (Comparison) ==, !=; (Equality) & (Unconditional AND) ^ (Exclusive OR) | (Unconditional OR) && (Conditional AND) Short-circuit AND || (Conditional OR) Short-circuit OR =, +=, -=, *=, /=, %= (Assignment operator)
75
Operator Associativity
When two operators with the same precedence are evaluated, the associativity of the operators determines the order of evaluation. All binary operators except assignment operators are left-associative. a – b + c – d is equivalent to ((a – b) + c) – d Assignment operators are right-associative. Therefore, the expression a = b += c = 5 is equivalent to a = (b += (c = 5))
76
Operand Evaluation Order
The precedence and associativity rules specify the order of the operators, but do not specify the order in which the operands of a binary operator are evaluated. Operands are evaluated from left to right in Java. The left-hand operand of a binary operator is evaluated before any part of the right-hand operand is evaluated.
77
Operand Evaluation Order, cont.
If no operands have side effects that change the value of a variable, the order of operand evaluation is irrelevant. Interesting cases arise when operands do have a side effect. For example, x becomes 1 in the following code, because a is evaluated to 0 before ++a is evaluated to 1. int a = 0; int x = a + (++a); But x becomes 2 in the following code, because ++a is evaluated to 1, then a is evaluated to 1. int x = ++a + a;
78
Getting Input from Input Dialog Boxes
String string = JOptionPane.showInputDialog( null, “Prompt Message”, “Dialog Title”, JOptionPane.QUESTION_MESSAGE)); where x is a string for the prompting message and y is a string for the title of the input dialog box.
79
Convertting Strings to Integers
The input returned from the input dialog box is a string. If you enter a numeric value such as 123, it returns “123”. To obtain the input as a number, you have to convert a string into a number. To convert a string into an int value, you can use the static parseInt method in the Integer class as follows: int intValue = Integer.parseInt(intString); where intString is a numeric string such as “123”.
80
Convertting Strings to Doubles
To convert a string into a double value, you can use the static parseDouble method in the Double class as follows: double doubleValue =Double.parseDouble(doubleString); where doubleString is a numeric string such as “123.45”.
81
Example 2.2 Entering Input from Dialog Boxes
This program first prompts the user to enter a year as an int value and checks if it is a leap year, it then prompts you to enter a double value and checks if it is positive. A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400. InputDialogDemo Run
82
Example 2.3 Computing Mortgages
This program lets the user enter the interest rate, number of years, and loan amount and computes monthly payment and total payment. ComputeMortgage Run
83
Example 2.4 Computing Changes
This program lets the user enter the amount in decimal representing dollars and cents and output a report listing the monetary equivalent in single dollars, quarters, dimes, nickels, and pennies. Your program should report maximum number of dollars, then the maximum number of quarters, and so on, in this order. ComputeChange Run
84
Programming Style and Documentation
Appropriate Comments Naming Conventions Proper Indentation and Spacing Lines Block Styles
85
Appropriate Comments Include a summary at the beginning of the program to explain what the program does, its key features, its supporting data structures, and any unique techniques it uses. Include your name, class section, instruction, date, and a brief description at the beginning of the program.
86
Naming Conventions Choose meaningful and descriptive names.
Variables and method names: Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computeArea.
87
Naming Conventions, cont.
Class names: Capitalize the first letter of each word in the name. For example, the class name ComputeArea. Constants: Capitalize all letters in constants. For example, the constant PI.
88
Proper Indentation and Spacing
Indent two spaces. Spacing Use blank line to separate segments of the code.
89
Block Styles Use end-of-line style for braces.
90
Programming Errors Syntax Errors Runtime Errors Logic Errors
Detected by the compiler Runtime Errors Causes the program to abort Logic Errors Produces incorrect result
91
Compilation Errors public class ShowSyntaxErrors {
public static void main(String[] args) { i = 30; System.out.println(i+4); }
92
Runtime Errors public class ShowRuntimeErrors {
public static void main(String[] args) { int i = 1 / 0; }
93
Logic Errors public class ShowLogicErrors {
// Determine if a number is between 1 and 100 inclusively public static void main(String[] args) { // Prompt the user to enter a number String input = JOptionPane.showInputDialog(null, "Please enter an integer:", "ShowLogicErrors", JOptionPane.QUESTION_MESSAGE); int number = Integer.parseInt(input); // Display the result System.out.println("The number is between 1 and 100, " + "inclusively? " + ((1 < number) && (number < 100))); System.exit(0); }
94
Chapter 3 Control Statements
Selection Statements Using if and if...else Nested if Statements Using switch Statements Conditional Operator Repetition Statements Looping: while, do-while, and for Nested loops Using break and continue
95
Selection Statements if Statements switch Statements
Conditional Operators
96
if Statements Example: if (booleanExpression) { statement(s); }
if ((i > 0) && (i < 10)) { System.out.println("i is an " + "integer between 0 and 10");
97
Caution Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); { area = radius*radius*PI; System.out.println( "The area for the circle of radius " + radius + " is " + area); } This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style. Wrong
98
The if...else Statement if (booleanExpression) {
statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case;
99
if...else Example if (radius >= 0) { area = radius*radius*PI;
System.out.println("The area for the “ + “circle of radius " + radius + " is " + area); } else { System.out.println("Negative input");
100
Multiple Alternative if Statements
if (score >= 90) grade = ‘A’; else if (score >= 80) grade = ‘B’; if (score >= 70) grade = ‘C’; if (score >= 60) grade = ‘D’; grade = ‘F’; if (score >= 90) grade = ‘A’; else if (score >= 80) grade = ‘B’; else if (score >= 70) grade = ‘C’; else if (score >= 60) grade = ‘D’; else grade = ‘F’;
101
Note The else clause matches the most recent if clause in the same block. For example, the following statement int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); is equivalent to
102
Note, cont. Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) System.out.println("A"); } else System.out.println("B"); This statement prints B.
103
Nested if Statements Example 3.1 Using Nested if Statements
This program reads in number of years and loan amount and computes the monthly payment and total payment. The interest rate is determined by number of years. TestIfElse
104
switch Statements switch (year) { case 7: annualInterestRate = 7.25;
break; case 15: annualInterestRate = 8.50; case 30: annualInterestRate = 9.0; default: System.out.println( "Wrong number of years, enter 7, 15, or 30"); }
105
switch Statement Flow Chart
106
switch Statement Rules
The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. The value1, ..., and valueN must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression. (The case statements are executed in sequential order.) The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed.
107
switch Statement Rules, cont.
The default case, which is optional, can be used to perform actions when none of the specified cases is true. · The order of the cases (including the default case) does not matter. However, it is a good programming style to follow the logical sequence of the cases and place the default case at the end.
108
Caution Do not forget to use a break statement when one is needed. For example, the following code always displays Wrong number of years regardless of what numOfYears is. Suppose the numOfYears is 15. The statement annualInterestRate = 8.50 is executed, then the statement annualInterestRate = 9.0, and finally the statement System.out.println("Wrong number of years"). switch (numOfYears) { case 7: annualInterestRate = 7.25; case 15: annualInterestRate = 8.50; case 30: annualInterestRate = 9.0; default: System.out.println("Wrong number of years"); }
109
Conditional Operator if (x > 0) y = 1 else y = -1; is equivalent to
y = (x > 0) ? 1 : -1; Ternary operator Binary operator Unary operator
110
Conditional Operator if (num % 2 == 0)
System.out.println(num + “is even”); else System.out.println(num + “is odd”); System.out.println( (num % 2 == 0)? num + “is even” : num + “is odd”);
111
Conditional Operator, cont.
(booleanExp) ? exp1 : exp2
112
Repetitions while Loops do-while Loops for Loops break and continue
113
while Loop Flow Chart while (continuation-condition) { // loop-body; }
114
while Loop Flow Chart, cont.
int i = 0; while (i < 100) { System.out.println( "Welcome to Java!"); i++; }
115
Example 3.2: Using while Loops
TestWhile.java TestWhile
116
Caution Don’t use floating-point values for equality checking in a loop control. Since floating-point values are approximations, using them could result in imprecise counter values and inaccurate results. This example uses int value for data. If a floating-point type value is used for data, (data != 0) may be true even though data is 0. // data should be zero double data = Math.pow(Math.sqrt(2), 2) - 2; if (data == 0) System.out.println("data is zero"); else System.out.println("data is not zero");
117
do-while Loop do { // Loop body; } while (continue-condition);
118
for Loops for (initial-action; loop-continuation-condition; action-after-each-iteration) { //loop body; } int i = 0; while (i < 100) { System.out.println("Welcome to Java! ” + i); i++; Example: int i; for (i = 0; i < 100; i++) {
119
for Loop Flow Chart for (initial-action; loop-continuation-condition;
action-after-each-iteration) { //loop body; }
120
for Loop Example int i; for (i = 0; i<100; i++) {
System.out.println( "Welcome to Java"); }
121
for Loop Examples Examples for using the for loop:
Example 3.3: Using for Loops TestSum Example 3.4: Using Nested for Loops TestMulTable
122
Which Loop to Use? The three forms of loop statements, while, do, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. I recommend that you use the one that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition.
123
Caution Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below: for (int i=0; i<10; i++); { System.out.println("i is " + i); } Wrong
124
Caution, cont. Similarly, the following loop is also wrong:
int i=0; while (i<10); { System.out.println("i is " + i); i++; } In the case of the do loop, the following semicolon is needed to end the loop. do { } while (i<10); Wrong Correct
125
The break Keyword
126
The continue Keyword
127
Using break and continue
Examples for using the break and continue keywords: Example 3.5: TestBreak.java TestBreak Example 3.6: TestContinue.java TestContinue
128
Example 3.7 Finding the Sales Amount
You have just started a sales job in a department store. Your pay consists of a base salary and a commission. The base salary is $5,000. The scheme shown below is used to determine the commission rate. Sales Amount Commission Rate $0.01–$5, percent $5,000.01–$10, percent $10, and above 12 percent Your goal is to earn $30,000 in a year. Write a program that will find out the minimum amount of sales you have to generate in order to make $30,000. FindSalesAmount Run
129
Example 3.8 Displaying a Pyramid of Numbers
In this example, you will use nested loops to print the following output: 1 212 32123 Your program prints five lines. Each line consists of three parts. The first part comprises the spaces before the numbers; the second part, the leading numbers, such as on line 3; and the last part, the ending numbers, such as 2 3 on line 3. PrintPyramid Run
130
Example 3.9 Displaying Prime Numbers
This example displays the first 50 prime numbers in five lines, each of which contains 10 numbers. An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. The problem can be broken into the following tasks: For number = 2, 3, 4, 5, 6, ..., test whether the number is prime. Determine whether a given number is prime. Count the prime numbers. Print each prime number, and print 10 numbers per line. PrimeNumber Run
131
Chapter 4 Methods Introducing Methods Passing Parameters
Benefits of methods, Declaring Methods, and Calling Methods Passing Parameters Pass by Value Overloading Methods Ambiguous Invocation Scope of Local Variables Method Abstraction The Math Class Case Studies Recursion (Optional)
132
Introducing Methods Method Structure A method is a collection of statements that are grouped together to perform an operation.
133
Introducing Methods, cont.
parameter profile refers to the type, order, and number of the parameters of a method. method signature is the combination of the method name and the parameter profiles. The parameters defined in the method header are known as formal parameters. When a method is invoked, its formal parameters are replaced by variables or data, which are referred to as actual parameters.
134
Declaring Methods public static int max(int num1, int num2) {
if (num1 > num2) return num1; else return num2; }
135
Calling Methods Example 4.1 Testing the max method
This program demonstrates calling a method max to return the largest of the int values TestMax
136
Calling Methods, cont.
137
Calling Methods, cont.
138
CAUTION A return statement is required for a nonvoid method. The following method is logically correct, but it has a compilation error, because the Java compiler thinks it possible that this method does not return any value. public static int xMethod(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; } To fix this problem, delete if (n<0) in the code.
139
Passing Parameters public static void nPrintln(String message, int n) { for (int i = 0; i < n; i++) System.out.println(message); }
140
Pass by Value Example 4.2 Testing Pass by value
This program demonstrates passing values to the methods. TestPassByValue
141
Pass by Value, cont.
142
TestMethodOverloading
Overloading Methods Example 4.3 Overloading the max Method public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; } TestMethodOverloading
143
Ambiguous Invocation Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error.
144
Ambiguous Invocation public class AmbiguousOverloading {
public static void main(String[] args) { System.out.println(max(1, 2)); } public static double max(int num1, double num2) { if (num1 > num2) return num1; else return num2; public static double max(double num1, int num2) {
145
Scope of Local Variables
A local variable: a variable defined inside a method. Scope: the part of the program where the variable can be referenced. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used.
146
Scope of Local Variables, cont.
You can declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks. Thus, the following code is correct.
147
Scope of Local Variables, cont.
// Fine with no errors public static void correctMethod() { int x = 1; int y = 1; // i is declared for (int i = 1; i < 10; i++) { x += i; } // i is declared again y += i;
148
Scope of Local Variables, cont.
// With no errors public static void incorrectMethod() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { int x = 0; x += i; }
149
Method Abstraction You can think of the method body as a black box that contains the detailed implementation for the method.
150
Benefits of Methods Write once and reuse it any times.
Information hiding. Hide the implementation from the user. Reduce complexity.
151
The Math Class Class constants: Class methods: PI E
Trigonometric Methods Exponent Methods Rounding Methods min, max, abs, and random Methods
152
Trigonometric Methods
sin(double a) cos(double a) tan(double a) acos(double a) asin(double a) atan(double a)
153
Exponent Methods exp(double a) Returns e raised to the power of a.
log(double a) Returns the natural logarithm of a. pow(double a, double b) Returns a raised to the power of b. sqrt(double a) Returns the square root of a.
154
Rounding Methods double ceil(double x)
x rounded up to its nearest integer. This integer is returned as a double value. double floor(double x) x is rounded down to its nearest integer. This integer is returned as a double value. double rint(double x) x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double. int round(float x) Return (int)Math.floor(x+0.5). long round(double x) Return (long)Math.floor(x+0.5).
155
min, max, abs, and random max(a, b)and min(a, b) abs(a) random()
Returns the maximum or minimum of two parameters. abs(a) Returns the absolute value of the parameter. random() Returns a random double value in the range [0.0, 1.0).
156
Example 4.4 Computing Mean and Standard Deviation
Generate 10 random numbers and compute the mean and standard deviation ComputeMeanDeviation
157
Example 4.5 Obtaining Random Characters
Write the methods for generating random characters. The program uses these methods to generate 175 random characters between ‘!' and ‘~' and displays 25 characters per line. To find out the characters between ‘!' and ‘~', see Appendix B, “The ASCII Character Set.” RandomCharacter
158
Example 4.5 Obtaining Random Characters, cont.
Appendix B: ASCII Character Set
159
Case Studies Example 4.6 Displaying Calendars
The program reads in the month and year and displays the calendar for a given month of the year. PrintCalendar
160
Design Diagram
161
Recursion (Optional) Example 4.7 Computing Factorial factorial(0) = 1;
factorial(n) = n*factorial(n-1); ComputeFactorial
162
Example 4.7 Computing Factorial, cont.
163
Example 4.7 Computing Factorial, cont.
164
Fibonacci Numbers Example 4.8 Computing Finonacci Numbers
… f0 f1 fib(2) = fib(0) + fib(1); fib(0) = 0; fib(1) = 1; fib(n) = fib(n-2) + fib(n-1); n>=2
165
Fibonacci Numbers, cont
ComputeFibonacci
166
Fibonnaci Numbers, cont.
167
Towers of Hanoi Example 4.9 Solving the Towers of Hanoi Problem
Solve the towers of Hanoi problem. TowersOfHanoi
168
Towers of Hanoi, cont.
169
Chapter 5 Arrays Introducing Arrays
Declaring Array Variables, Creating Arrays, and Initializing Arrays Passing Arrays to Methods Copying Arrays Multidimensional Arrays Search and Sorting Methods
170
Introducing Arrays Array is a data structure that represents a collection of the same types of data. An Array of 10 Elements of type double
171
Declaring Array Variables
datatype[] arrayname; Example: double[] myList; datatype arrayname[]; double myList[];
172
Creating Arrays arrayName = new datatype[arraySize]; Example:
myList = new double[10]; myList[0] references the first element in the array. myList[9] references the last element in the array.
173
Declaring and Creating in One Step
datatype[] arrayname = new datatype[arraySize]; double[] myList = new double[10]; datatype arrayname[] = new datatype[arraySize]; double myList[] = new double[10];
174
The Length of Arrays arrayVariable.length For example,
Once an array is created, its size is fixed. It cannot be changed. You can find its size using arrayVariable.length For example, myList.length returns 10
175
Initializing Arrays This shorthand syntax must be in one statement.
Using a loop: for (int i = 0; i < myList.length; i++) myList[i] = i; Declaring, creating, initializing in one step: double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement.
176
Declaring, creating, initializing Using the Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;
177
CAUTION Using the shorthand notation, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. For example, the following is wrong: double[] myList; myList = {1.9, 2.9, 3.4, 3.5};
178
Example 5.1 Testing Arrays
Objective: The program receives 6 numbers from the keyboard, finds the largest number and counts the occurrence of the largest number entered from the keyboard. Suppose you entered 3, 5, 2, 5, 5, and 5, the largest number is 5 and its occurrence count is 4. TestArray Run
179
Example 5.2 Assigning Grades
Objective: read student scores (int) from the keyboard, get the best score, and then assign grades based on the following scheme: Grade is A if score is >= best–10; Grade is B if score is >= best–20; Grade is C if score is >= best–30; Grade is D if score is >= best–40; Grade is F otherwise. AssignGrade Run
180
Passing Arrays to Methods
Java uses pass by value to pass parameters to a method. There are important differences between passing a value of variables of primitive data types and passing arrays. For a parameter of a primitive type value, the actual value is passed. Changing the value of the local parameter inside the method does not affect the value of the variable outside the method. For a parameter of an array type, the value of the parameter contains a reference to an array; this reference is passed to the method. Any changes to the array that occur inside the method body will affect the original array that was passed as the argument.
181
Example 5.3 Passing Arrays as Arguments
Objective: Demonstrate differences of passing primitive data type variables and array variables. TestPassArray Run
182
Example 5.3, cont.
183
Example 5.4 Computing Deviation Using Arrays
Run
184
Example 5.5 Counting Occurrence of Each Letter
Generate 100 lowercase letters randomly and assign to an array of characters. Count the occurrence of each letter in the array. Find the mean and standard deviation of the counts. CountLettersInArray Run
185
Example 5.6 Copying Arrays
In this example, you will see that a simple assignment cannot copy arrays in the following program. The program simply creates two arrays and attempts to copy one to the other, using an assignment statement. TestCopyArray Run
186
Copying Arrays
187
Copying Arrays Using a loop: int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length]; for (int i = 0; i < sourceArrays.length; i++) targetArray[i] = sourceArray[i];
188
The arraycopy Utility arraycopy(sourceArray, src_pos, targetArray, tar_pos, length); Example: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
189
Multidimensional Arrays
Declaring Variables of Multidimensional Arrays and Creating Multidimensional Arrays int[][] matrix = new int[10][10]; or int matrix[][] = new int[10][10]; matrix[0][0] = 3; for (int i=0; i<matrix.length; i++) for (int j=0; j<matrix[i].length; j++) { matrix[i][j] = (int)(Math.random()*1000); } double[][] x;
190
Multidimensional Array Illustration
191
Declaring, Creating, and Initializing Using Shorthand Notations
You can also use a shorthand notation to declare, create and initialize a two-dimensional array. For example, int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; This is equivalent to the following statements: int[][] array = new int[4][3]; array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; array[2][0] = 7; array[2][1] = 8; array[2][2] = 9; array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
192
Lengths of Multidimensional Arrays
int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; array.length array[0].length array[1].length array[2].length
193
Ragged Arrays Each row in a two-dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as a ragged array. For example, int[][] matrix = { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} };
194
Example 5.7 Adding and Multiplying Two Matrices
Objective: Use two-dimensional arrays to create two matrices, and then add and multiply the two matrices. TestMatrixOperation Run
195
Example 5.7 (cont) Adding and Multiplying Two Matrices
cij = ai1b1j+ai2b2j+ai3b3j+ai4b4j+ai5b5j
196
Example 5.8 Grading Multiple-Choice Test
Objective: write a program that grades multiple-choice test. Grade Exam Run
197
Example 5.9 Calculating Total Scores
Objective: write a program that calculates the total score for students in a class. Suppose the scores are stored in a three-dimensional array named scores. The first index in scores refers to a student, the second refers to an exam, and the third refers to the part of the exam. Suppose there are 7 students, 5 exams, and each exam has two parts--the multiple-choice part and the programming part. So, scores[i][j][0] represents the score on the multiple-choice part for the i’s student on the j’s exam. Your program displays the total score for each student, . Run TotalScore
198
Searching Arrays Searching is the process of looking for a specific element in an array; for example, discovering whether a certain score is included in a list of scores. Searching, like sorting, is a common task in computer programming. There are many algorithms and data structures devoted to searching. In this section, two commonly used approaches are discussed, linear search and binary search.
199
Linear Search The linear search approach compares the key element, key, with each element in the array list[]. The method continues to do so until the key matches an element in the list or the list is exhausted without a match being found. If a match is made, the linear search returns the index of the element in the array that matches the key. If no match is found, the search returns -1.
200
Example 5.10 Testing Linear Search
Objective: Implement and test the linear search method by creating an array of 10 elements of int type randomly and then display this array. Prompt the user to enter a key for testing the linear search. LinearSearch Run
201
Binary Search For binary search to work, the elements in the array must already be ordered. Without loss of generality, assume that the array is in ascending order. e.g The binary search first compares the key with the element in the middle of the array. Consider the following three cases:
202
Binary Search, cont. · If the key is less than the middle element, you only need to search the key in the first half of the array. · If the key is equal to the middle element, the search ends with a match. · If the key is greater than the middle element, you only need to search the key in the second half of the array.
203
Binary Search, cont.
204
Example 5.11 Testing Binary Search
Objective: Implement and test the binary search method. The program first creates an array of 10 elements of int type. It displays this array and then prompts the user to enter a key for testing binary search. BinarySearch Run
205
Example 5.12 Using Arrays in Sorting
Objective: Use the selectionSort method to write a program that will sort a list of double floating-point numbers. int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted Sort it to produce 1, 2, 4, 5, 6, 8, 9 2, 9, 5, 4, 8, 1, 6 SelectionSort Run
206
Example 5.12: (Cont) Using Arrays in Sorting
int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted Find the largest element in myList and swap it with the last element in myList. 2, 9, 5, 4, 8, 1, 6 => 2, 6, 5, 4, 8, 1, 9 (size = 7) 2, 6, 5, 4, 8, 1 => 2, 6, 5, 4, 1, 8 (size = 6) 2, 6, 5, 4, 1 => 2, 1, 5, 4, 6 (size = 5) 2, 1, 5, 4 => 2, 1, 4, 5 2, 1, 4 => 2, 1, 4, 2, 1 => 1, 2 Sort it to produce 1, 2, 4, 5, 6, 8, 9
207
Exercise 5.5: Bubble Sort int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted Pass 1: 2, 5, 4, 8, 1, 6, 9 Pass 2: 2, 4, 5, 1, 6, 8, 9 Pass 3: 2, 4, 1, 5, 6, 8, 9 Pass 4: 2, 1, 4, 5, 6, 8, 9 Pass 5: 1, 2, 4, 5, 6, 8, 9 Pass 6: 1, 2, 4, 5, 6, 8, 9
208
Chapter 6 Objects and Classes
OO Programming Concepts Creating Objects and Object Reference Variables Differences between primitive data type and object type Automatic garbage collection Constructors Modifiers (public, private and static) Instance and Class Variables and Methods Scope of Variables Use the this Keyword Case Studies (Mortgage class and Count class)
209
OO Programming Concepts
210
Class and Objects
211
Class Declaration class Circle { double radius = 1.0;
double findArea(){ return radius * radius * ; }
212
Declaring Object Reference Variables
ClassName objectReference; Example: Circle myCircle;
213
Creating Objects Example:
objectReference = new ClassName(); Example: myCircle = new Circle(); The object reference is assigned to the object reference variable.
214
Declaring/Creating Objects in a Single Step
ClassName objectReference = new ClassName(); Example: Circle myCircle = new Circle();
215
Differences between variables of primitive Data types and object types
216
Copying Variables of Primitive Data Types and Object Types
217
Garbage Collection As shown in the previous figure, after the assignment statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer useful. This object is known as garbage. Garbage is automatically collected by JVM.
218
Garbage Collection, cont
TIP: If you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The Java VM will automatically collect the space if the object is not referenced by any variable.
219
Accessing Objects Referencing the object’s data: objectReference.data
myCircle.radius Invoking the object’s method: objectReference.method myCircle.findArea()
220
Example 6.1 Using Objects Objective: Demonstrate creating objects, accessing data, and using methods. TestCircle Run
221
Constructors Circle(double r) { radius = r; }
myCircle = new Circle(5.0); Constructors are a special kind of methods that are invoked to construct objects.
222
Constructors, cont. A constructor with no parameters is referred to as a default constructor. · Constructors must have the same name as the class itself. · Constructors do not have a return type—not even void. · Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.
223
Example 6.2 Using Classes from the Java Library
Objective: Demonstrate using classes from the Java library. Use the JFrame class in the javax.swing package to create two frames; use the methods in the JFrame class to set the title, size and location of the frames and to display the frames. TestFrame Run
224
Example 6.3 Using Constructors
Objective: Demonstrate the role of constructors and use them to create objects. TestCircleWithConstructors Run
225
Visibility Modifiers and Accessor Methods
By default, the class, variable, or data can be accessed by any class in the same package. public The class, data, or method is visible to any class in any package. private The data or methods can be accessed only by the declaring class. The get and set methods are used to read and modify private properties.
226
Example 6.4 Using the private Modifier and Accessor Methods
In this example, private data are used for the radius and the accessor methods getRadius and setRadius are provided for the clients to retrieve and modify the radius. TestCircleWithAccessors Run
227
Passing Objects to Methods
Passing by value (the value is the reference to the object) Example 6.5 Passing Objects as Arguments TestPassingObject Run
228
Passing Objects to Methods, cont.
229
Instance Variables, and Methods
Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class.
230
Class Variables, Constants, and Methods
Class variables are shared by all the instances of the class. Class methods are not tied to a specific object. Class constants are final variables shared by all the instances of the class.
231
Class Variables, Constants, and Methods, cont.
To declare class variables, constants, and methods, use the static modifier.
232
Class Variables, Constants, and Methods, cont.
233
Example 6.6 Using Instance and Class Variables and Method
Objective: Demonstrate the roles of instance and class variables and their uses. This example adds a class variable numOfObjects to track the number of Circle objects created. TestCircleWithStaticVariable Run
234
Scope of Variables The scope of instance and class variables is the entire class. They can be declared anywhere inside a class. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used.
235
The Keyword this Use this to refer to the current object.
Use this to invoke other constructors of the object.
236
Array of Objects Circle[] circleArray = new Circle[10]; An array of objects is actually an array of reference variables. So invoking circleArray[1].findArea() involves two levels of referencing as shown in the next figure. circleArray references to the entire array. circleArray[1] references to a Circle object.
237
Array of Objects, cont. Circle[] circleArray = new Circle[10];
238
Array of Objects, cont. Example 6.7: Summarizing the areas of the circles TotalArea Run
239
Class Abstraction Class abstraction means to separate class implementation from the use of the class. The creator of the class provides a description of the class and let the user know how the class can be used. The user of the class does not need to know how the class is implemented. The detail of implementation is encapsulated and hidden from the user.
240
Example 6.8 The Mortgage Class
TestMortgageClass Run
241
Example 6.9 The Count Class
Run TestVoteCandidate
242
Java API and Core Java classes
java.lang Contains core Java classes, such as numeric classes, strings, and objects. This package is implicitly imported to every Java program. java.awt Contains classes for graphics. java.applet Contains classes for supporting applets.
243
Java API and Core Java classes, cont.
java.io Contains classes for input and output streams and files. java.util Contains many utilities, such as date. java.net Contains classes for supporting network communications.
244
Java API and Core Java classes, cont.
java.awt.image Contains classes for managing bitmap images. java.awt.peer Platform-specific GUI implementation. Others: java.sql java.rmi
245
Chapter 7 Strings To process strings using the String class, the StringBuffer class, and the StringTokenizer class. To use the String class to process fixed strings. To use static methods in the Character class. To use the StringBuffer class to process flexible strings. To use the StringTokenizer class to extract tokens from a string. To use the command-line arguments.
246
The String Class Constructing a String:
String message = "Welcome to Java!" String message = new String("Welcome to Java!“); String s = new String(); Obtaining String length and Retrieving Individual Characters in a string String String Concatenation (concat) Substrings (substring(index), substring(start, end)) Comparisons (equals, compareTo) String Conversions Finding a Character or a Substring in a String Conversions between Strings and Arrays Converting Characters and Numeric Values to Strings
248
Constructing Strings Strings newString = new String(stringLiteral);
String message = new String("Welcome to Java!"); Since strings are used frequently, Java provides a shorthand notation for creating a string: String message = "Welcome to Java!";
249
Strings Are Immutable NOTE: A String object is immutable, whose contents cannot be changed. To improve efficiency and save memory, Java Virtual Machine stores two String objects into the same object, if the two String objects are created with the same string literal using the shorthand notation. Therefore, the shorthand notation is preferred to create strings.
250
Strings Are Immutable, cont.
NOTE: A string that is created using the shorthand notation is known as a canonical string. You can use the String’s intern method to return a canonical string, which is the same string that is created using the shorthand notation.
251
Examples String s = "Welcome to Java!";
String s1 = new String("Welcome to Java!"); String s2 = s1.intern(); System.out.println("s1 == s is " + (s1 == s)); System.out.println("s2 == s is " + (s2 == s)); System.out.println("s1 == s2 is " + (s1 == s2)); display s1 == s is false s2 == s is true s1 == s2 false
252
Finding String Length Finding string length using the length() method:
message = "Welcome"; message.length() (returns 7)
253
Retrieving Individual Characters in a String
Do not use message[0] Use message.charAt(index) Index starts from 0
254
String Concatenation String s3 = s1.concat(s2); String s3 = s1 + s2;
255
Extracting Substrings
String is an immutable class; its values cannot be changed individually. String s1 = "Welcome to Java"; String s2 = s1.substring(0, 11) + "HTML";
256
String Comparisons equals String s1 = "Welcome";
if (s1.equals(s2)){ // s1 and s2 have the same contents } if (s1 == s2) { // s1 and s2 have the same reference
257
String Comparisons, cont.
compareTo(Object object) String s1 = "Welcome"; String s2 = "welcome"; if (s1.compareTo(s2) > 0) { // s1 is greater than s2 } else if (s1.compareTo(s2 == 0) { // s1 and s2 have the same reference else // s1 is less than s2
258
String Conversions The contents of a string cannot be changed once the string is created. But you can convert a string to a new string using the following methods: toLowerCase toUpperCase trim replace(oldChar, newChar)
259
Finding a Character or a Substring in a String
"Welcome to Java!".indexOf('W')) returns 0. "Welcome to Java!".indexOf('x')) returns -1. "Welcome to Java!".indexOf('o', 5)) returns 9. "Welcome to Java!".indexOf("come")) returns 3. "Welcome to Java!".indexOf("Java", 5)) returns 11. "Welcome to Java!".indexOf("java", 5)) returns -1.
260
Convert Character and Numbers to Strings
The String class provides several static valueOf methods for converting a character, an array of characters, and numeric values to strings. These methods have the same name valueOf with different argument types char, char[], double, long, int, and float. For example, to convert a double value to a string, use String.valueOf(5.44). The return value is string consists of characters ‘5’, ‘.’, ‘4’, and ‘4’.
261
Example 7.1 Finding Palindromes
Objective: Checking whether a string is a palindrome: a string that reads the same forward and backward. Run CheckPalindrome
262
The Character Class
263
Examples charObject.compareTo(new Character('a')) returns 1
charObject.compareTo(new Character('b')) returns 0 charObject.compareTo(new Character('c')) returns -1 charObject.compareTo(new Character('d') returns –2 charObject.equals(new Character('b')) returns true charObject.equals(new Character('d')) returns false
264
Example 7.2 Counting Each Letter in a String
This example gives a program that counts the number of occurrence of each letter in a string. Assume the letters are not case-sensitive. Run CountEachLetter
265
The StringBuffer Class
The StringBuffer class is an alternative to the String class. In general, a string buffer can be used wherever a string is used. StringBuffer is more flexible than String. You can add, insert, or append new contents into a string buffer. However, the value of a string is fixed once the string is created.
267
StringBuffer Constructors
public StringBuffer() No characters, initial capacity 16 characters. public StringBuffer(int length) No characters, initial capacity specified by the length argument. public StringBuffer(String str) Represents the same sequence of characters as the string argument. Initial capacity 16 plus the length of the string argument.
268
Appending New Contents into a String Buffer
StringBuffer strBuf = new StringBuffer(); strBuf.append("Welcome"); strBuf.append(' '); strBuf.append("to"); strBuf.append("Java");
269
Example 7.3 Checking Palindromes Ignoring Non-alphanumeric Characters
This example gives a program that counts the number of occurrence of each letter in a string. Assume the letters are not case-sensitive. Run PalindromeIgnoreNonAlphanumeric
270
Example 7.4 Using StringBuffer for Output
This This example gives a program that prints the multiplication table created in Example 3.4, "Using Nested for Loops," from Chapter 3. Rather than print one number at a time, the program appends all the elements of the table into a string buffer. After the table is completely constructed in the string buffer, the program prints the entire string buffer on the console once. Run TestMulTableUsingStringBuffer
271
The StringTokenizer Class Constructors
StringTokenizer(String s, String delim, boolean returnTokens) StringTokenizer(String s, String delim) StringTokenizer(String s)
272
The StringTokenizer Class Methods
boolean hasMoreTokens() String nextToken() String nextToken(String delim)
273
Example 7.5 Testing StringTokenizer
Objective: Using a string tokenizer, retrieve words from a string and display them on the console. TestStringTokenizer Run
274
Command-Line Parameters
class TestMain { public static void main(String[] args) { ... } java TestMain arg0 arg1 arg2 ... argn
275
Processing Command-Line Parameters
In the main method, get the arguments from args[0], args[1], ..., args[n], which corresponds to arg0, arg1, ..., argn in the command line. Example 12.4
276
Example 7.6 Using Command-Line Parameters
Objective: Write a program that will perform binary operations on integers. The program receives three parameters: an operator and two integers. java Calculator + 2 3 Calculator java Calculator - 2 3 java Calculator / 2 3 Run java Calculator “*” 2 3
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.