Java 最常用函数

news/2024/7/8 2:02:58

Hello.java

public class Hello {

  // 主要方法

  public static void main(String[] args)

  {

    // 输出: Hello, world!

    System.out.println("Hello, world!");

  }

}

编译和运行

$ javac Hello.java

$ java Hello

Hello, world!

变量 Variables

int num = 5;

float floatNum = 5.99f;

char letter = 'D';

boolean bool = true;

String site = "quickref.me";

原始数据类型

数据类型

大小

默认

范围

byte

1 byte

0

-128 ^to^ 127

short

2 byte

0

-2^15^ ^to^ 2^15^-1

int

4 byte

0

-2^31^ ^to^ 2^31^-1

long

8 byte

0

-2^63^ ^to^ 2^63^-1

float

4 byte

0.0f

N/A

double

8 byte

0.0d

N/A

char

2 byte

\u0000

0 ^to^ 65535

boolean

N/A

false

true / false

字符串 Strings

String first = "John";

String last = "Doe";

String name = first + " " + last;

System.out.println(name);

查看: Strings

循环 Loops

String word = "QuickRef";

for (char c: word.toCharArray()) {

  System.out.print(c + "-");

}

// 输出: Q-u-i-c-k-R-e-f-

查看: Loops

数组 Arrays

char[] chars = new char[10];

chars[0] = 'a'

chars[1] = 'b'

String[] letters = {"A", "B", "C"};

int[] mylist = {100, 200};

boolean[] answers = {true, false};

查看: Arrays

Swap

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

Type Casting

// 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

条件语句 Conditionals

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");

}

查看: [Conditionals](#条件语句 Conditionals)

用户输入

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("Reference");


┌───┬───┬───┬───┬───┬───┬───┬───┬───┐

| R | e | f | e | r | e | n | c | e |

└───┴───┴───┴───┴───┴───┴───┴───┴───┘

0   1   2   3   4   5   6   7   8   9


sb.delete(3, 9);


┌───┬───┬───┬───┬───┬───┬───┬───┬───┐

| R | e | f |   |   |   |   |   |   |

└───┴───┴───┴───┴───┴───┴───┴───┴───┘

0   1   2   3   4   5   6   7   8   9


sb.insert(0, "My ");


┌───┬───┬───┬───┬───┬───┬───┬───┬───┐

| M | y |   | R | e | f |   |   |   |

└───┴───┴───┴───┴───┴───┴───┴───┴───┘

0   1   2   3   4   5   6   7   8   9


sb.append("!");


┌───┬───┬───┬───┬───┬───┬───┬───┬───┐

| M | y |   | R | e | f | ! |   |   |

└───┴───┴───┴───┴───┴───┴───┴───┴───┘

0   1   2   3   4   5   6   7   8   9

比较

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");

// 输出: hello

System.out.println(str);


String str = "hello";

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

// 输出: helloworld

System.out.println(concat);

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

Java 数组

申明 Declare

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;

修改 Modify

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] + " ");

}

// 输出: 2 4 6

Loop (Read)

String[] arr = {"a", "b", "c"};

for (int a: arr) {

    System.out.print(a + " ");

}

// 输出: a b c

Multidimensional Arrays

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]);

  }

}

// 输出: 1 2 3 4 5 6 7

Sort

char[] chars = {'b', 'a', 'c'};

Arrays.sort(chars);

// [a, b, c]

Arrays.toString(chars);

Java 条件语句

运算符

  • + (加法运算符(也用于字符串连接))
  • - (减法运算符)
  • * (乘法运算符)
  • / (分区运算符)
  • % (余数运算符)
  • = (简单赋值运算符)
  • ++ (增量运算符;将值增加 1)
  • -- (递减运算符;将值减 1)
  • ! (逻辑补码运算符;反转布尔值)

  • == (等于)
  • != (不等于)
  • > (比...更棒)
  • >= (大于或等于)
  • < (少于)
  • <= (小于或等于)

  • && 条件与
  • || 条件或
  • ?: 三元(if-then-else 语句的简写)

  • instanceof (将对象与指定类型进行比较)

  • ~ (一元按位补码)
  • << (签名左移)
  • >> (有符号右移)
  • >>> (无符号右移)
  • & (按位与)
  • ^ (按位异或)
  • | (按位包含 OR)

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;

}

// 输出: Result March

System.out.println("Result " + str);

三元运算符

int a = 10;

int b = 20;

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

// 输出: 20

System.out.println(max);

Java 循环

For 循环

for (int i = 0; i < 10; i++) {

  System.out.print(i);

}

// 输出: 0123456789


for (int i = 0,j = 0; i < 3; i++,j--) {

  System.out.print(j + "|" + i + " ");

}

// 输出: 0|0 -1|1 -2|2

增强的 For 循环

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

for (int number: numbers) {

  System.out.print(number);

}

// 输出: 12345

用于循环数组或列表

While 循环

int count = 0;

while (count < 5) {

  System.out.print(count);

  count++;

}

// 输出: 01234

Do While 循环

int count = 0;

do {

  System.out.print(count);

  count++;

} while (count < 5);

// 输出: 01234

继续声明

for (int i = 0; i < 5; i++) {

  if (i == 3) {

    continue;

  }

  System.out.print(i);

}

// 输出: 01245

中断语句

for (int i = 0; i < 5; i++) {

  System.out.print(i);

  if (i == 3) {

    break;

  }

}

// 输出: 0123

Java 框架搜集

Java 搜集

搜集

Interface

有序

已排序

线程安全

复制

Nullable

ArrayList

List

Y

N

N

Y

Y

Vector

List

Y

N

Y

Y

Y

LinkedList

List, Deque

Y

N

N

Y

Y

CopyOnWriteArrayList

List

Y

N

Y

Y

Y

HashSet

Set

N

N

N

N

One null

LinkedHashSet

Set

Y

N

N

N

One null

TreeSet

Set

Y

Y

N

N

N

CopyOnWriteArraySet

Set

Y

N

Y

N

One null

ConcurrentSkipListSet

Set

Y

Y

Y

N

N

HashMap

Map

N

N

N

N (key)

One null (key)

HashTable

Map

N

N

Y

N (key)

N (key)

LinkedHashMap

Map

Y

N

N

N (key)

One null (key)

TreeMap

Map

Y

Y

N

N (key)

N (key)

ConcurrentHashMap

Map

N

N

Y

N (key)

N

ConcurrentSkipListMap

Map

Y

Y

Y

N (key)

N

ArrayDeque

Deque

Y

N

N

Y

N

PriorityQueue

Queue

Y

N

N

Y

N

ConcurrentLinkedQueue

Queue

Y

N

Y

Y

N

ConcurrentLinkedDeque

Deque

Y

N

Y

Y

N

ArrayBlockingQueue

Queue

Y

N

Y

Y

N

LinkedBlockingDeque

Deque

Y

N

Y

Y

N

PriorityBlockingQueue

Queue

Y

N

Y

Y

N

ArrayList

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

// 添加

nums.add(2);

nums.add(5);

nums.add(8);

// 检索

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

// 为循环迭代编制索引

for (int i = 0; i < nums.size(); i++) {

    System.out.println(nums.get(i));

}

nums.remove(nums.size() - 1);

nums.remove(0); // 非常慢

for (Integer value : nums) {

    System.out.println(value);

}

HashMap

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");

// 检索

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

// Lambda forEach

m.forEach((key, value) -> {

    String msg = key + ": " + value;

    System.out.println(msg);

});

HashSet

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);

}

ArrayDeque

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

// 使用 add()

a.add("Dog");

// 使用 addFirst()

a.addFirst("Cat");

// 使用 addLast()

a.addLast("Horse");

// [Cat, Dog, Horse]

System.out.println(a);

// 访问元素

System.out.println(a.peek());

// 移除元素

System.out.println(a.pop());

杂项 Misc

访问修饰符

修饰符

Class

Package

Subclass

World

public

Y

Y

Y

Y

protected

Y

Y

Y

N

no modifier

Y

Y

N

N

private

Y

N

N

N

常用表达

String text = "I am learning Java";

// 删除所有空格

text.replaceAll("\\s+", "");

// 拆分字符串

text.split("\\|");

text.split(Pattern.quote("|"));

查看: Regex in java

注释 Comment

// 我是单行注释!

 

/*

而我是一个

多行注释!

*/

/**

  * 这个

  *

  * 文档

  * 注释

 */

关键字

  • abstract
  • continue
  • for
  • new
  • switch
  • assert
  • default
  • goto
  • package
  • synchronized
  • boolean
  • do
  • if
  • private
  • this
  • break
  • double
  • implements
  • protected
  • throw
  • byte
  • else
  • import
  • public
  • throws
  • case
  • enum
  • instanceof
  • return
  • transient
  • catch
  • extends
  • int
  • short
  • try
  • char
  • final
  • interface
  • static
  • void
  • class
  • finally
  • long
  • strictfp
  • volatile
  • const
  • float
  • native
  • super
  • while

数学方法

Math.max(a,b)

a 和 b 的最大值

Math.min(a,b)

a 和 b 的最小值

Math.abs(a)

绝对值

Math.sqrt(a)

a 的平方根

Math.pow(a,b)

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)

以度为单位的角度弧度

Math.toRadians(deg)

以弧度为单位的角度度

Try/Catch/Finally

try {

  // something

} catch (Exception e) {

  e.printStackTrace();

} finally {

  System.out.println("always printed");

}

另见

  • Java 官网 (java.com)


http://lihuaxi.xjx100.cn/news/405678.html

相关文章

装载问题 ——回溯法(Java)

装载问题 ——回溯法&#xff08;Java&#xff09; 文章目录装载问题 ——回溯法&#xff08;Java&#xff09;1、 问题描述1.1 装载问题1.2 转换问题2、算法设计2.1 可行性约束函数2.2 上界函数2.3 解空间树2.4 剪枝函数2.5 算法设计3、程序代码4、参考资料1、 问题描述 有一…

VUE 中防抖和节流真实项目的使用

概念 1. 防抖 防抖策略(debounce)&#xff1a;是当事件被触发后,延迟n秒后再执行回调函数,如果在这n秒内事件被再次触发,则重新计时. 好处是:它能够保证用户在频繁触发某些事件的时候,不会频繁的执行回调,只会被执行一次. 防抖的概念&#xff1a;如果有人进电梯&#xff08;触…

怎么把电脑硬盘文件恢复回来?跟着我这么做

电脑的硬盘数据丢失了&#xff0c;用了很多方法都没有办法找回来&#xff0c;电脑文件还能找回来吗&#xff1f;硬盘文件恢复要怎么操作&#xff1f;这时候就要寻求第三方数据恢复软件来恢复数据了。下面有详细的操作步骤&#xff0c;简单几步就可以找回你消失的硬盘数据&#…

浅析静态应用安全测试

摘要&#xff1a;根据Forrester的 The State Of Application Security, 2022一文的预测&#xff0c;应用安全性的缺失将仍然是最常见的外部攻击方式&#xff0c;因此SAST将会在可预见的未来一直被重视。本文分享自华为云社区《SAST-静态应用安全测试》&#xff0c;作者&#xf…

Maven 常用插件

前言 建议先看下之前的Blog: Maven 生命周期 & 自定义 Maven 插件。更深入的了解下Build类型插件的运作机制与简单配置。可以官网中查看到更多的支持插件&#xff1a;官网下面的example中只是用到了插件的部分功能&#xff08;goal&#xff09;&#xff0c;更多的功能以及…

网络协议七层模型

1、OSI七层模型&TCP/IP四层模型OSI七层模型 TCP/IP四层模型 对应网络协议 说明应用层 应用层 HTTP、TFTP、FTP、NFS、WAIS、SMTP 主要是终端应用,比如说是FTP,web浏览器,QQ表示层 应用层 Telnet, Rlogin,SNMP, Gopher 主要是对接收的数据进行解密、解压缩等(也就是把计…

excel如何利用公式计算身份证号码对应的年龄

excel如何利用公式计算身份证号码对应的年龄互联网实用攻略 2022-10-31 18:19福建科技领域创作者,活力创作者关注 excel中,利用mid函数可以提取身份证号码中对应的出生年月日,然后TEXT函数将出生日期转为文本,再利用DATEDIF函数计算两个日期(当期日期和身份证号码对应的出…

Spring Batch 批处理-作业增量参数

引言 接着上篇&#xff1a;Spring Batch 批处理-作业参数校验&#xff0c;了解作业参数校验后&#xff0c;本篇就来了解一下Spirng Batch 作业增量参数。 作业增量参数 不知道大家发现了没有&#xff0c;每次运行作业时&#xff0c;都改动作业名字&#xff0c;或者改动作业的…