Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Programming Spring, 2013

Similar presentations


Presentation on theme: "Java Programming Spring, 2013"— Presentation transcript:

1 Java Programming Spring, 2013

2 Contents (Chapter 6 in Textbook)
Data Types(数据类型) Operators(运算符) Expressions(表达式) Arrays(数组) 包装器类 字符串类 名字含义 控制流语句 Chapter 4 Java Basic Grammar

3 Chapter 4 Java Basic Grammar
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

4 Chapter 4 Java Basic Grammar
Data in Java Primitive data types(基本数据类型) 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

5 Chapter 4 Java Basic Grammar

6 Chapter 4 Java Basic Grammar
Primitive Data Type 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

7 Chapter 4 Java Basic Grammar
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

8 Chapter 4 Java Basic Grammar
Type int(整数) A variable of type int may take values from – to Exceeding the range of legal values results in OVERFLOW(溢出), a run-time error. Base of the number: octal(8进制) — a leading 0(zero) hexadecimal(16进制) — a leading 0x or 0X decimal(10进制) Chapter 4 Java Basic Grammar

9 Chapter 4 Java Basic Grammar
Type long(长整数) A variable of type long may take values from – L to L. 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

10 Chapter 4 Java Basic Grammar
Type float(单精度浮点数) float :4个字节,32位 从 e-45到 e+38 (正值或负值的绝对值) 数字后必须用f指明,否则属于double型。 Chapter 4 Java Basic Grammar

11 Chapter 4 Java Basic Grammar
Type double (双精度浮点数) Type double represents “real” numbers approximately from -1.7  to 1.7  with 15 accurate significant digits(有效数字). Format of large or small values: =  1017 is e17 =  10-5 is e-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

12 Chapter 4 Java Basic Grammar
Type char(字符) Characters are individual symbols(单个字符), enclosed in single quotes(单括号) Examples: 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

13 Chapter 4 Java Basic Grammar
Type char(字符) JAVA中的字符为Unicode字符 双字节,16bits, 范围‘\u0000’~‘\uFFFF’ 字母:Unicode字符集中的任意一个都是字母。例: © 版权 “ 双引号 ½ 分式1/2 Δ 大写希腊字母delta ø 斜杠穿过字母o的符号 Chapter 4 Java Basic Grammar

14 Chapter 4 Java Basic Grammar
Unicode ASCII最初使用7位码表示大小写字母、数字0~9以及若干控制字符; ISO8859-Latin-1代码集--ASCII代码集被扩展到8位,即增加至128个字符,用于表示英文中不存在的各种西欧语言的字符。 Unicode是ISO标准16位字符集,支持65 536个不同的字符。其中大约有21 000个字符专门用于中文、日文和韩文的表意文字。ISO Latin-1代码集占用Unicode的前256个字符。 Chapter 4 Java Basic Grammar

15 Chapter 4 Java Basic Grammar
数据类型示例 int i = 178; long l = 8864L; (8864l) double d1 = ; double d2 = D; (37.266d) double d3 = 26.77e3; float f = F; (87.363f) char c = ‘d‘; boolean b1 = true; boolean b2 = false; Chapter 4 Java Basic Grammar

16 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

17 Chapter 4 Java Basic Grammar
转义字符 ‘\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

18 Chapter 4 Java Basic Grammar
转义字符示例 程序运行结果: E:\Java>java Test java 语言 jav语言 java 语言 \java语言\ 'java语言' "java语言" 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语言\""); } Chapter 4 Java Basic Grammar

19 Chapter 4 Java Basic Grammar
标识符命名规则 变量、函数、数组、对象、类和接口等等都需要命名,这些名称统称为标识符; Java中对于标识符的命名规则作了如下限制: 只能由英文字母、数字、下划线“_”和“$”符号组成; 必须以英文字母、“_”或“$”开头,即不能以数字开头; 除“_”和“$”以外,不能包含其它任何特殊字符; 不能与关键字冲突; 严格区分大小写。 Chapter 4 Java Basic Grammar

20 Chapter 4 Java Basic Grammar
Variables(变量) To store a value, we use a variable – a name(变量名) referring to the location in which the value is stored(变量名对应内存的位置). Fields(域) Local Variables (局部变量) 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

21 Chapter 4 Java Basic Grammar
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

22 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

23 final Variable (常量) final double PI=3.14; final int N=100;
为了修改方便,在程序中常把不允许修改的量用一个标识符表示,该标识符称为符号常量,又叫常量符号。 Java中一般只将类的成员定义为常量,称为类常量,而不在在方法中定义常量,定义常量的同时必须赋值。具体格式为: final <数据类型> <符号常量名>=<初值> 常量名一般大写。如: final double PI=3.14; final int N=100; Chapter 4 Java Basic Grammar

24 Chapter 4 Java Basic Grammar
Operators(操作符) Arithmetic(算术) Operations + addition - subtraction or negation * multiplication / division % remainder(取余) Increment & Decrement Operators(自增/自减运算符) ++ -- Chapter 4 Java Basic Grammar

25 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

26 Bit Manipulation Operators (按位逻辑运算符)
仅限于整数。 原理是:先把十进制(或N进制)转换成二进制,再分别同位进行与运算 & bitwise AND(按位与),可以把某些位置0 | bitwise inclusive OR(按位或),可以把某些位置1 ^ bitwise exclusive or (XOR)(按位异或 ),可以把某些位置反。 ~ 按位非 按位取反 >> 带符号右移 << 左移 >>> 不带符号右移 Chapter 4 Java Basic Grammar

27 Bit Manipulation Operators(按位逻辑运算符)
例如: 12&5(Java中位与运算是用&符号表示的),即: 12 = 1100 & 5 = 0101 = Chapter 4 Java Basic Grammar

28 Bit Manipulation Operators (按位逻辑运算符)
按位异或 运算符:两个操作数中,如果两个相应位相同,则结果为0,否则为1. 即:     0^0=0, 1^0=1, 0^1=1, 1^1=0 例如:     ^ = 按位异或 可以把某些位置反。 Chapter 4 Java Basic Grammar

29 加密 解密还原 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"); System.out.print(" "+a[i]); System.out.println("\n原文:\n"); for(int i=0;i<a.length;i++) { 加密 解密还原

30 Chapter 4 Java Basic Grammar

31 Chapter 4 Java Basic Grammar
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; boolean isShort = name instanceof Short; boolean isObject = name instanceof Object; //true //false //true Chapter 4 Java Basic Grammar

32 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

33 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

34 Chapter 4 Java Basic Grammar
字符串连接符: + Example: String + String (字符串 + 字符串) String boo=“boo”; String cry=boo+“hoo”; String + Other types(字符串 + 其它类型) int no=1001; String stuNo=“cuit”+no; // “boohoo” // “cuit1001” Chapter 4 Java Basic Grammar

35 Chapter 4 Java Basic Grammar
字符串连接符 + 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

36 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

37 Chapter 4 Java Basic Grammar
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

38 Chapter 4 Java Basic Grammar
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

39 Expression Data Type (表达式数据类型)
Every expression has a data type. Type decision rules are as follows: 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

40 Expression Data Type (表达式数据类型)
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

41 Data Type Conversions (数据类型转换)
1. Implicit Type Conversions (隐式/自动类型转换) 2. Explicit Type Casts (显式/强制类型转换) Chapter 4 Java Basic Grammar

42 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 int long float double char Chapter 4 Java Basic Grammar

43 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

44 Explicit Type Casts (显式类型转换)
指从计算机中占内存位(bit)数多的类型向占位数少的类型转换。 “possible loss of precision”(数据精度丢失)数据丢失可能造成高位数据的丢失。 凡是数据类型高的转换为数据类型低的都要进行强制类型转换,转换方法如下: (<类型>) <表达式> byte short int long float double char Chapter 4 Java Basic Grammar

45 Chapter 4 Java Basic Grammar
显型类型转换/强制类型转换 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); } Chapter 4 Java Basic Grammar

46 Chapter 4 Java Basic Grammar
显型类型转换/强制类型转换 class Test { public static void main(String args[]) { char c1 = ‘A’, c2; // ‘A’的ASCII值为65 int i; i = (int) c1 + 1; c2 = (char) i; System.out.println(c1 + c2); //??? System.out.println(c1 + “ ,” +c2); } Output: 131 A, B Chapter 4 Java Basic Grammar

47 数据类型隐式转换简单练习1: public class Autotraf{
public static void main(String arg[]) { char a='d'; int i=120; float f=1.2340f; double d= ; long l=7844L; System.out.println("i的值是"+i); i=a; i=120; System.out.println("f的值是"+f); f=i; System.out.println("d的值是"+d); d=i; System.out.println("l的值是"+l); l=i; }

48

49 数据类型显式转换简单练习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("intbyte:"+b+""+a); b=(int) c; System.out.println("doubleint:"+c+""+b); b=(byte) c; System.out.println("double  byte:"+c+""+b); ch=(char) -70; System.out.println("-70char:"+ch); }

50

51 Reference data types (引用数据类型)
和基本数据类型的数据一样,对象也是数据,其类型是对应的类。 Java将各种对象数据类型称为Reference(引用)数据类型。 基本数据类型的变量存放的是数据本身。 引用数据类型的变量存放的是对对象的引用,即:该变量表示的对象所存储的首地址。 Chapter 4 Java Basic Grammar

52 Chapter 4 Java Basic Grammar
栈内存: 栈内存中的空间一般都有名称,通过变量名访问其存储的数据。 堆内存(即动态内存分配): 堆内存中的空间一般没有名称,只能通过指针访问。 Java变量有两种类型 简单类型变量:保存在栈(stack)中 对象变量:保存在堆(heap)中,需要用new来分配空间 Chapter 4 Java Basic Grammar

53 Chapter 4 Java Basic Grammar
而除了8种原始数据类型以外,其它的任何数据都不可以在栈中分配,只能到堆中开辟空间,而在堆中分配的空间又只能通过指针访问; 通过指针访问堆内存的方式,在Java中被称作引用数据类型; 可以认为,Java中的引用就类似于指针,只是对指针进行了一定程度上的包装,避免了因直接操作指针而造成的数据意外损坏,从而导致程序错误的情况。 Chapter 4 Java Basic Grammar

54 所引用对象在堆中的32位地址 对象变量名 对象实际存储空间 栈内存 堆内存

55 Chapter 4 Java Basic Grammar
数据内存分配示例: int sum = 0; //简单数据 String s = “Hello World!”; //引用数据 sum s f789a1 Hello World! Chapter 4 Java Basic Grammar

56 Chapter 4 Java Basic Grammar
练习: 阅读和运行课件中所有的示例程序。 Chapter 4 Java Basic Grammar


Download ppt "Java Programming Spring, 2013"

Similar presentations


Ads by Google