logo
💻 编程语言

Java

Java Cheat Sheet - 快速参考指南,收录常用语法、命令与实践。

📂 分类 · 编程语言🧭 Markdown 速查🏷️ 2 个标签
#java#jvm
向下滚动查看内容
返回全部 Cheat Sheets

Getting Started

Hello.java
JAVA
滚动查看更多
public class Hello {
  // main method
  public static void main(String[] args)
  {
    // Output: Hello, world!
    System.out.println("Hello, world!");
  }
}

Compiling and running

BASH
滚动查看更多
$ javac Hello.java
$ java Hello
Hello, world!
Variables
JAVA
滚动查看更多
int num = 5;
float floatNum = 5.99f;
char letter = 'D';
boolean bool = true;
String site = "cheatsheets.zip";
Primitive Data Types
Data TypeSizeDefaultRange
byte1 byte0-128 ^to^ 127
short2 byte0-2^15^ ^to^ 2^15^-1
int4 byte0-2^31^ ^to^ 2^31^-1
long8 byte0-2^63^ ^to^ 2^63^-1
float4 byte0.0fN/A
double8 byte0.0dN/A
char2 byte\u00000 ^to^ 65535
booleanN/Afalsetrue / false

{.show-header}

Strings
JAVA
滚动查看更多
String first = "John";
String last = "Doe";
String name = first + " " + last;
System.out.println(name);

See: Strings

Loops
JAVA
滚动查看更多
String word = "CheatSheets";
for (char c: word.toCharArray()) {
  System.out.print(c + "-");
}
// Outputs: C-h-e-a-t-S-h-e-e-t-s-

See: Loops

Arrays
JAVA
滚动查看更多
char[] chars = new char[10];
chars[0] = 'a'
chars[1] = 'b'

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

See: Arrays

Swap
JAVA
滚动查看更多
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
JAVA
滚动查看更多
// 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
JAVA
滚动查看更多
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");
}

See: Conditionals

User Input
JAVA
滚动查看更多
Scanner in = new Scanner(System.in);
String str = in.nextLine();
System.out.println(str);

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

Java Strings

Basic
JAVA
滚动查看更多
String str1 = "value";
String str2 = new String("value");
String str3 = String.valueOf(123);
Concatenation
JAVA
滚动查看更多
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;        // Incompatible types
StringBuilder

StringBuilder sb = new StringBuilder(10);

JAVA
滚动查看更多
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
|   |   |   |   |   |   |   |   |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9

sb.append("QuickRef");

JAVA
滚动查看更多
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | R | e | f |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9

sb.delete(5, 9);

JAVA
滚动查看更多
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k |   |   |   |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9

sb.insert(0, "My ");

JAVA
滚动查看更多
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y |   | Q | u | i | c | k |   |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9

sb.append("!");

JAVA
滚动查看更多
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y |   | Q | u | i | c | k | ! |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0   1   2   3   4   5   6   7   8   9
Comparison
JAVA
滚动查看更多
String s1 = new String("cheatsheets.zip");
String s2 = new String("cheatsheets.zip");

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

"AB".equalsIgnoreCase("ab")  // true
Manipulation
JAVA
滚动查看更多
String str = "Abcd";

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

"  abc ".trim();       // abc
"ab".toCharArray();    // {'a', 'b'}
Information
JAVA
滚动查看更多
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
Immutable
JAVA
滚动查看更多
String str = "hello";
str.concat("world");

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

JAVA
滚动查看更多
String str = "hello";
String concat = str.concat("world");

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

Once created cannot be modified, any modification creates a new String

Java Arrays

Declare
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;
Modify
JAVA
滚动查看更多
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
Loop (Read & Modify)
JAVA
滚动查看更多
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
Loop (Read)
JAVA
滚动查看更多
String[] arr = {"a", "b", "c"};
for (String a: arr) {
    System.out.print(a + " ");
}
// Outputs: a b c
Multidimensional Arrays
JAVA
滚动查看更多
int[][] matrix = { {1, 2, 3}, {4, 5} };

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

int[][] a = 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
Sort
JAVA
滚动查看更多
char[] chars = {'b', 'a', 'c'};
Arrays.sort(chars);

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

Java Conditionals

Operators
  • <a data-tooltip="Additive operator (also used for String concatenation)">+</a>
  • <a data-tooltip="Subtraction operator">-</a>
  • <a data-tooltip="Multiplication operator">*</a>
  • <a data-tooltip="Division operator">/</a>
  • <a data-tooltip="Remainder operator">%</a>
  • <a data-tooltip="Simple assignment operator">=</a>
  • <a data-tooltip="Increment operator; increments a value by 1">++</a>
  • <a data-tooltip="Decrement operator; decrements a value by 1">--</a>
  • <a data-tooltip="Logical complement operator; inverts the value of a boolean">!</a>

{.marker-none .cols-4}


  • <a data-tooltip="Equal to">==</a>
  • <a data-tooltip="Not equal to">!=</a>
  • <a data-tooltip="Greater than">></a>
  • <a data-tooltip="Greater than or equal to">>=</a>
  • <a data-tooltip="Less than"><</a>
  • <a data-tooltip="Less than or equal to"><=</a>

{.marker-none .cols-4}


  • <a data-tooltip="Conditional-AND">&&</a>
  • <a data-tooltip="Conditional-OR">||</a>
  • ?:{data-tooltip="Ternary (shorthand for if-then-else statement)"}

{.marker-none .cols-4}


  • <a data-tooltip="Compares an object to a specified type">instanceof</a>

{.marker-none}


  • <a data-tooltip="Unary bitwise complement">~</a>
  • <a data-tooltip="Signed left shift"><<</a>
  • <a data-tooltip="Signed right shift">>></a>
  • <a data-tooltip="Unsigned right shift">>>></a>
  • <a data-tooltip="Bitwise AND">&</a>
  • <a data-tooltip="Bitwise exclusive OR">^</a>
  • <a data-tooltip="Bitwise inclusive OR">|</a>

{.marker-none .cols-4}

If else
JAVA
滚动查看更多
int k = 15;
if (k > 20) {
  System.out.println(1);
} else if (k > 10) {
  System.out.println(2);
} else {
  System.out.println(3);
}
Switch
JAVA
滚动查看更多
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);
Ternary operator
JAVA
滚动查看更多
int a = 10;
int b = 20;
int max = (a > b) ? a : b;

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

Java Loops

For Loop
JAVA
滚动查看更多
for (int i = 0; i < 10; i++) {
  System.out.print(i);
}
// Outputs: 0123456789

JAVA
滚动查看更多
for (int i = 0,j = 0; i < 3; i++,j--) {
  System.out.print(j + "|" + i + " ");
}
// Outputs: 0|0 -1|1 -2|2
Enhanced For Loop
JAVA
滚动查看更多
int[] numbers = {1,2,3,4,5};

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

Used to loop around array's or List's

While Loop
JAVA
滚动查看更多
int count = 0;

while (count < 5) {
  System.out.print(count);
  count++;
}
// Outputs: 01234
Do While Loop
JAVA
滚动查看更多
int count = 0;

do {
  System.out.print(count);
  count++;
} while (count < 5);
// Outputs: 01234
Continue Statement
JAVA
滚动查看更多
for (int i = 0; i < 5; i++) {
  if (i == 3) {
    continue;
  }
  System.out.print(i);
}
// Outputs: 0124
Break Statement
JAVA
滚动查看更多
for (int i = 0; i < 5; i++) {
  System.out.print(i);
  if (i == 3) {
    break;
  }
}
// Outputs: 0123

Java Collections Framework

Java Collections
CollectionInterfaceOrderedSortedThread safeDuplicateNullable
ArrayListListYNNYY
VectorListYNYYY
LinkedListList, DequeYNNYY
CopyOnWriteArrayListListYNYYY
HashSetSetNNNNOne null
LinkedHashSetSetYNNNOne null
TreeSetSetYYNNN
CopyOnWriteArraySetSetYNYNOne null
ConcurrentSkipListSetSetYYYNN
HashMapMapNNNN (key)One null (key)
HashTableMapNNYN (key)N (key)
LinkedHashMapMapYNNN (key)One null (key)
TreeMapMapYYNN (key)N (key)
ConcurrentHashMapMapNNYN (key)N
ConcurrentSkipListMapMapYYYN (key)N
ArrayDequeDequeYNNYN
PriorityQueueQueueYNNYN
ConcurrentLinkedQueueQueueYNYYN
ConcurrentLinkedDequeDequeYNYYN
ArrayBlockingQueueQueueYNYYN
LinkedBlockingDequeDequeYNYYN
PriorityBlockingQueueQueueYNYYN

{.show-header .left-text}

ArrayList
JAVA
滚动查看更多
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);
}
HashMap
JAVA
滚动查看更多
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);
});
HashSet
JAVA
滚动查看更多
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
JAVA
滚动查看更多
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());

Misc

Access Modifiers
ModifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN

{.show-header .left-text}

Regular expressions
JAVA
滚动查看更多
String text = "I am learning Java";
// Removing All Whitespace
text.replaceAll("\\s+", "");

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

See: Regex in java

Comment
JAVA
滚动查看更多
// I am a single line comment!

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

/**
 * This
 * is
 * documentation
 * comment
 */
Keywords
  • 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

{.marker-none .cols-6}

Math methods
MethodDescription
Math.max(a,b)Maximum of a and b
Math.min(a,b)Minimum of a and b
Math.abs(a)Absolute value a
Math.sqrt(a)Square-root of a
Math.pow(a,b)Power of b
Math.round(a)Closest integer
Math.sin(ang)Sine of ang
Math.cos(ang)Cosine of ang
Math.tan(ang)Tangent of ang
Math.asin(ang)Inverse sine of ang
Math.log(a)Natural logarithm of a
Math.toDegrees(rad)Angle rad in degrees
Math.toRadians(deg)Angle deg in radians
Try/Catch/Finally
JAVA
滚动查看更多
try {
  // something
} catch (Exception e) {
  e.printStackTrace();
} finally {
  System.out.println("always printed");
}

相关 Cheat Sheets

1v1免费职业咨询
logo

Follow Us

linkedinfacebooktwitterinstagramweiboyoutubebilibilitiktokxigua

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png

地址

Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号
Business Hub, 155 Waymouth St, Adelaide SA 5000

Disclaimer

footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。 JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议

© 2017-2025 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572