Bài giảng Phát triển phần mềm phân tán - Bài 2: Java syntax basics - Vũ Thị Hương Giang

21-Oct-16  
Objectives  
LESSON II.  
Java syntax basics  
•
Understand the Java syntax basics and their  
semantics for writing a program.  
Vu Thi Huong Giang  
SoICT (School of Information and  
Communication Technology)  
HUST (Hanoi University of Science  
and Technology)  
Structure of a Java program  
Content  
•
•
•
•
•
•
White space  
Separators  
Comments  
Identifiers and keywords  
Data types and literals  
Comment line arguments  
Program  
Package  
Book  
• Part  
•
–
Class  
Methods  
block  
Statement  
Expression  
Token  
–
Chapter  
section  
Paragraph  
Sentence  
Phrase  
Word  
•
•
–
–
»
»
•
•
•
•
I. White spaces  
II. Separators  
•
•
A whitespace is a space, a tab or a new line.  
It is used to separate the tokens in a source file  
and to improve readability  
• Help define the structure of program  
()  
parenthesis  
braces  
lists of parameters in method definitions and calls,  
precedence in expressions,  
type casts  
•
Java don’t require indentation rules  
{}  
block of code, local scope,  
class definitions, method definitions,  
automatically initialized arrays  
–
Example: following codes are equivalent  
[]  
;
brackets  
semicolon  
comma  
declaring array types,  
referring to array values brackets  
package firstpackage;  
public class SayHello  
public static void main(String[] args)  
// Display Chao! on the screen  
System.out.println ("Chao!");  
}
{
{
terminating statements,  
chain statements inside the “for” statement  
,
separating multiple identifiers in a variable declaration,  
chains statements in the test,  
expression of a for loop  
}
.
period (dot)  
colon  
separate package names from sub packages and classes,  
separating an object variable from its attribute or method  
package firstpackage; public class SayHello {public static  
void main(String[] args) // Display Chao! on the screen  
System.out.println ("Chao!");}}  
{
:
using after loop labels  
1
21-Oct-16  
III. Comment  
Comments  
•
Example  
Implementation comment:  
•
Comments are used to  
/** SayHello aims to display  
a
hello in  
Vietnamese on the standard output  
device.  
•
/* text */  
Ignore the text between /*  
and */  
// text  
–
give overviews of code  
*
–
*
–
provide additional information that is not readily  
available in the code itself  
*/  
class SayHello  
{
•
/* The program starts here.*/  
•
•
Comments should contain only information that is  
relevant to reading and understanding the  
program.  
–
Ignore all text from //to the  
end of the line  
public static void main(String[] args)  
{
// Display Chao! on the screen  
System.out.println(“Chao!");  
Documentation comment:  
/** documentation */  
}
•
Two kinds of comments:  
}
–
javadoc uses it to  
–
Implementation comment  
automatically generate  
software documentation  
–
Documentation comment  
javadoc tool  
•
Used to automatically generate the API  
documentation or the implementation documentation  
for a set of Java source files.  
IV. IDENTIFIERS AND  
KEYWORDS  
–
Parse the declarations and documentation comments  
–
Produce a corresponding set of HTML pages describing  
classes, interfaces, constructors, methods, and fields  
•
Frequent tags of javadoc:  
@param : Explanation of argument name  
–
–
@return : Explanation of the return value of the method of  
the object is described  
–
–
@exception class-name description : Explanation of the  
exception class-name that may be thrown by the method  
@see reference : Adds a "See Also" heading with a link or  
text entry that points to reference  
1. Identifier  
2. Naming rules  
3. Keywords  
1. Identifier  
2. Naming Rules  
•
Class: starts with upper case  
•
Java identifiers are tokens that represent names of  
variables, constants, methods, objects, classes, files written  
in Java language  
camel style (capitalize the first letter of each  
subsequent word)  
– ThisIsAnExampleOfClassName, Circle, Account, ..  
•
Features:  
–
Case-sensitive  
•
•
•
Method and variable: start with low case; camel style  
•
identifier Hello <> identifier hello <> identifier HELLO  
– thisIsAnExampleOfMethodName, setColor, isFull, ..  
–
–
–
No limit of length  
Not the same as Java keywords like class, public, void, etc.  
Not be true, false or null  
Basic data type constant : all capitals  
– MAX_LENGTH, TAX_VALUE ..  
Object constant: all low cases  
– Color.red, System.out ..  
•
Structure: Identifiers must begin with either a letter, an  
underscore “_” or a dollar sign “$”.  
–
Choose meaning and descriptive names  
Consistent naming in the whole program  
Letters: lower or upper case  
Subsequent characters: letters, digital numbers, etc.  
–
11  
12  
2
21-Oct-16  
3. Java keywords  
•
•
Keywords are predefined identifiers reserved by Java for a  
specific purpose.  
53 Java reserved words:  
V. DATA TYPES AND  
LITERALS  
abstract continue  
float  
for  
goto  
if  
native  
new  
null  
strictfp  
super  
switch  
synchronized  
this  
void  
volatile  
while  
assert  
boolean  
break  
byte  
default  
do  
double  
else  
package  
1. Data type categories  
a. Primitive data types  
b. Reference data types  
c. Literals  
implements private  
case  
enum  
import  
protected throw  
catch  
char  
class  
const  
extends  
false  
final  
finally  
instanceof public  
throws  
transient  
true  
int  
interface  
long  
return  
short  
static  
try  
2. Variables  
3. Type compatibility  
4. Strong typing  
5. Array  
You cannot use reserved words as names for your  
variables, classes, methods, etc.  
13  
1. Data type categories  
8 primitive data types  
Type  
byte  
short  
int  
Size  
Min value  
-128  
Max value  
127  
Default  
•
•
•
Primitive data types : 8  
Reference data types: 2  
Literals: 6  
Integer  
8 bits  
0
16 bits  
32 bits  
64 bits  
32 bits  
-32768  
32767  
0
-2,147,483,648  
-9 x 1018  
2,147,483,647  
9 x 1018  
0
long  
float  
0
-3.4 x 1038  
with 7  
significant digits digits  
-1.7 x 10308  
with 15  
3.4 x 1038  
with 7 significant  
0.0  
Floating  
point  
number  
double  
64 bits  
1.7 x 10308  
with 15  
0.0  
significant digits significant digits  
char  
16 bits  
\u0000 (0)  
false  
\uffff (65636)  
true  
\u0000  
false  
Unicode  
character  
boolean 1 bits  
Boolean  
values  
Composite data types  
(reference types)  
Literals  
•
Literals are constant value of 6 following types:  
•
Composite data type: constructed out of primitive  
data types and other composite date types.  
–
Integer literals  
•
•
•
Decimal: 100 or 100L (long type)  
Octal: 013 or 013L  
Hexadecimal: 0x52 or 0xFFl  
–
Object: value of every type  
–
Array: ordered list of values of the same data type  
•
•
Data of composite types don’t have well-defined  
standard size, so they are handled by reference.  
The default value of this type is null (no data  
should be referenced).  
–
Floating-point literals (default is double type)  
•
Decimal expression:  
0.23445, 0.655d (double type) or 0.23445F (float type)  
Exponent (scientific) expression: 6.02E13  
–
•
–
–
–
–
Boolean literals: true or false  
Character literals: ‘a’, ‘\t’, ‘\u3042’  
String literals: “Hello”, “Have a nice day!”  
Null literal: null(there no data should be referenced)  
18  
3
21-Oct-16  
2. Variables  
Assignment and initialization  
•
Assignment: associate a  
value to a variable  
•
A variable is a name  
that refers to a value  
located in memory  
Used to store data  
int myFirstNumber, mySecondNumber;  
myFirstNumber  
=
100;  
myFirstNumber*2;  
mySecondNumber  
=
variable  
= <expression>;  
•
Declaration:  
int myFirstNumber;  
int mySecondNumber;  
–
variable's name  
•
Initialization: give an initial  
value in the declaration  
–
the type of information  
that it will hold (data  
type)  
or  
int myThirdNumber  
int myFourthNumber  
= 10;  
–
Static: initialize with a literal  
int myFirstNumber, mySecondNumber;  
Multiple variables of the  
same type can be  
created in one  
–
Dynamic: initialize with an  
expression available at the  
moment  
=
myThirdNumber  
+ 5;  
declaration  
20  
Primitive variable  
Reference variable  
•
•
Reference: the memory address at which a composite data  
(object or array) is stored.  
Reference variable:  
•
•
A primitive variable is a variable of one of  
primitive data types  
A primitive variable stores the data in the actual  
memory location where it is  
int myFirstNumber;  
–
–
–
Store the address in the memory location  
Point to another memory location where the actual data is  
When a variable is referenced in a program, its current value is used  
myFirstNumber  
=
100;  
•
Example:  
String firstName  
= « Giang »;  
Memory address: 1001  
Memory address: 1500  
Memory address: 2000  
3. Type compatibility  
Type casting  
•
Integer types and floating-point types are compatible with  
each other  
Implicit type casting  
Explicit type casting  
•
•
•
Numeric types are not compatible with char or boolean  
char and booleanare not compatible with each other  
What happens if a value of type T1 is assigned to a variable  
of another type T2 ?  
T1 t1;  
•
When operating on values  
of different data types, the  
lower one is promoted to  
the type of the higher one.  
•
The type is put in  
parentheses in front of the  
value being converted.  
Example: if we want a  
floating-point result of the  
division, we can cast the  
variable total:  
•
•
Example:  
T2 t2 = t1;  
int intVal = 123;  
–
–
types T1 and T2 are incompatible not possible  
types T1 and T2 are compatible:  
• T1 and T2are the same  
long longVal = 213000L;  
int count, total;  
float result;  
longVal  
intVal  
=
intVal; //ok  
longVal; //na  
• T1 is larger than T2  
• T2 is larger than T1  
type casting  
=
result  
=
(float) total / count;  
24  
4
21-Oct-16  
4. Strong typing  
5. Array  
•
•
Every variable and expression has a type  
•
•
Array: ordered list of elements which hold values  
of the same data type  
Declaration:  
–
All assignments are checked for type-compatibility  
Every type is strictly defined  
data_type[] array_name;  
–
No automatic conversion of non-compatible, conflicting  
types  
data_type array_name[];  
•
Java compiler checks the type of all expressions  
and parameters  
•
•
Creation:  
data_type[] array_name = new data_type[SIZE];  
–
Any typing errors must be corrected for a successful  
data_type array_name[] = new data_type[SIZE];  
compilation  
Initialization:  
data_type[] array_name = {value1, value2,.., valuen};  
data_type array_name[] = {value1, value2,.., valuen};  
Example  
Array of reference type  
char c[] = new char[5];  
//creation  
•
Be aware that the array of the reference type is  
"array of the variables that refer to the objects",  
and that it is not "array of the objects".  
//initialization all at once  
char d[] {‘A’,’B’,‘1’,‘2’,‘3’};  
=
char e[] = new char [3]; // creation  
//assignment for each element  
String array[] = new String[5];  
e[0]  
=
‘0’; e[1]  
=
‘A’; e[2]  
=
‘X’; e[3]  
=
‘3’; e[4] = ‘3’;  
array[0] = “Chao”;  
c
d
e
0
1
2
3
4
\u0000  
0
1
2
3
4
‘A’  
0
1
2
3
4
‘0’  
\u0000  
‘B’  
‘1’  
‘2’  
‘3’  
‘A’  
‘X’  
‘3’  
‘3’  
\u0000  
\u0000  
\u0000  
index  
index  
index  
value  
value  
value  
28  
Multi-dimensional array  
VI. Comment line arguments  
•
Multidimensional arrays are implemented as arrays of  
arrays.  
•
When a java application is launched, the runtime  
system starts by calling the main()method of its main  
class  
•
Example  
•
•
The main()method then calls all methods found in his  
body to run this application  
Syntax:  
// integer array 512 x 128 elements  
int[][] twoD = new int[512][128];  
// character array  
char[][][] threeD  
// String array  
String[][] dogs  
8
=
x 16  
new char[8][16][24];  
rows x columns  
{{ "terry", "brown" },  
x 24  
public static void main(String args[]){  
4
=
2
// body  
}
{
{
{
"Kristin", "white" }  
"toby", "gray"},  
"fido", "black"}  
–
The runtime system passes arguments to the application  
through an array of Strings.  
•
Arguments can be passed from the command line  
};  
•
Any number of arguments can be accepted as configuration  
information of the application.  
29  
5
21-Oct-16  
Comment line arguments  
Example  
public class Echo {  
public static void main (String[] args) {  
•
Launching a java application without  
configuration information  
for (String s: args) { System.out.println(s); }  
}
}
prompt> java class_name  
>java Echo I got it  
•
Launching a java application with configuration  
information  
public class MyFavouriteBook {  
public static void main(String[] args) {  
System.out.println("My favourite book");  
System.out.println("Title: " + args[0]);  
System.out.println("Author: " + args[1]);  
System.out.println("Language: " + args[2]);  
System.out.println(  
prompt> java class_name arg[0] arg[1] .. arg[n]  
"Why do I love it ?" + args[3]);  
}
}
> java MyFavouriteBook A B C D  
Quiz: Javadoc  
Quiz 1+2 - Solution  
1. Explain the result  
javadoc –private Circle.java  
Show all class and member  
Given a Java source file named  
virtual_parse_stack.java  
javadoc -author -version Circle.java  
Include the tags @author and @version  
This file can be found at JDK installation folder  
C:\Program Files\Java\jdk1.7.0_03\src.zip  
\com\sun\java_cup\internal\runtime  
1. Run the following command for producing different  
documentations.  
javadoc –private virtual_parse_stack.java  
javadoc -author -version virtual_parse_stack.java  
2. Explain the obtained results  
3. Try to get the same results by using Eclipse.  
Quiz 3 - Solution  
Quiz: array  
4. Given a one dimension array of int type, write a  
program named OneDimensionArrayUsage that  
calculates its sum total (int) and its mean value  
(float)  
int data[] =  
{1, 80,22, 134, 0, 33, 93,45,33, 12} ;  
•
The expected output is  
sum: 453  
mean: 45.3  
5. Extend the program so that it displays the  
minimal and maximal value of the array.  
6
21-Oct-16  
Quiz 3 - Solution  
Quiz 4 - Solution  
public class Arithmetic  
{
public class OneDimensionArrayUsage  
{
public static void main(String[] args)  
//...  
{
public static void main(String[] args)  
int data[] {1, 80,22, 134, 0, 33, 93,45,33, 12};  
int sum 0; // Total sum  
{
=
int min  
= 0; int max = 0;  
=
for(int i=0; i<data.length; i++){  
// Calculation of total  
sum += data[i];  
for(int i=0; i<data.length; i++){  
// Calculation of total  
sum += data[i];  
}
if (data[i]  
if (data[i]  
}
<
>
min) min  
max) max  
=
=
data[i];  
data[i];  
float mean  
= sum / 10.0f; // Mean  
//...  
System.out.println(“Total sum :" + sum);  
System.out.println("Minimal value :"  
+
+
min);  
max);  
System.out.println(“Mean :" + mean);  
System.out.println("Maximal value :"  
}
}
}
}
37  
Review  
•
•
•
White space: separate the tokens  
Separators: help define the structure of program  
Comment: improve readability + auto generate  
documentation  
•
•
Identifier: naming  
Data types: every variable, literal and expression  
has a type  
•
Comment line arguments: pass arguments to the  
application through an array of Strings.  
7
pdf 7 trang Thùy Anh 20820 Free
Bạn đang xem tài liệu "Bài giảng Phát triển phần mềm phân tán - Bài 2: Java syntax basics - Vũ Thị Hương Giang", để tải tài liệu gốc về máy hãy click vào nút Download ở trên

File đính kèm:

  • pdfbai_giang_phat_trien_phan_mem_phan_tan_bai_2_java_syntax_bas.pdf