Lập trình Java - Phần 1
Chia sẻ bởi Nguyễn Bùi Minh Tâm |
Ngày 19/03/2024 |
12
Chia sẻ tài liệu: Lập trình Java - Phần 1 thuộc Công nghệ thông tin
Nội dung tài liệu:
11/20/2009
Võ Phương Bình - ITFAC - DLU
1
Chapter 1: Introduction to Java
Chapter 2: Primitive Data Types and Operations
Chapter 3: Control Statements
Chapter 4: Methods
Chapter 5: Arrays
Part I: Fundamentals of Programming
11/20/2009
Võ Phương Bình - ITFAC - DLU
2
Chapter 1:
Introduction to Java
What Is Java?
Getting Started With Java Programming
Create, Compile and Running a Java Application
11/20/2009
Võ Phương Bình - ITFAC - DLU
3
What Is Java?
History
Applications of Java
Compare to C/C++/C#
Characteristics of Java
11/20/2009
Võ Phương Bình - ITFAC - DLU
4
History
James Gosling and Sun Microsystems (1983-1984)
Oak
In a project of electric device developing
Java, May 20, 1995, Sun World
HotJava
The first Java-enabled Web browser
JDK Evolutions
J2SE, J2ME, and J2EE
11/20/2009
Võ Phương Bình - ITFAC - DLU
5
JDK Versions
JDK 1.0 (1995)
JDK 1.1 (1996)
Java 2 SDK v 1.2 (JDK 1.2, 1998)
Java 2 SDK v 1.3 (JDK 1.3, 2000)
Java 2 SDK v 1.4 (JDK 1.4, 2002)
Java 5 SDK v 1.5 (JDK 1.5, 2005)
11/20/2009
Võ Phương Bình - ITFAC - DLU
6
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.
JDK Editions (2)
11/20/2009
Võ Phương Bình - ITFAC - DLU
7
Standard desktop &
workstation applications
Heavy duty server
systems
Small & memory
constrained devices
11/20/2009
Võ Phương Bình - ITFAC - DLU
8
Java IDE Tools
Eclipse
Borland Jbuilder
NetBean
Microsoft Visual J++, J#
WebGain Café
IBM Visual Age for Java
Forte by Sun Microsystems
11/20/2009
Võ Phương Bình - ITFAC - DLU
9
Applications of Java
JAVA
Mobile
Console
GUI
Network
Web
Database
RMI
Applet
11/20/2009
Võ Phương Bình - ITFAC - DLU
10
Console
11/20/2009
Võ Phương Bình - ITFAC - DLU
11
GUI (with JFC)
11/20/2009
Võ Phương Bình - ITFAC - DLU
12
Applet & Web
11/20/2009
Võ Phương Bình - ITFAC - DLU
13
Database & Web
11/20/2009
Võ Phương Bình - ITFAC - DLU
14
Mobile
11/20/2009
Võ Phương Bình - ITFAC - DLU
15
Compare to C/C++/C#
Similar to C/C++/C#
Difference:
Compiler
11/20/2009
Võ Phương Bình - ITFAC - DLU
16
Traditional Compiler (C/C++)
11/20/2009
Võ Phương Bình - ITFAC - DLU
17
Java Compiler
11/20/2009
Võ Phương Bình - ITFAC - DLU
18
Characteristics of Java
Java is simple
Java is object-oriented
Java is distributed
Java is robust
Java is secure
Java is architecture-neutral
Java is multithreaded
Java is dynamic
11/20/2009
Võ Phương Bình - ITFAC - DLU
19
Getting Started with Java Programming
A Simple Java Application
Compiling Programs
Executing Applications
11/20/2009
Võ Phương Bình - ITFAC - DLU
20
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!");
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
21
Creating and Compiling Programs
On command line
javac file.java
11/20/2009
Võ Phương Bình - ITFAC - DLU
22
Executing Applications
On command line
java classname
11/20/2009
Võ Phương Bình - ITFAC - DLU
23
Example
javac Welcome.java
java Welcome
output:...
11/20/2009
Võ Phương Bình - ITFAC - DLU
24
Compiling and Running a Program
Where are the files stored in the directory?
11/20/2009
Võ Phương Bình - ITFAC - DLU
25
Anatomy of a Java Program
Comments
Package
Reserved words
Modifiers
Statements
Blocks
Classes
Methods
The main method
Input processing
11/20/2009
Võ Phương Bình - ITFAC - DLU
26
Comments
Similar to C/C++
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 */.
11/20/2009
Võ Phương Bình - ITFAC - DLU
27
Package
The second line in the program (package chapter1;) specifies a package name, chapter1, for the class Welcome.
11/20/2009
Võ Phương Bình - ITFAC - DLU
28
Reserved Words
11/20/2009
Võ Phương Bình - ITFAC - DLU
29
Statements
Similar to C/C++, every statement in Java ends with a semicolon (;).
11/20/2009
Võ Phương Bình - ITFAC - DLU
30
Blocks
A pair of braces in a program forms a block that groups components of a program
11/20/2009
Võ Phương Bình - ITFAC - DLU
31
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
32
Methods
What is System.out.println "Welcome to Java!"? 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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
33
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;
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
34
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
35
The showMessageDialog Method
JOptionPane.showMessageDialog(null, "Welcome to Java!", "Example 1.2", JOptionPane.INFORMATION_MESSAGE);
11/20/2009
Võ Phương Bình - ITFAC - DLU
36
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
37
Input processing
Examples:
public static void main(String[] args) {
InputStreamReader io = new InputStreamReader(System.in);
BufferedReader console = new BufferedReader(io);
try{
System.out.print("Nhap chuoi str = ");
String str = console.readLine();
System.out.print(str);
}
catch(Exception ex){}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
38
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
39
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.
An identifier cannot be true, false, or
null.
An identifier can be of any length.
11/20/2009
Võ Phương Bình - ITFAC - DLU
40
Variables
// Compute the first area
radius = 1.0;
area = radius*radius*3.14159;
System.out.println("The area is “ + area + " for radius "+radius);
// Compute the second area
radius = 2.0;
area = radius*radius*3.14159;
System.out.println("The area is “ + area + " for radius "+radius);
11/20/2009
Võ Phương Bình - ITFAC - DLU
41
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;
11/20/2009
Võ Phương Bình - ITFAC - DLU
42
Assignment Statements
x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
a = `A`; // Assign `A` to a;
11/20/2009
Võ Phương Bình - ITFAC - DLU
43
Declaring and Initializing
in One Step
int x = 1;
double d = 1.4;
float f = 1.4;
11/20/2009
Võ Phương Bình - ITFAC - DLU
44
Constants
final datatype CONSTANTNAME = VALUE;
final double PI = 3.14159;
final int SIZE = 3;
11/20/2009
Võ Phương Bình - ITFAC - DLU
45
Numerical Data Types
byte 8 bits
short 16 bits
int 32 bits
long 64 bits
float 32 bits
double 64 bits
11/20/2009
Võ Phương Bình - ITFAC - DLU
46
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)
11/20/2009
Võ Phương Bình - ITFAC - DLU
47
NOTE
Calculations involving floating-point numbers are approximated because these numbers are not stored with complete accuracy.
For example,
System.out.println(1 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
displays 0.5000000000000001, not 0.5, and
System.out.println(1.0 - 0.9);
displays 0.09999999999999998, not 0.1.
Integers are stored precisely. Therefore, calculations with integers yield a precise integer result.
11/20/2009
Võ Phương Bình - ITFAC - DLU
48
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 = 1000000;
double d = 5.0;
11/20/2009
Võ Phương Bình - ITFAC - DLU
49
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 (-2147483648) to 231–1 (2147483647). To denote an integer literal of the long type, append it with the letter L or l.
11/20/2009
Võ Phương Bình - ITFAC - DLU
50
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
51
Scientific Notation
Floating-point literals can also be specified in scientific notation.
For example, 1.23456e+2, same as 1.23456e2, is equivalent to 123.456, and 1.23456e-2 is equivalent to 0.0123456.
E (or e) represents an exponent and it can be either in lowercase or uppercase.
11/20/2009
Võ Phương Bình - ITFAC - DLU
52
Arithmetic Expressions
is translated to
(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
11/20/2009
Võ Phương Bình - ITFAC - DLU
53
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
54
Increment and
Decrement Operators
11/20/2009
Võ Phương Bình - ITFAC - DLU
55
Increment and
Decrement Operators, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
56
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
57
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--;
11/20/2009
Võ Phương Bình - ITFAC - DLU
58
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)
11/20/2009
Võ Phương Bình - ITFAC - DLU
59
Type Casting
double
float
long
int
short
byte
11/20/2009
Võ Phương Bình - ITFAC - DLU
60
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;
11/20/2009
Võ Phương Bình - ITFAC - DLU
61
Character Data Type
char letter = `A`; (ASCII)
char numChar = `4`; (ASCII)
char letter = `u0041`; Unicode)
char numChar = `u0034`;(Unicode)
Special characters
char tab = ‘ ’;
11/20/2009
Võ Phương Bình - ITFAC - DLU
62
Unicode Format
Description Escape Sequence Unicode
Backspace u0008
Tab u0009
Linefeed u000a
Carriage return u000d
11/20/2009
Võ Phương Bình - ITFAC - DLU
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;
11/20/2009
Võ Phương Bình - ITFAC - DLU
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)
11/20/2009
Võ Phương Bình - ITFAC - DLU
65
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
11/20/2009
Võ Phương Bình - ITFAC - DLU
66
Boolean Operators
Operator Name
! not
&& and
|| or
^ exclusive or
11/20/2009
Võ Phương Bình - ITFAC - DLU
67
Truth Table for Operator !
Truth Table for Operator !
Operand !Operand
true false
false true
11/20/2009
Võ Phương Bình - ITFAC - DLU
68
Truth Table for Operator &&
Operand1 Operand2 Operand1 && Operand2
false false false
false true false
true false false
true true true
11/20/2009
Võ Phương Bình - ITFAC - DLU
69
Truth Table for Operator ||
Operand1 Operand2 Operand1 || Operand2
false false false
false true true
true false true
true true true
11/20/2009
Võ Phương Bình - ITFAC - DLU
70
Truth Table for Operator ^
Operand1 Operand2 Operand1 ^ Operand2
false false false
false true true
true false true
true true false
11/20/2009
Võ Phương Bình - ITFAC - DLU
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)
11/20/2009
Võ Phương Bình - ITFAC - DLU
72
The & and | Operators
If x is 1, what is x after this expression?
(x > 1) & (x++ < 10)
If x is 1, what is x after this expression?
(1 > x) && ( 1 > x++)
How about (1 == x) | (10 > x++)?
(1 == x) || (10 > x++)?
11/20/2009
Võ Phương Bình - ITFAC - DLU
73
Operator Precedence
How to evaluate
3 + 4 * 4 > 5 * (4 + 3) - ++i
11/20/2009
Võ Phương Bình - ITFAC - DLU
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)
11/20/2009
Võ Phương Bình - ITFAC - DLU
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))
11/20/2009
Võ Phương Bình - ITFAC - DLU
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
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 a = 0;
int x = ++a + a;
11/20/2009
Võ Phương Bình - ITFAC - DLU
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
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”.
11/20/2009
Võ Phương Bình - ITFAC - DLU
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”.
11/20/2009
Võ Phương Bình - ITFAC - DLU
81
Programming Style and Documentation
Appropriate Comments
Naming Conventions
Proper Indentation and Spacing Lines
Block Styles
11/20/2009
Võ Phương Bình - ITFAC - DLU
82
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
83
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
84
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
85
Proper Indentation and Spacing
Indentation
Indent two spaces.
Spacing
Use blank line to separate segments of the code.
11/20/2009
Võ Phương Bình - ITFAC - DLU
86
Block Styles
Use end-of-line style for braces.
11/20/2009
Võ Phương Bình - ITFAC - DLU
87
Programming Errors
Syntax Errors
Detected by the compiler
Runtime Errors
Causes the program to abort
Logic Errors
Produces incorrect result
11/20/2009
Võ Phương Bình - ITFAC - DLU
88
Compilation Errors
public class ShowSyntaxErrors {
public static void main(String[] args) {
i = 30;
System.out.println(i+4);
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
89
Runtime Errors
public class ShowRuntimeErrors {
public static void main(String[] args) {
int i = 1 / 0;
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
90
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);
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
91
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
92
Selection Statements
if Statements
switch Statements
Conditional Operators
11/20/2009
Võ Phương Bình - ITFAC - DLU
93
if Statements
if (booleanExpression) {
statement(s);
}
Example:
if ((i > 0) && (i < 10)) {
System.out.println("i is an " +
"integer between 0 and 10");
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
94
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
95
The if...else Statement
if (booleanExpression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
96
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");
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
97
Multiple Alternative if Statements
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’;
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’;
11/20/2009
Võ Phương Bình - ITFAC - DLU
98
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
int i = 1; int j = 2; int k = 3;
if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");
11/20/2009
Võ Phương Bình - ITFAC - DLU
99
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
100
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
101
switch Statements
switch (year) {
case 7: annualInterestRate = 7.25;
break;
case 15: annualInterestRate = 8.50;
break;
case 30: annualInterestRate = 9.0;
break;
default: System.out.println(
"Wrong number of years, enter 7, 15, or 30");
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
102
switch Statement Flow Chart
11/20/2009
Võ Phương Bình - ITFAC - DLU
103
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
104
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
105
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");
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
106
Conditional Operator
if (x > 0) y = 1
else y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
Ternary operator
Binary operator
Unary operator
11/20/2009
Võ Phương Bình - ITFAC - DLU
107
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”);
11/20/2009
Võ Phương Bình - ITFAC - DLU
108
Conditional Operator, cont.
(booleanExp) ? exp1 : exp2
11/20/2009
Võ Phương Bình - ITFAC - DLU
109
Repetitions
while Loops
do-while Loops
for Loops
break and continue
11/20/2009
Võ Phương Bình - ITFAC - DLU
110
while Loop Flow Chart
while (continuation-condition) {
// loop-body;
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
111
while Loop Flow Chart, cont.
int i = 0;
while (i < 100) {
System.out.println(
"Welcome to Java!");
i++;
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
112
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");
11/20/2009
Võ Phương Bình - ITFAC - DLU
113
do-while Loop
do {
// Loop body;
} while (continue-condition);
11/20/2009
Võ Phương Bình - ITFAC - DLU
114
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++) {
System.out.println("Welcome to Java! ” + i);
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
115
for Loop Flow Chart
for (initial-action;
loop-continuation-condition;
action-after-each-iteration) {
//loop body;
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
116
for Loop Example
int i;
for (i = 0; i<100; i++) {
System.out.println(
"Welcome to Java");
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
117
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
118
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
119
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.
int i=0;
do {
System.out.println("i is " + i);
i++;
} while (i<10);
Wrong
Correct
11/20/2009
Võ Phương Bình - ITFAC - DLU
120
The break Keyword
11/20/2009
Võ Phương Bình - ITFAC - DLU
121
The continue Keyword
11/20/2009
Võ Phương Bình - ITFAC - DLU
122
Chapter 4: Methods
Introducing Methods
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)
11/20/2009
Võ Phương Bình - ITFAC - DLU
123
Introducing Methods
Method Structure
A method is a collection of statements that are grouped together to perform an operation.
11/20/2009
Võ Phương Bình - ITFAC - DLU
124
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
125
Declaring Methods
public static int max(int num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
126
Calling Methods, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
127
Calling Methods, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
128
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
129
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
130
Pass by Value, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
131
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;
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
132
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
133
Ambiguous Invocation, cont
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) {
if (num1 > num2)
return num1;
else
return num2;
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
134
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
135
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
136
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
for (int i = 1; i < 10; i++) {
y += i;
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
137
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;
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
138
Method Abstraction
You can think of the method body as a black box that contains the detailed implementation for the method.
11/20/2009
Võ Phương Bình - ITFAC - DLU
139
Benefits of Methods
Write once and reuse it any times.
Information hiding. Hide the implementation from the user.
Reduce complexity.
11/20/2009
Võ Phương Bình - ITFAC - DLU
140
The Math Class
Class constants:
PI
E
Class methods:
Trigonometric Methods
Exponent Methods
Rounding Methods
min, max, abs, and random Methods
11/20/2009
Võ Phương Bình - ITFAC - DLU
141
Trigonometric Methods
sin(double a)
cos(double a)
tan(double a)
acos(double a)
asin(double a)
atan(double a)
11/20/2009
Võ Phương Bình - ITFAC - DLU
142
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
143
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).
11/20/2009
Võ Phương Bình - ITFAC - DLU
144
min, max, abs, and random
max(a, b)and min(a, b)
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).
11/20/2009
Võ Phương Bình - ITFAC - DLU
145
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
146
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
147
Declaring Array Variables
datatype[] arrayname;
Example:
double[] myList;
datatype arrayname[];
Example:
double myList[];
11/20/2009
Võ Phương Bình - ITFAC - DLU
148
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
149
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];
11/20/2009
Võ Phương Bình - ITFAC - DLU
150
The Length of Arrays
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
151
Initializing Arrays
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
152
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;
11/20/2009
Võ Phương Bình - ITFAC - DLU
153
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};
11/20/2009
Võ Phương Bình - ITFAC - DLU
154
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
155
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
156
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
157
Copying Arrays
11/20/2009
Võ Phương Bình - ITFAC - DLU
158
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];
11/20/2009
Võ Phương Bình - ITFAC - DLU
159
The arraycopy Utility
arraycopy(sourceArray, src_pos, targetArray, tar_pos, length);
Example:
System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
11/20/2009
Võ Phương Bình - ITFAC - DLU
160
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 for (int j=0; j {
matrix[i][j] = (int)(Math.random()*1000);
}
double[][] x;
11/20/2009
Võ Phương Bình - ITFAC - DLU
161
Multidimensional Array Illustration
11/20/2009
Võ Phương Bình - ITFAC - DLU
162
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;
11/20/2009
Võ Phương Bình - ITFAC - DLU
163
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
164
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}
};
Võ Phương Bình - ITFAC - DLU
1
Chapter 1: Introduction to Java
Chapter 2: Primitive Data Types and Operations
Chapter 3: Control Statements
Chapter 4: Methods
Chapter 5: Arrays
Part I: Fundamentals of Programming
11/20/2009
Võ Phương Bình - ITFAC - DLU
2
Chapter 1:
Introduction to Java
What Is Java?
Getting Started With Java Programming
Create, Compile and Running a Java Application
11/20/2009
Võ Phương Bình - ITFAC - DLU
3
What Is Java?
History
Applications of Java
Compare to C/C++/C#
Characteristics of Java
11/20/2009
Võ Phương Bình - ITFAC - DLU
4
History
James Gosling and Sun Microsystems (1983-1984)
Oak
In a project of electric device developing
Java, May 20, 1995, Sun World
HotJava
The first Java-enabled Web browser
JDK Evolutions
J2SE, J2ME, and J2EE
11/20/2009
Võ Phương Bình - ITFAC - DLU
5
JDK Versions
JDK 1.0 (1995)
JDK 1.1 (1996)
Java 2 SDK v 1.2 (JDK 1.2, 1998)
Java 2 SDK v 1.3 (JDK 1.3, 2000)
Java 2 SDK v 1.4 (JDK 1.4, 2002)
Java 5 SDK v 1.5 (JDK 1.5, 2005)
11/20/2009
Võ Phương Bình - ITFAC - DLU
6
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.
JDK Editions (2)
11/20/2009
Võ Phương Bình - ITFAC - DLU
7
Standard desktop &
workstation applications
Heavy duty server
systems
Small & memory
constrained devices
11/20/2009
Võ Phương Bình - ITFAC - DLU
8
Java IDE Tools
Eclipse
Borland Jbuilder
NetBean
Microsoft Visual J++, J#
WebGain Café
IBM Visual Age for Java
Forte by Sun Microsystems
11/20/2009
Võ Phương Bình - ITFAC - DLU
9
Applications of Java
JAVA
Mobile
Console
GUI
Network
Web
Database
RMI
Applet
11/20/2009
Võ Phương Bình - ITFAC - DLU
10
Console
11/20/2009
Võ Phương Bình - ITFAC - DLU
11
GUI (with JFC)
11/20/2009
Võ Phương Bình - ITFAC - DLU
12
Applet & Web
11/20/2009
Võ Phương Bình - ITFAC - DLU
13
Database & Web
11/20/2009
Võ Phương Bình - ITFAC - DLU
14
Mobile
11/20/2009
Võ Phương Bình - ITFAC - DLU
15
Compare to C/C++/C#
Similar to C/C++/C#
Difference:
Compiler
11/20/2009
Võ Phương Bình - ITFAC - DLU
16
Traditional Compiler (C/C++)
11/20/2009
Võ Phương Bình - ITFAC - DLU
17
Java Compiler
11/20/2009
Võ Phương Bình - ITFAC - DLU
18
Characteristics of Java
Java is simple
Java is object-oriented
Java is distributed
Java is robust
Java is secure
Java is architecture-neutral
Java is multithreaded
Java is dynamic
11/20/2009
Võ Phương Bình - ITFAC - DLU
19
Getting Started with Java Programming
A Simple Java Application
Compiling Programs
Executing Applications
11/20/2009
Võ Phương Bình - ITFAC - DLU
20
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!");
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
21
Creating and Compiling Programs
On command line
javac file.java
11/20/2009
Võ Phương Bình - ITFAC - DLU
22
Executing Applications
On command line
java classname
11/20/2009
Võ Phương Bình - ITFAC - DLU
23
Example
javac Welcome.java
java Welcome
output:...
11/20/2009
Võ Phương Bình - ITFAC - DLU
24
Compiling and Running a Program
Where are the files stored in the directory?
11/20/2009
Võ Phương Bình - ITFAC - DLU
25
Anatomy of a Java Program
Comments
Package
Reserved words
Modifiers
Statements
Blocks
Classes
Methods
The main method
Input processing
11/20/2009
Võ Phương Bình - ITFAC - DLU
26
Comments
Similar to C/C++
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 */.
11/20/2009
Võ Phương Bình - ITFAC - DLU
27
Package
The second line in the program (package chapter1;) specifies a package name, chapter1, for the class Welcome.
11/20/2009
Võ Phương Bình - ITFAC - DLU
28
Reserved Words
11/20/2009
Võ Phương Bình - ITFAC - DLU
29
Statements
Similar to C/C++, every statement in Java ends with a semicolon (;).
11/20/2009
Võ Phương Bình - ITFAC - DLU
30
Blocks
A pair of braces in a program forms a block that groups components of a program
11/20/2009
Võ Phương Bình - ITFAC - DLU
31
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
32
Methods
What is System.out.println "Welcome to Java!"? 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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
33
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;
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
34
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
35
The showMessageDialog Method
JOptionPane.showMessageDialog(null, "Welcome to Java!", "Example 1.2", JOptionPane.INFORMATION_MESSAGE);
11/20/2009
Võ Phương Bình - ITFAC - DLU
36
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
37
Input processing
Examples:
public static void main(String[] args) {
InputStreamReader io = new InputStreamReader(System.in);
BufferedReader console = new BufferedReader(io);
try{
System.out.print("Nhap chuoi str = ");
String str = console.readLine();
System.out.print(str);
}
catch(Exception ex){}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
38
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
39
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.
An identifier cannot be true, false, or
null.
An identifier can be of any length.
11/20/2009
Võ Phương Bình - ITFAC - DLU
40
Variables
// Compute the first area
radius = 1.0;
area = radius*radius*3.14159;
System.out.println("The area is “ + area + " for radius "+radius);
// Compute the second area
radius = 2.0;
area = radius*radius*3.14159;
System.out.println("The area is “ + area + " for radius "+radius);
11/20/2009
Võ Phương Bình - ITFAC - DLU
41
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;
11/20/2009
Võ Phương Bình - ITFAC - DLU
42
Assignment Statements
x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
a = `A`; // Assign `A` to a;
11/20/2009
Võ Phương Bình - ITFAC - DLU
43
Declaring and Initializing
in One Step
int x = 1;
double d = 1.4;
float f = 1.4;
11/20/2009
Võ Phương Bình - ITFAC - DLU
44
Constants
final datatype CONSTANTNAME = VALUE;
final double PI = 3.14159;
final int SIZE = 3;
11/20/2009
Võ Phương Bình - ITFAC - DLU
45
Numerical Data Types
byte 8 bits
short 16 bits
int 32 bits
long 64 bits
float 32 bits
double 64 bits
11/20/2009
Võ Phương Bình - ITFAC - DLU
46
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)
11/20/2009
Võ Phương Bình - ITFAC - DLU
47
NOTE
Calculations involving floating-point numbers are approximated because these numbers are not stored with complete accuracy.
For example,
System.out.println(1 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
displays 0.5000000000000001, not 0.5, and
System.out.println(1.0 - 0.9);
displays 0.09999999999999998, not 0.1.
Integers are stored precisely. Therefore, calculations with integers yield a precise integer result.
11/20/2009
Võ Phương Bình - ITFAC - DLU
48
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 = 1000000;
double d = 5.0;
11/20/2009
Võ Phương Bình - ITFAC - DLU
49
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 (-2147483648) to 231–1 (2147483647). To denote an integer literal of the long type, append it with the letter L or l.
11/20/2009
Võ Phương Bình - ITFAC - DLU
50
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
51
Scientific Notation
Floating-point literals can also be specified in scientific notation.
For example, 1.23456e+2, same as 1.23456e2, is equivalent to 123.456, and 1.23456e-2 is equivalent to 0.0123456.
E (or e) represents an exponent and it can be either in lowercase or uppercase.
11/20/2009
Võ Phương Bình - ITFAC - DLU
52
Arithmetic Expressions
is translated to
(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
11/20/2009
Võ Phương Bình - ITFAC - DLU
53
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
54
Increment and
Decrement Operators
11/20/2009
Võ Phương Bình - ITFAC - DLU
55
Increment and
Decrement Operators, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
56
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
57
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--;
11/20/2009
Võ Phương Bình - ITFAC - DLU
58
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)
11/20/2009
Võ Phương Bình - ITFAC - DLU
59
Type Casting
double
float
long
int
short
byte
11/20/2009
Võ Phương Bình - ITFAC - DLU
60
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;
11/20/2009
Võ Phương Bình - ITFAC - DLU
61
Character Data Type
char letter = `A`; (ASCII)
char numChar = `4`; (ASCII)
char letter = `u0041`; Unicode)
char numChar = `u0034`;(Unicode)
Special characters
char tab = ‘ ’;
11/20/2009
Võ Phương Bình - ITFAC - DLU
62
Unicode Format
Description Escape Sequence Unicode
Backspace u0008
Tab u0009
Linefeed u000a
Carriage return u000d
11/20/2009
Võ Phương Bình - ITFAC - DLU
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;
11/20/2009
Võ Phương Bình - ITFAC - DLU
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)
11/20/2009
Võ Phương Bình - ITFAC - DLU
65
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
11/20/2009
Võ Phương Bình - ITFAC - DLU
66
Boolean Operators
Operator Name
! not
&& and
|| or
^ exclusive or
11/20/2009
Võ Phương Bình - ITFAC - DLU
67
Truth Table for Operator !
Truth Table for Operator !
Operand !Operand
true false
false true
11/20/2009
Võ Phương Bình - ITFAC - DLU
68
Truth Table for Operator &&
Operand1 Operand2 Operand1 && Operand2
false false false
false true false
true false false
true true true
11/20/2009
Võ Phương Bình - ITFAC - DLU
69
Truth Table for Operator ||
Operand1 Operand2 Operand1 || Operand2
false false false
false true true
true false true
true true true
11/20/2009
Võ Phương Bình - ITFAC - DLU
70
Truth Table for Operator ^
Operand1 Operand2 Operand1 ^ Operand2
false false false
false true true
true false true
true true false
11/20/2009
Võ Phương Bình - ITFAC - DLU
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)
11/20/2009
Võ Phương Bình - ITFAC - DLU
72
The & and | Operators
If x is 1, what is x after this expression?
(x > 1) & (x++ < 10)
If x is 1, what is x after this expression?
(1 > x) && ( 1 > x++)
How about (1 == x) | (10 > x++)?
(1 == x) || (10 > x++)?
11/20/2009
Võ Phương Bình - ITFAC - DLU
73
Operator Precedence
How to evaluate
3 + 4 * 4 > 5 * (4 + 3) - ++i
11/20/2009
Võ Phương Bình - ITFAC - DLU
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)
11/20/2009
Võ Phương Bình - ITFAC - DLU
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))
11/20/2009
Võ Phương Bình - ITFAC - DLU
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
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 a = 0;
int x = ++a + a;
11/20/2009
Võ Phương Bình - ITFAC - DLU
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
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”.
11/20/2009
Võ Phương Bình - ITFAC - DLU
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”.
11/20/2009
Võ Phương Bình - ITFAC - DLU
81
Programming Style and Documentation
Appropriate Comments
Naming Conventions
Proper Indentation and Spacing Lines
Block Styles
11/20/2009
Võ Phương Bình - ITFAC - DLU
82
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
83
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
84
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
85
Proper Indentation and Spacing
Indentation
Indent two spaces.
Spacing
Use blank line to separate segments of the code.
11/20/2009
Võ Phương Bình - ITFAC - DLU
86
Block Styles
Use end-of-line style for braces.
11/20/2009
Võ Phương Bình - ITFAC - DLU
87
Programming Errors
Syntax Errors
Detected by the compiler
Runtime Errors
Causes the program to abort
Logic Errors
Produces incorrect result
11/20/2009
Võ Phương Bình - ITFAC - DLU
88
Compilation Errors
public class ShowSyntaxErrors {
public static void main(String[] args) {
i = 30;
System.out.println(i+4);
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
89
Runtime Errors
public class ShowRuntimeErrors {
public static void main(String[] args) {
int i = 1 / 0;
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
90
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);
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
91
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
92
Selection Statements
if Statements
switch Statements
Conditional Operators
11/20/2009
Võ Phương Bình - ITFAC - DLU
93
if Statements
if (booleanExpression) {
statement(s);
}
Example:
if ((i > 0) && (i < 10)) {
System.out.println("i is an " +
"integer between 0 and 10");
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
94
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
95
The if...else Statement
if (booleanExpression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
96
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");
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
97
Multiple Alternative if Statements
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’;
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’;
11/20/2009
Võ Phương Bình - ITFAC - DLU
98
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
int i = 1; int j = 2; int k = 3;
if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");
11/20/2009
Võ Phương Bình - ITFAC - DLU
99
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
100
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
101
switch Statements
switch (year) {
case 7: annualInterestRate = 7.25;
break;
case 15: annualInterestRate = 8.50;
break;
case 30: annualInterestRate = 9.0;
break;
default: System.out.println(
"Wrong number of years, enter 7, 15, or 30");
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
102
switch Statement Flow Chart
11/20/2009
Võ Phương Bình - ITFAC - DLU
103
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
104
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
105
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");
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
106
Conditional Operator
if (x > 0) y = 1
else y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
Ternary operator
Binary operator
Unary operator
11/20/2009
Võ Phương Bình - ITFAC - DLU
107
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”);
11/20/2009
Võ Phương Bình - ITFAC - DLU
108
Conditional Operator, cont.
(booleanExp) ? exp1 : exp2
11/20/2009
Võ Phương Bình - ITFAC - DLU
109
Repetitions
while Loops
do-while Loops
for Loops
break and continue
11/20/2009
Võ Phương Bình - ITFAC - DLU
110
while Loop Flow Chart
while (continuation-condition) {
// loop-body;
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
111
while Loop Flow Chart, cont.
int i = 0;
while (i < 100) {
System.out.println(
"Welcome to Java!");
i++;
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
112
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");
11/20/2009
Võ Phương Bình - ITFAC - DLU
113
do-while Loop
do {
// Loop body;
} while (continue-condition);
11/20/2009
Võ Phương Bình - ITFAC - DLU
114
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++) {
System.out.println("Welcome to Java! ” + i);
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
115
for Loop Flow Chart
for (initial-action;
loop-continuation-condition;
action-after-each-iteration) {
//loop body;
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
116
for Loop Example
int i;
for (i = 0; i<100; i++) {
System.out.println(
"Welcome to Java");
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
117
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
118
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
119
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.
int i=0;
do {
System.out.println("i is " + i);
i++;
} while (i<10);
Wrong
Correct
11/20/2009
Võ Phương Bình - ITFAC - DLU
120
The break Keyword
11/20/2009
Võ Phương Bình - ITFAC - DLU
121
The continue Keyword
11/20/2009
Võ Phương Bình - ITFAC - DLU
122
Chapter 4: Methods
Introducing Methods
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)
11/20/2009
Võ Phương Bình - ITFAC - DLU
123
Introducing Methods
Method Structure
A method is a collection of statements that are grouped together to perform an operation.
11/20/2009
Võ Phương Bình - ITFAC - DLU
124
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
125
Declaring Methods
public static int max(int num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
126
Calling Methods, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
127
Calling Methods, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
128
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
129
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
130
Pass by Value, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
131
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;
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
132
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
133
Ambiguous Invocation, cont
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) {
if (num1 > num2)
return num1;
else
return num2;
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
134
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
135
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
136
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
for (int i = 1; i < 10; i++) {
y += i;
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
137
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;
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
138
Method Abstraction
You can think of the method body as a black box that contains the detailed implementation for the method.
11/20/2009
Võ Phương Bình - ITFAC - DLU
139
Benefits of Methods
Write once and reuse it any times.
Information hiding. Hide the implementation from the user.
Reduce complexity.
11/20/2009
Võ Phương Bình - ITFAC - DLU
140
The Math Class
Class constants:
PI
E
Class methods:
Trigonometric Methods
Exponent Methods
Rounding Methods
min, max, abs, and random Methods
11/20/2009
Võ Phương Bình - ITFAC - DLU
141
Trigonometric Methods
sin(double a)
cos(double a)
tan(double a)
acos(double a)
asin(double a)
atan(double a)
11/20/2009
Võ Phương Bình - ITFAC - DLU
142
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
143
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).
11/20/2009
Võ Phương Bình - ITFAC - DLU
144
min, max, abs, and random
max(a, b)and min(a, b)
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).
11/20/2009
Võ Phương Bình - ITFAC - DLU
145
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
146
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
147
Declaring Array Variables
datatype[] arrayname;
Example:
double[] myList;
datatype arrayname[];
Example:
double myList[];
11/20/2009
Võ Phương Bình - ITFAC - DLU
148
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
149
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];
11/20/2009
Võ Phương Bình - ITFAC - DLU
150
The Length of Arrays
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
151
Initializing Arrays
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
152
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;
11/20/2009
Võ Phương Bình - ITFAC - DLU
153
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};
11/20/2009
Võ Phương Bình - ITFAC - DLU
154
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
155
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
156
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.
11/20/2009
Võ Phương Bình - ITFAC - DLU
157
Copying Arrays
11/20/2009
Võ Phương Bình - ITFAC - DLU
158
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];
11/20/2009
Võ Phương Bình - ITFAC - DLU
159
The arraycopy Utility
arraycopy(sourceArray, src_pos, targetArray, tar_pos, length);
Example:
System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
11/20/2009
Võ Phương Bình - ITFAC - DLU
160
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[i][j] = (int)(Math.random()*1000);
}
double[][] x;
11/20/2009
Võ Phương Bình - ITFAC - DLU
161
Multidimensional Array Illustration
11/20/2009
Võ Phương Bình - ITFAC - DLU
162
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;
11/20/2009
Võ Phương Bình - ITFAC - DLU
163
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
11/20/2009
Võ Phương Bình - ITFAC - DLU
164
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}
};
* Một số tài liệu cũ có thể bị lỗi font khi hiển thị do dùng bộ mã không phải Unikey ...
Người chia sẻ: Nguyễn Bùi Minh Tâm
Dung lượng: |
Lượt tài: 0
Loại file:
Nguồn : Chưa rõ
(Tài liệu chưa được thẩm định)