Java 备忘单

开始

// hello.java
public class Hello {
  // main methord
  public static void main(String[] args)
  {
    // Output: Hello, world!
    System.out.println("Hello, world!");
  }
}
// 编译和运行
$ javac Hello.java
$ java Hello
Hello, world!

 变量

int num = 5;
float floatNum = 5.99f;
char letter = 'D';
boolean bool = true;
String site = "quickref.me";

原始数据类型 

数据类型尺寸默认范围
byte1 字节0-128 ~ 127
short2 字节0-2 15 ~ 2 15 -1
int4 字节0-2 31 ~ 2 31 -1
long8 字节0-2 63 ~ 2 63 -1
float4 字节0.0fN/A
double8 字节0.0dN/A
char2 字节\u00000 ~ 65535
booleanN/Afasletrue/false

 字符串

String first = "John";
String last = "Doe";
String name = first + " " + last;
System.out.println(name);

循环

String word = "QuickRef";
for (char c: word.toCharArray()) {
  System.out.print(c + "-");
}
// Outputs: Q-u-i-c-k-R-e-f-

数组 

char[] chars = new char[10];
chars[0] = 'a'
chars[1] = 'b'

String[] letters = {"A", "B", "C"};
int[] mylist = {100, 200};
boolean[] answers = {true, false};

交换 

int a = 1;
int b = 2;
System.out.println(a + " " + b); // 1 2

int temp = a;
a = b;
b = temp;
System.out.println(a + " " + b); // 2 1

类型转换 

// Widening
// byte<short<int<long<float<double
int i = 10;
long l = i;               // 10

// Narrowing 
double d = 10.02;
long l = (long)d;         // 10

String.valueOf(10);       // "10"
Integer.parseInt("10");   // 10
Double.parseDouble("10"); // 10.0

 条件句

int j = 10;

if (j == 10) {
  System.out.println("I get printed");
} else if (j > 10) {
  System.out.println("I don't");
} else {
  System.out.println("I also don't");
}

用户输入 

Scanner in = new Scanner(System.in);
String str = in.nextLine();
System.out.println(str);

int num = in.nextInt();
System.out.println(num);

 Java 字符串

// 基本的
String str1 = "value"; 
String str2 = new String("value");
String str3 = String.valueOf(123);

// 级联
String s = 3 + "str" + 3;     // 3str3
String s = 3 + 3 + "str";     // 6str
String s = "3" + 3 + "str";   // 33str
String s = "3" + "3" + "23";  // 3323
String s = "" + 3 + 3 + "23"; // 3323
String s = 3 + 3 + 23;        // 29

// 字符串生成器

StringBuilder sb = new StringBuilder(10);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
|   |   |   |   |   |   |   |   |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9

sb.append("QuickRef");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | R | e | f |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9

sb.delete(5, 9);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k |   |   |   |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9

sb.insert(0, "我的");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y |   | Q | u | i | c | k |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9

sb.append("!");
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y |   | Q | u | i | c | k | ! |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9
String s = 3 + "str" + 3;     // 3str3
String s = 3 + 3 + "str";     // 6str
String s = "3" + 3 + "str";   // 33str
String s = "3" + "3" + "23";  // 3323
String s = "" + 3 + 3 + "23"; // 3323
String s = 3 + 3 + 23;        // 29

 比较

String s1 = new String("QuickRef"); 
String s2 = new String("QuickRef"); 

s1 == s2          // false
s1.equals(s2)     // true

"AB".equalsIgnoreCase("ab")  // true

操作 

String str = "Abcd";

str.toUpperCase();     // ABCD
str.toLowerCase();     // abcd
str.concat("#");       // Abcd#
str.replace("b", "-"); // A-cd

"  abc ".trim();       // abc
"ab".toCharArray();    // {'a', 'b'}

信息

String str = "abcd";

str.charAt(2);       // c
str.indexOf("a")     // 0
str.indexOf("z")     // -1
str.length();        // 4
str.toString();      // abcd
str.substring(2);    // cd
str.substring(2,3);  // c
str.contains("c");   // true
str.endsWith("d");   // true
str.startsWith("a"); // true
str.isEmpty();       // false

不可变

String str = "hello";
str.concat("world");

// Outputs: hello
System.out.println(str);


String str = "hello";
String concat = str.concat("world");

// Outputs: helloworld
System.out.println(concat);

// 一旦创建不能修改,任何修改都会创建一个新的String

Java 数组

声明

int[] a1;
int[] a2 = {1, 2, 3};
int[] a3 = new int[]{1, 2, 3};

int[] a4 = new int[3];
a4[0] = 1;
a4[2] = 2;
a4[3] = 3;

调整 

int[] a = {1, 2, 3};
System.out.println(a[0]); // 1

a[0] = 9;
System.out.println(a[0]); // 9

System.out.println(a.length); // 3

循环(读取和修改)

int[] arr = {1, 2, 3};
for (int i=0; i < arr.length; i++) {
    arr[i] = arr[i] * 2;
    System.out.print(arr[i] + " ");
}
// Outputs: 2 4 6

循环(读取) 

String[] arr = {"a", "b", "c"};
for (int a: arr) {
    System.out.print(a + " ");
}
// Outputs: a b c 

多维数组

int[][] matrix = { {1, 2, 3}, {4, 5} };

int x = matrix[1][0];  // 4
// [[1, 2, 3], [4, 5]]
Arrays.deepToString(matrix)

for (int i = 0; i < a.length; ++i) {
  for(int j = 0; j < a[i].length; ++j) {
    System.out.println(a[i][j]);
  }
}
// Outputs: 1 2 3 4 5 6 7 

类型

char[] chars = {'b', 'a', 'c'};
Arrays.sort(chars);

// [a, b, c]
Arrays.toString(chars);

Java 条件

运算符 

1. 算术运算符

  • +:加法
  • -:减法
  • *:乘法
  • /:除法
  • %:取模(求余数)
  • ++:自增(增加 1)
  • --:自减(减少 1)

2. 关系运算符

  • ==:等于
  • !=:不等于
  • >:大于
  • <:小于
  • >=:大于等于
  • <=:小于等于

3. 逻辑运算符

  • &&:逻辑与(AND)
  • ||:逻辑或(OR)
  • !:逻辑非(NOT)

4. 位运算符

  • &:按位与
  • |:按位或
  • ^:按位异或
  • ~:按位取反
  • <<:左移位
  • >>:右移位(带符号)
  • >>>:右移位(无符号)

5. 赋值运算符

  • =:赋值
  • +=:加法赋值
  • -=:减法赋值
  • *=:乘法赋值
  • /=:除法赋值
  • %=:取模赋值
  • &=:按位与赋值
  • |=:按位或赋值
  • ^=:按位异或赋值
  • <<=:左移位赋值
  • >>=:右移位赋值(带符号)
  • >>>=:右移位赋值(无符号)

6. 三元条件运算符

  • ? ::条件表达式(三元运算符)

7. 其他运算符

  • instanceof:检查一个对象是否是特定类的实例
  • new:创建对象的实例
  • void:表示没有返回值
  • this:引用当前对象
  • super:引用父类

 if-else 语句

int k = 15;
if (k > 20) {
  System.out.println(1);
} else if (k > 10) {
  System.out.println(2);
} else {
  System.out.println(3);
}

 switch 语句

int month = 3;
String str;
switch (month) {
  case 1:
    str = "January";
    break;
  case 2:
    str = "February";
    break;
  case 3:
    str = "March";
    break;
  default:
    str = "Some other month";
    break;
}

// Outputs: Result March
System.out.println("Result " + str);

 三元运算符

int a = 10;
int b = 20;
int max = (a > b) ? a : b;

// Outputs: 20
System.out.println(max);

 Java 循环

For循环 

for (int i = 0; i < 10; i++) {
  System.out.print(i);
}
// Outputs: 0123456789

for (int i = 0,j = 0; i < 3; i++,j--) {
  System.out.print(j + "|" + i + " ");
}
// Outputs: 0|0 -1|1 -2|2

 For-each 循环

int[] numbers = {1,2,3,4,5};

for (int number: numbers) {
  System.out.print(number);
}
// Outputs: 12345

// 用于循环数组或列表

 While 循环

int count = 0;

while (count < 5) {
  System.out.print(count);
  count++;
}
// Outputs: 01234

 Do While 循环

int count = 0;

do{
  System.out.print(count);
  count++;
} while (count < 5);
// Outputs: 01234

 Continue

for (int i = 0; i < 5; i++) {
  if (i == 3) {
    continue;
  }
  System.out.print(i);
}
// Outputs: 01245

 Break

for (int i = 0; i < 5; i++) {
  System.out.print(i);
  if (i == 3) {
    break;
  }
}
// Outputs: 0123

 Java 集合框架

Java 集合 

集合接口可组织可排序线程安全可复制可为空
ArrayListListYNNYY
VectorListYNYYY
LinkedListList, DequeYNNYY
HashSetSetNNNNOne null
LinkedHashSetSetYNNNOne null
TreeSetSetYYNNN
HashMapMapNNNN (key)One null (key)
HashTableMapNNYN (key)N (key)
LinkedHashMapMapYNNN (key)One null (key)
TreeMapMapYYNN (key)N (key)
ArrayDequeDequeYNNYN
PriorityQueueQueueYNNYN

 数组列表

List<Integer> nums = new ArrayList<>();

// Adding
nums.add(2);
nums.add(5);
nums.add(8);

// Retrieving
System.out.println(nums.get(0));

// Indexed for loop iteration
for (int i = 0; i < nums.size(); i++) {
    System.out.println(nums.get(i));
}

nums.remove(nums.size() - 1);
nums.remove(0); // VERY slow

for (Integer value : nums) {
    System.out.println(value);
}

 哈希表

Map<Integer, String> m = new HashMap<>();
m.put(5, "Five");
m.put(8, "Eight");
m.put(6, "Six");
m.put(4, "Four");
m.put(2, "Two");

// Retrieving
System.out.println(m.get(6));

// Lambda forEach
m.forEach((key, value) -> {
    String msg = key + ": " + value;
    System.out.println(msg);
});

 哈希集

Set<String> set = new HashSet<>();
if (set.isEmpty()) {
    System.out.println("Empty!");
}

set.add("dog");
set.add("cat");
set.add("mouse");
set.add("snake");
set.add("bear");

if (set.contains("cat")) {
    System.out.println("Contains cat");
}

set.remove("cat");
for (String element : set) {
    System.out.println(element);
}

 数组Deque

Deque<String> a = new ArrayDeque<>();

// Using add()
a.add("Dog");

// Using addFirst()
a.addFirst("Cat");

// Using addLast()
a.addLast("Horse");

// [Cat, Dog, Horse]
System.out.println(a);

// Access element
System.out.println(a.peek());

// Remove element
System.out.println(a.pop());

 访问修饰符

修饰符子类全局
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN

常用表达

String text = "I am learning Java";
// Removing All Whitespace
text.replaceAll("\\s+", "");

// Splitting a String
text.split("\\|");
text.split(Pattern.quote("|"));

 文本注释

// I am a single line comment!
 
/*
And I am a 
multi-line comment!
*/

/**
 * This  
 * is  
 * documentation  
 * comment 
 */

 关键词

  1. abstract
  2. assert
  3. boolean
  4. break
  5. byte
  6. case
  7. catch
  8. char
  9. class
  10. const (Java中没有使用,保留以便未来使用)
  11. continue
  12. default
  13. do
  14. double
  15. else
  16. enum (从Java 5开始引入)
  17. extends
  18. final
  19. finally
  20. float
  21. for
  22. goto (Java中没有使用,保留以便未来使用)
  23. if
  24. implements
  25. import
  26. instanceof
  27. int
  28. interface
  29. long
  30. native
  31. new
  32. package
  33. private
  34. protected
  35. public
  36. return
  37. short
  38. static
  39. strictfp (Java中的浮点数精度修饰符)
  40. super
  41. switch
  42. synchronized
  43. this
  44. throw
  45. throws
  46. transient
  47. try
  48. void
  49. volatile
  50. while

 数学方法

方法描述
Math.max(a,b)a 和 b 的最大值
Math.min(a,b)a 和 b 的最小值
Math.abs(a)绝对值a
Math.sqrt(a)a 的平方根
Math.pow(a,b)a的b次方
Math.round(a)最接近的整数
Math.sin(ang)正弦
Math.cos(ang)ang的余弦
Math.tan(ang)ang 的切线
Math.asin(ang)ang 的反正弦
Math.log(a)a 的自然对数
Math.toDegrees(rad)角度 rad
Math.toRadians(deg)以弧度为单位的角度度

 try/catch/finally

try {
  // something
} catch (Exception e) {
  e.printStackTrace();
} finally {
  System.out.println("always printed");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

**之火

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值