0% found this document useful (0 votes)
6 views5 pages

Java Cheatsheet

This document is a comprehensive Java cheatsheet aimed at beginners, covering essential concepts such as variables, data types, loops, conditionals, and collections. It provides code examples and explanations for various Java features, including strings, arrays, and user input. The cheatsheet serves as a quick reference for fundamental Java syntax and programming constructs.

Uploaded by

borkarhr25.comp
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views5 pages

Java Cheatsheet

This document is a comprehensive Java cheatsheet aimed at beginners, covering essential concepts such as variables, data types, loops, conditionals, and collections. It provides code examples and explanations for various Java features, including strings, arrays, and user input. The cheatsheet serves as a quick reference for fundamental Java syntax and programming constructs.

Uploaded by

borkarhr25.comp
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link] Search for cheatsheet ⌘ K Stars 7.

6k Follow Me

Java cheatsheet
This cheat sheet is a crash course for Java beginners and help review the basic syntax of the
Java language.

# Getting Started
[Link] Variables Primitive Data Types

public class Hello { int num = 5; Data Type Size Default Range
// main method float floatNum = 5.99f;
byte 1 byte 0 -128 to 127
public static void main(String[] args) char letter = 'D';
{ boolean bool = true;
short 2 byte 0 -215 to 215-1
// Output: Hello, world! String site = "[Link]";
[Link]("Hello, world!");
int 4 byte 0 -231 to
231-1
}
} long 8 byte 0 -263 to
263-1
Strings

Compiling and running String first = "John"; float 4 byte 0.0f N/A
String last = "Doe";
String name = first + " " + last; double 8 byte 0.0d N/A
$ javac [Link]
$ java Hello [Link](name);
char 2 byte \u0000 0 to 65535
Hello, world!

See: Strings boolean N/A false true / false

Loops Arrays Swap

String word = "QuickRef"; char[] chars = new char[10]; int a = 1;


for (char c: [Link]()) { chars[0] = 'a' int b = 2;
[Link](c + "-"); chars[1] = 'b' [Link](a + " " + b); // 1 2
}
// Outputs: Q-u-i-c-k-R-e-f- String[] letters = {"A", "B", "C"}; int temp = a;
int[] mylist = {100, 200}; a = b;
boolean[] answers = {true, false}; b = temp;
[Link](a + " " + b); // 2 1
See: Loops See: Arrays

Type Casting Conditionals User Input

// Widening int j = 10; Scanner in = new Scanner([Link]);


// byte<short<int<long<float<double String str = [Link]();
int i = 10; if (j == 10) { [Link](str);
long l = i; // 10 [Link]("I get printed");
} else if (j > 10) { int num = [Link]();
// Narrowing [Link]("I don't"); [Link](num);
double d = 10.02; } else {
long l = (long)d; // 10 [Link]("I also don't");
}
[Link](10); // "10"
[Link]("10"); // 10
[Link]("10"); // 10.0 See: Conditionals

# Java Strings
Basic Concatenation - StringBuilder

String str1 = "value"; String s = 3 + "str" + 3; // 3str3 StringBuilder sb = new StringBuilder(10);


String str2 = new String("value"); String s = 3 + 3 + "str"; // 6str
String str3 = [Link](123); String s = "3" + 3 + "str"; // 33str ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
String s = "3" + "3" + "23"; // 3323 | | | | | | | | | |
String s = "" + 3 + 3 + "23"; // 3323 └───┴───┴───┴───┴───┴───┴───┴───┴───┘
String s = 3 + 3 + 23; // 29 0 1 2 3 4 5 6 7 8 9
Comparison Manipulation [Link]("QuickRef");

String s1 = new String("QuickRef"); String str = "Abcd"; ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐


String s2 = new String("QuickRef"); | Q | u | i | c | k | R | e | f | |
[Link](); // ABCD └───┴───┴───┴───┴───┴───┴───┴───┴───┘
s1 == s2 // false [Link](); // abcd 0 1 2 3 4 5 6 7 8 9
[Link](s2) // true [Link]("#"); // Abcd#
[Link]("b", "-"); // A-cd
[Link](5, 9);
"AB".equalsIgnoreCase("ab") // true
" abc ".trim(); // abc
"ab".toCharArray(); // {'a', 'b'} ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
Information Immutable 0 1 2 3 4 5 6 7 8 9

String str = "abcd"; String str = "hello";


[Link](0, "My ");
[Link]("world");
[Link](2); // c
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
[Link]("a") // 0 // Outputs: hello
| M | y | | Q | u | i | c | k | |
[Link]("z") // -1 [Link](str);
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
[Link](); // 4
0 1 2 3 4 5 6 7 8 9
[Link](); // abcd
String str = "hello";
[Link](2); // cd
String concat = [Link]("world");
[Link](2,3); // c [Link]("!");
[Link]("c"); // true
// Outputs: helloworld
[Link]("d"); // true ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
[Link](concat);
[Link]("a"); // true | M | y | | Q | u | i | c | k | ! |
[Link](); // false └───┴───┴───┴───┴───┴───┴───┴───┴───┘
Once created cannot be modified, any modification 0 1 2 3 4 5 6 7 8 9
creates a new String

# Java Arrays
Declare Modify Loop (Read & Modify)

int[] a1; int[] a = {1, 2, 3}; int[] arr = {1, 2, 3};


int[] a2 = {1, 2, 3}; [Link](a[0]); // 1 for (int i=0; i < [Link]; i++) {
int[] a3 = new int[]{1, 2, 3}; arr[i] = arr[i] * 2;
a[0] = 9; [Link](arr[i] + " ");
int[] a4 = new int[3]; [Link](a[0]); // 9 }
a4[0] = 1; // Outputs: 2 4 6
a4[2] = 2; [Link]([Link]); // 3
a4[3] = 3;

Loop (Read) Multidimensional Arrays Sort

String[] arr = {"a", "b", "c"}; int[][] matrix = { {1, 2, 3}, {4, 5} }; char[] chars = {'b', 'a', 'c'};
for (int a: arr) { [Link](chars);
[Link](a + " "); int x = matrix[1][0]; // 4
} // [[1, 2, 3], [4, 5]] // [a, b, c]
// Outputs: a b c [Link](matrix) [Link](chars);

for (int i = 0; i < [Link]; ++i) {


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

# Java Conditionals
Operators If else Switch

+ - * / int k = 15; int month = 3;


if (k > 20) { String str;
% = ++ -- [Link](1); switch (month) {
} else if (k > 10) { case 1:
! [Link](2); str = "January";
} else { break;
== != > >= [Link](3); case 2:
} str = "February";
< <= break;
case 3:
str = "March";
&& || ?: Ternary operator
break;
default:
instanceof int a = 10; str = "Some other month";
int b = 20; break;
int max = (a > b) ? a : b; }
~ << >> >>>

// Outputs: 20 // Outputs: Result March


& ^ |
[Link](max); [Link]("Result " + str);

# Java Loops
For Loop Enhanced For Loop While Loop

for (int i = 0; i < 10; i++) { int[] numbers = {1,2,3,4,5}; int count = 0;
[Link](i);
} for (int number: numbers) { while (count < 5) {
// Outputs: 0123456789 [Link](number); [Link](count);
} count++;
// Outputs: 12345 }
for (int i = 0,j = 0; i < 3; i++,j--) {
// Outputs: 01234
[Link](j + "|" + i + " ");
}
// Outputs: 0|0 -1|1 -2|2 Used to loop around array's or List's

Do While Loop Continue Statement Break Statement

int count = 0; for (int i = 0; i < 5; i++) { for (int i = 0; i < 5; i++) {
if (i == 3) { [Link](i);
do { continue; if (i == 3) {
[Link](count); } break;
count++; [Link](i); }
} while (count < 5); } }
// Outputs: 01234 // Outputs: 01245 // Outputs: 0123

# Java Collections Framework


Java Collections ArrayList

Collection Interface Ordered Sorted Thread safe Duplicate Nullable List<Integer> nums = new ArrayList<>();

ArrayList List Y N N Y Y
// Adding
[Link](2);
Vector List Y N Y Y Y
[Link](5);
LinkedList List, Deque Y N N Y Y [Link](8);

CopyOnWriteArrayList List Y N Y Y Y // Retrieving


[Link]([Link](0));
HashSet Set N N N N One null
// Indexed for loop iteration
LinkedHashSet Set Y N N N One null for (int i = 0; i < [Link](); i++) {
[Link]([Link](i));
TreeSet Set Y Y N N N
}

CopyOnWriteArraySet Set Y N Y N One null


[Link]([Link]() - 1);
ConcurrentSkipListSet Set Y Y Y N N [Link](0); // VERY slow

HashMap Map N N N N (key) One null (key) for (Integer value : nums) {
[Link](value);
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

Pi it Bl ki Q Q Y N Y Y N

HashMap HashSet ArrayDeque

Map<Integer, String> m = new HashMap<>(); Set<String> set = new HashSet<>(); Deque<String> a = new ArrayDeque<>();
[Link](5, "Five"); if ([Link]()) {
[Link](8, "Eight"); [Link]("Empty!"); // Using add()
[Link](6, "Six"); } [Link]("Dog");
[Link](4, "Four");
[Link](2, "Two"); [Link]("dog"); // Using addFirst()
[Link]("cat"); [Link]("Cat");
// Retrieving [Link]("mouse");
[Link]([Link](6)); [Link]("snake"); // Using addLast()
[Link]("bear"); [Link]("Horse");
// Lambda forEach
[Link]((key, value) -> { if ([Link]("cat")) { // [Cat, Dog, Horse]
String msg = key + ": " + value; [Link]("Contains cat"); [Link](a);
[Link](msg); }
}); // Access element
[Link]("cat"); [Link]([Link]());
for (String element : set) {
[Link](element); // Remove element
} [Link]([Link]());

# Misc
Access Modifiers Regular expressions

Modifier Class Package Subclass World String text = "I am learning Java";
// Removing All Whitespace
public Y Y Y Y
[Link]("\\s+", "");

protected Y Y Y N
// Splitting a String
no modifier Y Y N N [Link]("\\|");
[Link]([Link]("|"));
private Y N N N

See: Regex in java

Comment Keywords

// I am a single line comment! abstract continue for new switch assert

/* default goto package synchronized boolean do


And I am a
multi-line comment! if private this break double implements
*/
protected throw byte else import public

/**
throws case enum instanceof return transient
* This
* is catch extends int short try char
* documentation
* comment final interface static void class finally
*/
long strictfp volatile const float native

super while

Math methods Try/Catch/Finally

[Link](a,b) Maximum of a and b try {


// something
[Link](a,b) Minimum of a and b } catch (Exception e) {
[Link]();
[Link](a) Absolute value a
} finally {
[Link]("always printed");
[Link](a) Square-root of a
}
[Link](a,b) Power of b

[Link](a) Closest integer

[Link](ang) Sine of ang

[Link](ang) Cosine of ang

[Link](ang) Tangent of ang


[Link](ang) Inverse sine of ang

[Link](a) Natural logarithm of a

[Link](rad) Angle rad in degrees

[Link](deg) Angle deg in radians

Related Cheatsheet Recent Cheatsheet


[Link]
C# Cheatsheet Remote Work Revolution Homebrew Cheatsheet
Share quick reference and cheat sheet for
Quick Reference Quick Reference Quick Reference
developers.

中文版 #Notes
PyTorch Cheatsheet Taskset Cheatsheet
Quick Reference Quick Reference

© 2023 [Link], All rights reserved.

You might also like