Java核心技术卷I -- 第3章 Java基本程序设计结构
1. 强制退出
System.exit(0);
注释分三种://,/* */,/** */
2. 数据类型(8种)
2.1. 整形(允许负数)
int 4字节 32位
short 2字节 16位
long 8字节 64位
byte 1字节 8位
从Java7开始,加上前缀0b代表二进制,0b1001就是9
数字字面加下划线,1_000_000表示一百万
Java没有任何无符号类型(unsigned)
2.2. 浮点型
float 4字节 32位 数值后有一个后缀F,如果没有,默认为double类型
double 8字节 64位
2.3. char类型(表示Unicode编码)
转义写法: \b 退格,\t制表,\n换行,\r回车,\"双引号,\'单引号,\\反斜杠
可以使用Character类的isJavaIdentifierPart和isJavaIdentifierStart检测哪些Unicode字符属于Java中的“字母”,不能使用
2.4. boolean类型
6个实心箭头,表示无信息丢失转换;3个虚箭头,表示可能有精度损失转换。
3. 类常量static final
可以在一个类的多个方法中使用,常量名大写,定义在方法体外。
4. 枚举类型
enum Size{SMALL, MEDIUM, LARGE, EXTRA_LARGE};
Size s = Size.MEDIUM;
5. 比较字符串相等(equals)
一定不要使用==,不区分大小写使用equalsIgnoreCase,==只是比较两个字符串是否被放置在同一个位置。
if (str != null && str.length != 0) -- 检查字符串既不为null也不为空
str.charAt(1) -- 返回位置1的单元
StringBuilder.append() 连接字符串
6. java.util.Scanner
6.1. 读取输入行
Scanner in = new Scanner(System.in);
String firstName = in.next(); -- 读取一个单词,以空白符为分隔符
String name = in.nextLine();
int age = in.nextInt();
6.2. 从控制台读取密码
Console cons = System.console();
String userName = cons.readLine("User name: ");
Char[] passwd = cons.readPassword("Password: ");
6.3. 读写文件中的内容
String filename = "c:\\mydirectory\\myfile.txt";
Scanner scanner = new Scanner(new File(filename), "BIG5"); //编码方式
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
}
Scanner in = new Scanner(Paths.get("myfile.txt")); -- 根据给定的路径名构造一个path
PrintWriter out = new PrintWriter("myfile.txt"); -- 文件不存在,则创建该文件
String dir = System.getProperty("user.dir"); -- 找到系统路径位置
7. 类型转换
String to Integer: Integer.parseInt(String);
Integer to String: Integer.toString();
int to String: String.valueOf(int);
8. while循环
while(condition) statement; // if condition is false, do not execute statment
do statement while (condition); //至少执行一次
9. switch
switch (input) {}
case标签可以是以下几种:
a. char, byte, short, int
b. 枚举
Size sz = ...;
switch (sz)
{
case SMALL: // no need to use Size.SMALL
...
break;
}
c. JavaSE7,支持字符串
String input = ...;
switch (input.toLowerCase())
{
case "yes":
...
break;
}
10. break&continue
break: 跳出整个循环,或者break read_data;到某个标签
continue: 跳过循环剩余部分,进入下一次新循环
11. 大数字 BigInteger / BigDecimal
BigInteger a = BigInteger.valueOf(100);
BigInteger c = a.add(b);
12. 数组 - 允许数组长度为0
int[] a = new int[100];
int[] anonymous = {17, 20, 32, 48};
for each循环: 遍历整个数组中的元素,不需要下标值
for (int element: a)
System.out.println(element);
打印数组: Arrays.toString(a);
数组拷贝: System.arraycopy(from, fromIndex, to, toIndex, count);
数组排序: Arrays.sort(a);
打印二维数组: Arrays.deepToString(a);