Java程序设计 Java Programming Spring, 2013 Contents (Chapter 6 in Textbook) Data Types(数据类型) Operators(运算符) Expressions(表达式) Arrays(数组) 包装器类 字符串类 名字含义 控制流语句 Chapter 4 Java Basic Grammar 2/49 Data in Java Java is a “typed” language(强类型语言): Every data value must have a type; The type gives rules for what values are allowed, and what operations can be done with the values. For the computer, values of a certain type usually take a known amount of storage space in memory. Chapter 4 Java Basic Grammar 3/49 Data in Java 1. Primitive data types(基本数据类型) 2. A primitive type represents a single value, which cannot be decomposed. Reference data types(引用数据类型) The reference(引用) types are ① class(类) types ② interface (接口) types ③ array(数组) types Variables of these types can refer to objects(指向对 象) of the corresponding type. Chapter 4 Java Basic Grammar 4/49 Java的数据类型 Chapter 4 Java Basic Grammar 5/49 Primitive Data Type 1. 2. 3. 4. 5. 6. 7. 8. Java has a number of pre-defined primitive data types. boolean Boolean (logical) values, either true or false char 16-bit single character byte 8-bit integers (signed) short 16-bit integers (signed) int 32-bit integers (signed) (e.g. 3) long 64-bit integers (signed) float 32-bit floating point double 64-bit floating point (e.g. 3.0) Chapter 4 Java Basic Grammar 6/49 Type Boolean A Boolean variable is one which can have only 2 possible values: true or false. Boolean variables are used when you need to do logical tests Example: “Is X greater than 3?” x > 3 Chapter 4 Java Basic Grammar 7/49 Type int(整数) A variable of type int may take values from –2147483648 to 2147483647. Exceeding the range of legal values results in OVERFLOW(溢出), a run-time error. Base of the number: 1. 2. 3. octal(8进制) — a leading 0(zero) hexadecimal(16进制) — a leading 0x or 0X decimal(10进制) Chapter 4 Java Basic Grammar 8/49 Type long(长整数) A variable of type long may take values from –9223372036854775808L to 9223372036854775807L. To indicate the difference between an int constant and a long constant, the character “L/l “ is appended. Example: 2 is of type int 2L is of type long Chapter 4 Java Basic Grammar 9/49 Type float(单精度浮点数) float :4个字节,32位 从1.40129846432481707e-45到 3.40282346638528860e+38 (正值或负值的绝对值) 数字后必须用f指明,否则属于double型。 Chapter 4 Java Basic Grammar 10/49 Type double (双精度浮点数) Type double represents “real” numbers approximately from -1.7 10308 to 1.7 10308 with 15 accurate significant digits(有效数字). Format of large or small values: 12345600000000000.0 = 0.123456 1017 is 0.123456e17 0.00000123456 = 0.123456 10-5 is 0.123456e-5 If the value of e is more negative than about -308, the result is UNDERFLOW, and the value will be replaced by zero. This happens quietly, and is not a run-time error. Chapter 4 Java Basic Grammar 11/49 Type char(字符) Characters are individual symbols(单个字符), enclosed in single quotes(单括号) Examples: 1. 2. 3. 4. 5. 6. letters of the alphabet (upper and lower case are distinct) 'A', 'a' punctuation symbol (标点符号),e.g. comma, period, question mark) single blank space parentheses '(', ')'; brackets '[', ']'; braces '{', '}' single digit ('0', '1', … '9') special characters such as '@', '$', '*', and so on. Chapter 4 Java Basic Grammar 12/49 Type char(字符) JAVA中的字符为Unicode字符 双字节,16bits, 范围‘\u0000’~‘\uFFFF’ 字母:Unicode字符集中的任意一个都是字母。例: © “ ½ Δ ø 版权 双引号 分式1/2 大写希腊字母delta 斜杠穿过字母o的符号 Chapter 4 Java Basic Grammar 13/49 Unicode ASCII最初使用7位码表示大小写字母、数字0~9以及若干 控制字符; ISO8859-Latin-1代码集--ASCII代码集被扩展到8位, 即增加至128个字符,用于表示英文中不存在的各种西欧语 言的字符。 Unicode是ISO标准16位字符集,支持65 536个不同的字符。 其中大约有21 000个字符专门用于中文、日文和韩文的表意 文字。ISO Latin-1代码集占用Unicode的前256个字符。 http://www.unicode.org/charts/ Chapter 4 Java Basic Grammar 14/49 数据类型示例 1. 2. 3. 4. 5. 6. 7. 8. 9. int i = 178; long l = 8864L; (8864l) double d1 = 37.266; double d2 = 37.266D; (37.266d) double d3 = 26.77e3; float f = 87.363F; (87.363f) char c = ‘d‘; boolean b1 = true; boolean b2 = false; Chapter 4 Java Basic Grammar 15/49 Special characters(转义字符) Some characters are treated specially because they cannot be typed easily, or have other interpretations in Java. The backslash(\,反斜杠) is used as an escape character(转义符): it signifies that the next character is not to have its “usual” meaning. E.g.: new-line character — '\n' tab character — '\t' single quote character — '\'' double quote character — '\"' backslash character — '\\‘ Chapter 4 Java Basic Grammar 16/49 转义字符 ‘\n’ -- new-line character (回车换行,另起一行并回到另起一 行的行首) ‘\r’-- Carriage return character(回车 ,回到当前行的行首) ‘\t’-- tab character (水平制表符,到下一个tab位置)、 ‘\’ ’-- single quote character (单引号)、 ‘\“ ’-- double quote character (双引号) ‘\\’ -- backslash character (反斜杠) ‘\b’ -- (退格)、 ‘\f ’-- (换页)、 Chapter 4 Java Basic Grammar 17/49 转义字符示例 程序运行结果: class Test { public static void main(String args[]){ System.out.println("java\n语言"); System.out.println("java\r语言"); System.out.println("java\b语言"); System.out.println("java\t语言"); System.out.println("\\java语言\\"); System.out.println("\'java语言\'"); System.out.println("\"java语言\""); } E:\Java>java Test java 语言 语言 jav语言 java 语言 \java语言\ 'java语言' "java语言" } Chapter 4 Java Basic Grammar 18/49 标识符命名规则 变量、函数、数组、对象、类和接口等等都需要命 名,这些名称统称为标识符; Java中对于标识符的命名规则作了如下限制: 只能由英文字母、数字、下划线“_”和“$”符号组成; 必须以英文字母、“_”或“$”开头,即不能以数字开头; 除“_”和“$”以外,不能包含其它任何特殊字符; 不能与关键字冲突; 严格区分大小写。 Chapter 4 Java Basic Grammar 19/49 Variables(变量) To store a value, we use a variable – a name(变 量名) referring to the location in which the value is stored(变量名对应内存的位置). 1. 2. Fields(域) Local Variables (局部变量) 3. can be declared anywhere within a block of statements; no default initialization value. Parameter Variables(传递参数变量) are declared in methods, constructors, or catch blocks; no explicit(清楚的) initializers. Chapter 4 Java Basic Grammar 20/49 Variables(变量) Variables must be declared before they can be used. A variable declaration has three parts: The type of the variable The name of the variable (Optional) Assign an initial value(初始值) to the variable. Example: int x = 3; Chapter 4 Java Basic Grammar 21/49 Assigning Values(赋值) to Variables The equals sign = is used to represent assigning a value to a variable. General form: <variable name> = <expression> ; Example: assume x and y are declared previously x = 3 + y; Chapter 4 Java Basic Grammar 22/49 final Variable (常量) 为了修改方便,在程序中常把不允许修改的量用一个标识符 表示,该标识符称为符号常量,又叫常量符号。 Java中一般只将类的成员定义为常量,称为类常量,而不 在在方法中定义常量,定义常量的同时必须赋值。具体格式 为: final <数据类型> <符号常量名>=<初值> 常量名一般大写。如: final double PI=3.14; final int N=100; Chapter 4 Java Basic Grammar 23/49 Operators(操作符) Arithmetic(算术) Operations + addition subtraction or negation * multiplication / division % remainder(取余) Increment & Decrement Operators(自增/自减运算符) ++ -Chapter 4 Java Basic Grammar 24/49 Logical Operators (逻辑运算符) Relational & Equality Operators (关系运算符) > greater than >= greater than or equal to < less than <= less than or equal to == equal to != not equal to ! --logical negation(逻辑非),单目运算符, 即只有一个操作数 &&--conditional AND(逻辑与) ||--conditional OR(逻辑或) &&和||的短路规则 如果从第一个操作数就已经可以断定出表达式结果,就自动不再计算 第二个操作数。 Chapter 4 Java Basic Grammar 25/49 Bit Manipulation Operators (按位逻辑运算符) 仅限于整数。 原理是:先把十进制(或N进制)转换成二进制,再分别 同位进行与运算 1. 2. 3. 4. & | ^ 置反。 ~ >> << >>> bitwise AND(按位与),可以把某些位置0 bitwise inclusive OR(按位或),可以把某些位置1 bitwise exclusive or (XOR)(按位异或 ),可以把某些位 按位非 按位取反 带符号右移 左移 不带符号右移 Chapter 4 Java Basic Grammar 26/49 Bit Manipulation Operators(按位 逻辑运算符) 例如: 12&5(Java中位与运算是用&符号表示的), 即: 12 = 1100 & 5 = 0101 -------------------= 0100 Chapter 4 Java Basic Grammar 27/49 Bit Manipulation Operators (按位逻辑运算符) 按位异或 运算符:两个操作数中,如果两个相应位 相同,则结果为0,否则为1. 即: 按位异 0^0=0, 1^0=1, 0^1=1, 1^1=0 或 可以 把某些 例如: 位置反。 ^ = 00101010 00010111 00111101 Chapter 4 Java Basic Grammar 28/49 class Secret { //Example:使用"异或"简单加密的实现 public static void main(String args[]) { char a[]={'金','木','水','火','土'}; char secret=‘z’; for(int i=0;i<a.length;i++) { a[i]=(char)(a[i]^secret); } System.out.println("密文:\n"); for(int i=0;i<a.length;i++) { System.out.print(" "+a[i]); } for(int i=0;i<a.length;i++) { a[i]=(char)(a[i]^secret); } } } 加密 解密 还原 System.out.println("\n原文:\n"); for(int i=0;i<a.length;i++) { System.out.print(" "+a[i]); } 29 Chapter 4 Java Basic Grammar 30/49 instanceof(对象判断运算符) instanceof: evaluates if a reference refers to an object that is an instance of a particular class or interface(判断一个引用数 据是否是某个类或接口的实例). Example: String name=“Java”;//声明变量 boolean isString = name instanceof String; //true boolean isShort = name instanceof Short; boolean isObject = name instanceof Object; Chapter 4 Java Basic Grammar //false //true 31/49 Conditional Operator(条件运算符) The Conditional Operator ?: ternary (three-operand, 三元) operator value = (userSetIt ? userValue : defaultValue); equivalent to: if (userSetIt) value = usersValue; else value = defaultValue; int a=5; a = (a>3?a+5:a-5); Chapter 4 Java Basic Grammar 32/49 String Concatenation Operator (字符串连接符): + You can use + to concatenate (连接) two strings. 使用规则: A + operator is a String concatenation when either operand to + is of type String or if the left-hand side of a += is a String; Chapter 4 Java Basic Grammar 33/49 字符串连接符: + Example: String + String (字符串 + 字符串) String boo=“boo”; // “boohoo” String cry=boo+“hoo”; String + Other types(字符串 + 其它类型) int no=1001; String stuNo=“cuit”+no; // “cuit1001” Chapter 4 Java Basic Grammar 34/49 字符串连接符 + Example: class Cancatenate { public static void main(String args[]){ System.out.println(1+2+"456"); System.out.println("1"+2+345); } } What is the output? Output: 3456 12345 Chapter 4 Java Basic Grammar 35/49 Precedence(优先) of Operators Operators are evaluated left-to-right, with the following precedence (all operators on the same line are treated equally): (Detail see Page 177) () (expression) [] (array subscript) . (object member) + – (to indicate positive or negative values) ! (not) * / % + - (for addition or subtraction of two values, concatenation) < > >= <= == != && || = (assignment to variable) Chapter 4 Java Basic Grammar 36/49 Expressions (表达式) An expression consists of operators and their operands(操作数), which are evaluated to yield(产生) a result; The result may be a variable or a value, or even void; Example: x + y + z Chapter 4 Java Basic Grammar 37/49 Expressions (表达式) Operands(操作数) to operators will be evaluated left-to-right. Except for the operators &&, ||, and ?:, every operand of an operator will be evaluated before the operation is performed; If evaluation of the left operand of a binary operator causes an exception, no part of the right-hand operand is evaluated. The evaluation stops as soon as an exception is encountered. Chapter 4 Java Basic Grammar 38/49 Expression Data Type (表达式数据类型) Every expression has a data type. Type decision rules are as follows: 1. 2. 3. If an arithmetic or bit manipulation operator is applied to integer values, the result of the expression is of type int unless one or both sides are long, in which case the result is long. The smaller byte and short integer are always promoted to int before evaluation. If either operand of an arithmetic operator is floating point, the operation is performed in floating-point arithmetic; Chapter 4 Java Basic Grammar 39/49 Expression Data Type (表达式数据类型) 4. 5. A + operator is a String concatenation when either operand to + is of type String or if the left-hand side of a += is a String; When used in an expression, a char value is converted to an int by setting the top 16 bits to zero. Example: Unicode character \uffff → integer 0x0000ffff Chapter 4 Java Basic Grammar 40/49 Data Type Conversions (数据类型转换) 1. Implicit Type Conversions (隐式/自动类型转换) 2. Explicit Type Casts (显式/强制类型转换) Chapter 4 Java Basic Grammar 41/49 Implicit Type Conversions (隐式/自动类型转换) 隐型类型转换:自动类型转换(系统完成) 原则:系统自动进行,在计算机中占内存位(bit)数少的 类型向占位数多的类型转换。 Widening conversion(扩展转换) — any numeric value can be assigned to any numeric variable whose type supports a larger range of values; byte short char int long float Chapter 4 Java Basic Grammar double 42/49 Implicit Type Conversions (隐式/自动类型转换) Example: byte j=60; short k=4; int l=31; long m=4l; long result=0l; //octal(8进制) result +=j-8; result *=k+2; result /=m+1; result -=l; result %=m; Chapter 4 Java Basic Grammar 43/49 Explicit Type Casts (显式类型转换) 强制类型转换(Cast) 指从计算机中占内存位(bit)数多的类型向占位数少的 类型转换。 “possible loss of precision”(数据精度丢失)数据丢失 可能造成高位数据的丢失。 凡是数据类型高的转换为数据类型低的都要进行强制类 型转换,转换方法如下: (<类型>) <表达式> byte short char int long float Chapter 4 Java Basic Grammar double 44/49 显型类型转换/强制类型转换 Example: class Test { public static void main(String args[]) { int a = 257; byte b = (byte)a; System.out.println("a=" + a); System.out.println("b=" + b); } } 257 1 00000000 00000000 00000001 00000001 00000001 Chapter 4 Java Basic Grammar 45/49 显型类型转换/强制类型转换 class Test { public static void main(String args[]) { char c1 = ‘A’, c2; // ‘A’的ASCII值为65 int i; Output: i = (int) c1 + 1; 131 c2 = (char) i; System.out.println(c1 + c2); //??? A, B System.out.println(c1 + “ ,” +c2); } } Chapter 4 Java Basic Grammar 46/49 数据类型隐式转换简单练习1: public class Autotraf{ public static void main(String arg[]) { char a='d'; int i=120; float f=1.2340f; double d=45.6000; long l=7844L; System.out.println("i的值是"+i); i=a; System.out.println("i的值是"+i); i=120; System.out.println("f的值是"+f); f=i; System.out.println("f的值是"+f); System.out.println("d的值是"+d); d=i; System.out.println("d的值是"+d); System.out.println("l的值是"+l); l=i; System.out.println("l的值是"+l); } } 47 48 数据类型显式转换简单练习2: public class Presstraf{ public static void main(String arg[]) { char ch, chinaword='你'; byte a; int b=325; double c=346.73; System.out.println("汉字你在unicode表中顺序:"+(int)chinaword); System.out.println("unicode表中325位置上字符为:"+(char)b); a=(byte) b; System.out.println("int byte:"+b+" "+a); b=(int) c; System.out.println("double int:"+c+" "+b); b=(byte) c; System.out.println("double byte:"+c+" "+b); ch=(char) -70; System.out.println("-70 char:"+ch); } 49 } 50 Reference data types (引用数据类型) 和基本数据类型的数据一样,对象也是数据,其类 型是对应的类。 Java将各种对象数据类型称为Reference(引用)数据 类型。 基本数据类型的变量存放的是数据本身。 引用数据类型的变量存放的是对对象的引用,即: 该变量表示的对象所存储的首地址。 Chapter 4 Java Basic Grammar 51/49 Java中的内存分配 栈内存: 栈内存中的空间一般都有名称,通过变量名访问其存储的 数据。 堆内存(即动态内存分配): 堆内存中的空间一般没有名称,只能通过指针访问。 Java变量有两种类型 简单类型变量:保存在栈(stack)中 对象变量:保存在堆(heap)中,需要用new来分配 空间 Chapter 4 Java Basic Grammar 52/49 Java中的内存分配 Java中的8种原始数据类型,其变量都是在栈中分配空间; 而除了8种原始数据类型以外,其它的任何数据都不可以在 栈中分配,只能到堆中开辟空间,而在堆中分配的空间又只 能通过指针访问; 通过指针访问堆内存的方式,在Java中被称作引用数据类型; 可以认为,Java中的引用就类似于指针,只是对指针进行了 一定程度上的包装,避免了因直接操作指针而造成的数据意 外损坏,从而导致程序错误的情况。 Chapter 4 Java Basic Grammar 53/49 所引用对象在堆 中的32位地址 对象变量名 对象实际 存储空间 栈内存 堆内存 54 数据内存分配示例: int sum = 0; String s = “Hello World!”; sum 0 s f789a1 //简单数据 //引用数据 Hello World! Chapter 4 Java Basic Grammar 55/49 练习: 阅读和运行课件中所有的示例程序。 Chapter 4 Java Basic Grammar 56/49