Latest commit

History

History
775 lines (623 loc) · 16.6 KB

File metadata and controls

775 lines (623 loc) · 16.6 KB
titleJava
date2021-03-10 11:50:01 -0800
iconicon-java
backgroundbg-red-700
tags
object-oriented
class
categories
Programming
introThis cheat sheet is a crash course for Java beginners and help review the basic syntax of the Java language.
plugins
tooltip

Getting started {.cols-3}

Hello.java {.row-span-2}

publicclassHello {
// main methordpublicstaticvoidmain(String[] args)
{
// Output: Hello, world!System.out.println("Hello, world!");
}
}

Compiling and running

$ javac Hello.java
$ java Hello
Hello, world!

Variables

intnum = 5;
floatfloatNum = 5.99f;
charletter = 'D';
booleanbool = true;
Stringsite = "quickref.me";

Primitive Data Types {.row-span-2}

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

Stringfirst = "John";
Stringlast = "Doe";
Stringname = first + " " + last;
System.out.println(name);

See: Strings

Loops

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

See: Loops

Arrays

char[] chars = newchar[10];
chars[0] = 'a'chars[1] = 'b'String[] letters = {"A", "B", "C"};
int[] mylist = {100, 200};
boolean[] answers = {true, false};

See: Arrays

Swap

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

Type Casting

// Widening// byte<short<int<long<float<doubleinti = 10;
longl = i; // 10// Narrowing doubled = 10.02;
longl = (long)d; // 10String.valueOf(10); // "10"Integer.parseInt("10"); // 10Double.parseDouble("10"); // 10.0

Conditionals

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

See: Conditionals

User Input

Scannerin = newScanner(System.in);
Stringstr = in.nextLine();
System.out.println(str);
intnum = in.nextInt();
System.out.println(num);

Java Strings {.cols-3}

Basic

Stringstr1 = "value"; Stringstr2 = newString("value");
Stringstr3 = String.valueOf(123);

Concatenation

Strings = 3 + "str" + 3; // 3str3Strings = 3 + 3 + "str"; // 6strStrings = "3" + 3 + "str"; // 33strStrings = "3" + "3" + "23"; // 3323Strings = "" + 3 + 3 + "23"; // 3323Strings = 3 + 3 + 23; // 29

StringBuilder {.row-span-3}

StringBuilder sb = new StringBuilder(10);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| | | | | | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("QuickRef");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | R | e | f | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.delete(5, 9);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.insert(0, "My ");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("!");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | ! |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

Comparison

Strings1 = newString("QuickRef"); Strings2 = newString("QuickRef"); s1 == s2// falses1.equals(s2) // true"AB".equalsIgnoreCase("ab") // true

Manipulation

Stringstr = "Abcd";
str.toUpperCase(); // ABCDstr.toLowerCase(); // abcdstr.concat("#"); // Abcd#str.replace("b", "-"); // A-cd" abc ".trim(); // abc"ab".toCharArray(); // {'a', 'b'}

Information

Stringstr = "abcd";
str.charAt(2); // cstr.indexOf("a") // 0str.indexOf("z") // -1str.length(); // 4str.toString(); // abcdstr.substring(2); // cdstr.substring(2,3); // cstr.contains("c"); // truestr.endsWith("d"); // truestr.startsWith("a"); // truestr.isEmpty(); // false

Immutable

Stringstr = "hello";
str.concat("world");
// Outputs: helloSystem.out.println(str);

Stringstr = "hello";
Stringconcat = str.concat("world");
// Outputs: helloworldSystem.out.println(concat);

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

Java Arrays {.cols-3}

Declare

int[] a1;
int[] a2 = {1, 2, 3};
int[] a3 = newint[]{1, 2, 3};
int[] a4 = newint[3];
a4[0] = 1;
a4[2] = 2;
a4[3] = 3;

Modify

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

Loop (Read & Modify)

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

Loop (Read)

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

Multidimensional Arrays

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

Sort

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

Java Conditionals {.cols-3}

Operators {.row-span-2}

  • +
  • -
  • *
  • /
  • %
  • =
  • ++
  • --
  • ! {.style-none .cols-4}

  • ==
  • !=
  • >
  • >=
  • <
  • <= {.style-none .cols-4}

  • &&
  • ||
  • ?:{data-tooltip="Ternary (shorthand for if-then-else statement)"} {.style-none .cols-4}

  • instanceof {.style-none}

  • ~
  • <<
  • >>
  • >>>
  • &
  • ^
  • | {.style-none .cols-4}

If else

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

Switch {.row-span-2}

intmonth = 3;
Stringstr;
switch (month) {
case1:
str = "January";
break;
case2:
str = "February";
break;
case3:
str = "March";
break;
default:
str = "Some other month";
break;
}
// Outputs: Result MarchSystem.out.println("Result " + str);

Ternary operator

inta = 10;
intb = 20;
intmax = (a > b) ? a : b;
// Outputs: 20System.out.println(max);

Java Loops {.cols-3}

For Loop

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

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

Enhanced For Loop

int[] numbers = {1,2,3,4,5};
for (intnumber: numbers) {
System.out.print(number);
}
// Outputs: 12345

Used to loop around array's or List's

While Loop

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

Do While Loop

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

Continue Statement

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

Break Statement

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

Java Collections Framework {.cols-3}

Java Collections {.col-span-2}

CollectionInterfaceOrderedSortedThread safeDuplicateNullable
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
{.show-header .left-text}

ArrayList

List<Integer> nums = newArrayList<>();
// Addingnums.add(2);
nums.add(5);
nums.add(8);
// RetrievingSystem.out.println(nums.get(0));
// Indexed for loop iterationfor (inti = 0; i < nums.size(); i++) {
System.out.println(nums.get(i));
}
nums.remove(nums.size() - 1);
nums.remove(0); // VERY slowfor (Integervalue : nums) {
System.out.println(value);
}

HashMap

Map<Integer, String> m = newHashMap<>();
m.put(5, "Five");
m.put(8, "Eight");
m.put(6, "Six");
m.put(4, "Four");
m.put(2, "Two");
// RetrievingSystem.out.println(m.get(6));
// Lambda forEachm.forEach((key, value) -> {
Stringmsg = key + ": " + value;
System.out.println(msg);
});

HashSet

Set<String> set = newHashSet<>();
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 (Stringelement : set) {
System.out.println(element);
}

ArrayDeque

Deque<String> a = newArrayDeque<>();
// Using add()a.add("Dog");
// Using addFirst()a.addFirst("Cat");
// Using addLast()a.addLast("Horse");
// [Cat, Dog, Horse]System.out.println(a);
// Access elementSystem.out.println(a.peek());
// Remove elementSystem.out.println(a.pop());

Misc {.cols-3}

Access Modifiers {.col-span-2}

ModifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN
{.show-header .left-text}

Regular expressions

Stringtext = "I am learning Java";
// Removing All Whitespacetext.replaceAll("\\s+", "");
// Splitting a Stringtext.split("\\|");
text.split(Pattern.quote("|"));

See: Regex in java

Comment

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

Keywords {.col-span-2}

  • 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 {.style-none .cols-7}

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

try {
// something
} catch (Exceptione) {
e.printStackTrace();
} finally {
System.out.println("always printed");
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

History
775 lines (623 loc) · 16.6 KB

File metadata and controls

775 lines (623 loc) · 16.6 KB
titleJava
date2021-03-10 11:50:01 -0800
iconicon-java
backgroundbg-red-700
tags
object-oriented
class
categories
Programming
introThis cheat sheet is a crash course for Java beginners and help review the basic syntax of the Java language.
plugins
tooltip

Getting started {.cols-3}

Hello.java {.row-span-2}

publicclassHello {
// main methordpublicstaticvoidmain(String[] args)
{
// Output: Hello, world!System.out.println("Hello, world!");
}
}

Compiling and running

$ javac Hello.java
$ java Hello
Hello, world!

Variables

intnum = 5;
floatfloatNum = 5.99f;
charletter = 'D';
booleanbool = true;
Stringsite = "quickref.me";

Primitive Data Types {.row-span-2}

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

Stringfirst = "John";
Stringlast = "Doe";
Stringname = first + " " + last;
System.out.println(name);

See: Strings

Loops

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

See: Loops

Arrays

char[] chars = newchar[10];
chars[0] = 'a'chars[1] = 'b'String[] letters = {"A", "B", "C"};
int[] mylist = {100, 200};
boolean[] answers = {true, false};

See: Arrays

Swap

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

Type Casting

// Widening// byte<short<int<long<float<doubleinti = 10;
longl = i; // 10// Narrowing doubled = 10.02;
longl = (long)d; // 10String.valueOf(10); // "10"Integer.parseInt("10"); // 10Double.parseDouble("10"); // 10.0

Conditionals

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

See: Conditionals

User Input

Scannerin = newScanner(System.in);
Stringstr = in.nextLine();
System.out.println(str);
intnum = in.nextInt();
System.out.println(num);

Java Strings {.cols-3}

Basic

Stringstr1 = "value"; Stringstr2 = newString("value");
Stringstr3 = String.valueOf(123);

Concatenation

Strings = 3 + "str" + 3; // 3str3Strings = 3 + 3 + "str"; // 6strStrings = "3" + 3 + "str"; // 33strStrings = "3" + "3" + "23"; // 3323Strings = "" + 3 + 3 + "23"; // 3323Strings = 3 + 3 + 23; // 29

StringBuilder {.row-span-3}

StringBuilder sb = new StringBuilder(10);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| | | | | | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("QuickRef");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | R | e | f | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.delete(5, 9);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.insert(0, "My ");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("!");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | ! |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

Comparison

Strings1 = newString("QuickRef"); Strings2 = newString("QuickRef"); s1 == s2// falses1.equals(s2) // true"AB".equalsIgnoreCase("ab") // true

Manipulation

Stringstr = "Abcd";
str.toUpperCase(); // ABCDstr.toLowerCase(); // abcdstr.concat("#"); // Abcd#str.replace("b", "-"); // A-cd" abc ".trim(); // abc"ab".toCharArray(); // {'a', 'b'}

Information

Stringstr = "abcd";
str.charAt(2); // cstr.indexOf("a") // 0str.indexOf("z") // -1str.length(); // 4str.toString(); // abcdstr.substring(2); // cdstr.substring(2,3); // cstr.contains("c"); // truestr.endsWith("d"); // truestr.startsWith("a"); // truestr.isEmpty(); // false

Immutable

Stringstr = "hello";
str.concat("world");
// Outputs: helloSystem.out.println(str);

Stringstr = "hello";
Stringconcat = str.concat("world");
// Outputs: helloworldSystem.out.println(concat);

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

Java Arrays {.cols-3}

Declare

int[] a1;
int[] a2 = {1, 2, 3};
int[] a3 = newint[]{1, 2, 3};
int[] a4 = newint[3];
a4[0] = 1;
a4[2] = 2;
a4[3] = 3;

Modify

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

Loop (Read & Modify)

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

Loop (Read)

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

Multidimensional Arrays

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

Sort

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

Java Conditionals {.cols-3}

Operators {.row-span-2}

  • +
  • -
  • *
  • /
  • %
  • =
  • ++
  • --
  • ! {.style-none .cols-4}

  • ==
  • !=
  • >
  • >=
  • <
  • <= {.style-none .cols-4}

  • &&
  • ||
  • ?:{data-tooltip="Ternary (shorthand for if-then-else statement)"} {.style-none .cols-4}

  • instanceof {.style-none}

  • ~
  • <<
  • >>
  • >>>
  • &
  • ^
  • | {.style-none .cols-4}

If else

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

Switch {.row-span-2}

intmonth = 3;
Stringstr;
switch (month) {
case1:
str = "January";
break;
case2:
str = "February";
break;
case3:
str = "March";
break;
default:
str = "Some other month";
break;
}
// Outputs: Result MarchSystem.out.println("Result " + str);

Ternary operator

inta = 10;
intb = 20;
intmax = (a > b) ? a : b;
// Outputs: 20System.out.println(max);

Java Loops {.cols-3}

For Loop

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

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

Enhanced For Loop

int[] numbers = {1,2,3,4,5};
for (intnumber: numbers) {
System.out.print(number);
}
// Outputs: 12345

Used to loop around array's or List's

While Loop

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

Do While Loop

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

Continue Statement

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

Break Statement

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

Java Collections Framework {.cols-3}

Java Collections {.col-span-2}

CollectionInterfaceOrderedSortedThread safeDuplicateNullable
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
{.show-header .left-text}

ArrayList

List<Integer> nums = newArrayList<>();
// Addingnums.add(2);
nums.add(5);
nums.add(8);
// RetrievingSystem.out.println(nums.get(0));
// Indexed for loop iterationfor (inti = 0; i < nums.size(); i++) {
System.out.println(nums.get(i));
}
nums.remove(nums.size() - 1);
nums.remove(0); // VERY slowfor (Integervalue : nums) {
System.out.println(value);
}

HashMap

Map<Integer, String> m = newHashMap<>();
m.put(5, "Five");
m.put(8, "Eight");
m.put(6, "Six");
m.put(4, "Four");
m.put(2, "Two");
// RetrievingSystem.out.println(m.get(6));
// Lambda forEachm.forEach((key, value) -> {
Stringmsg = key + ": " + value;
System.out.println(msg);
});

HashSet

Set<String> set = newHashSet<>();
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 (Stringelement : set) {
System.out.println(element);
}

ArrayDeque

Deque<String> a = newArrayDeque<>();
// Using add()a.add("Dog");
// Using addFirst()a.addFirst("Cat");
// Using addLast()a.addLast("Horse");
// [Cat, Dog, Horse]System.out.println(a);
// Access elementSystem.out.println(a.peek());
// Remove elementSystem.out.println(a.pop());

Misc {.cols-3}

Access Modifiers {.col-span-2}

ModifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN
{.show-header .left-text}

Regular expressions

Stringtext = "I am learning Java";
// Removing All Whitespacetext.replaceAll("\\s+", "");
// Splitting a Stringtext.split("\\|");
text.split(Pattern.quote("|"));

See: Regex in java

Comment

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

Keywords {.col-span-2}

  • 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 {.style-none .cols-7}

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

try {
// something
} catch (Exceptione) {
e.printStackTrace();
} finally {
System.out.println("always printed");
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
775 lines (623 loc) · 16.6 KB

File metadata and controls

775 lines (623 loc) · 16.6 KB
titleJava
date2021-03-10 11:50:01 -0800
iconicon-java
backgroundbg-red-700
tags
object-oriented
class
categories
Programming
introThis cheat sheet is a crash course for Java beginners and help review the basic syntax of the Java language.
plugins
tooltip

Getting started {.cols-3}

Hello.java {.row-span-2}

publicclassHello {
// main methordpublicstaticvoidmain(String[] args)
{
// Output: Hello, world!System.out.println("Hello, world!");
}
}

Compiling and running

$ javac Hello.java
$ java Hello
Hello, world!

Variables

intnum = 5;
floatfloatNum = 5.99f;
charletter = 'D';
booleanbool = true;
Stringsite = "quickref.me";

Primitive Data Types {.row-span-2}

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

Stringfirst = "John";
Stringlast = "Doe";
Stringname = first + " " + last;
System.out.println(name);

See: Strings

Loops

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

See: Loops

Arrays

char[] chars = newchar[10];
chars[0] = 'a'chars[1] = 'b'String[] letters = {"A", "B", "C"};
int[] mylist = {100, 200};
boolean[] answers = {true, false};

See: Arrays

Swap

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

Type Casting

// Widening// byte<short<int<long<float<doubleinti = 10;
longl = i; // 10// Narrowing doubled = 10.02;
longl = (long)d; // 10String.valueOf(10); // "10"Integer.parseInt("10"); // 10Double.parseDouble("10"); // 10.0

Conditionals

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

See: Conditionals

User Input

Scannerin = newScanner(System.in);
Stringstr = in.nextLine();
System.out.println(str);
intnum = in.nextInt();
System.out.println(num);

Java Strings {.cols-3}

Basic

Stringstr1 = "value"; Stringstr2 = newString("value");
Stringstr3 = String.valueOf(123);

Concatenation

Strings = 3 + "str" + 3; // 3str3Strings = 3 + 3 + "str"; // 6strStrings = "3" + 3 + "str"; // 33strStrings = "3" + "3" + "23"; // 3323Strings = "" + 3 + 3 + "23"; // 3323Strings = 3 + 3 + 23; // 29

StringBuilder {.row-span-3}

StringBuilder sb = new StringBuilder(10);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| | | | | | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("QuickRef");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | R | e | f | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.delete(5, 9);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.insert(0, "My ");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("!");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | ! |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

Comparison

Strings1 = newString("QuickRef"); Strings2 = newString("QuickRef"); s1 == s2// falses1.equals(s2) // true"AB".equalsIgnoreCase("ab") // true

Manipulation

Stringstr = "Abcd";
str.toUpperCase(); // ABCDstr.toLowerCase(); // abcdstr.concat("#"); // Abcd#str.replace("b", "-"); // A-cd" abc ".trim(); // abc"ab".toCharArray(); // {'a', 'b'}

Information

Stringstr = "abcd";
str.charAt(2); // cstr.indexOf("a") // 0str.indexOf("z") // -1str.length(); // 4str.toString(); // abcdstr.substring(2); // cdstr.substring(2,3); // cstr.contains("c"); // truestr.endsWith("d"); // truestr.startsWith("a"); // truestr.isEmpty(); // false

Immutable

Stringstr = "hello";
str.concat("world");
// Outputs: helloSystem.out.println(str);

Stringstr = "hello";
Stringconcat = str.concat("world");
// Outputs: helloworldSystem.out.println(concat);

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

Java Arrays {.cols-3}

Declare

int[] a1;
int[] a2 = {1, 2, 3};
int[] a3 = newint[]{1, 2, 3};
int[] a4 = newint[3];
a4[0] = 1;
a4[2] = 2;
a4[3] = 3;

Modify

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

Loop (Read & Modify)

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

Loop (Read)

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

Multidimensional Arrays

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

Sort

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

Java Conditionals {.cols-3}

Operators {.row-span-2}

  • +
  • -
  • *
  • /
  • %
  • =
  • ++
  • --
  • ! {.style-none .cols-4}

  • ==
  • !=
  • >
  • >=
  • <
  • <= {.style-none .cols-4}

  • &&
  • ||
  • ?:{data-tooltip="Ternary (shorthand for if-then-else statement)"} {.style-none .cols-4}

  • instanceof {.style-none}

  • ~
  • <<
  • >>
  • >>>
  • &
  • ^
  • | {.style-none .cols-4}

If else

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

Switch {.row-span-2}

intmonth = 3;
Stringstr;
switch (month) {
case1:
str = "January";
break;
case2:
str = "February";
break;
case3:
str = "March";
break;
default:
str = "Some other month";
break;
}
// Outputs: Result MarchSystem.out.println("Result " + str);

Ternary operator

inta = 10;
intb = 20;
intmax = (a > b) ? a : b;
// Outputs: 20System.out.println(max);

Java Loops {.cols-3}

For Loop

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

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

Enhanced For Loop

int[] numbers = {1,2,3,4,5};
for (intnumber: numbers) {
System.out.print(number);
}
// Outputs: 12345

Used to loop around array's or List's

While Loop

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

Do While Loop

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

Continue Statement

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

Break Statement

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

Java Collections Framework {.cols-3}

Java Collections {.col-span-2}

CollectionInterfaceOrderedSortedThread safeDuplicateNullable
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
{.show-header .left-text}

ArrayList

List<Integer> nums = newArrayList<>();
// Addingnums.add(2);
nums.add(5);
nums.add(8);
// RetrievingSystem.out.println(nums.get(0));
// Indexed for loop iterationfor (inti = 0; i < nums.size(); i++) {
System.out.println(nums.get(i));
}
nums.remove(nums.size() - 1);
nums.remove(0); // VERY slowfor (Integervalue : nums) {
System.out.println(value);
}

HashMap

Map<Integer, String> m = newHashMap<>();
m.put(5, "Five");
m.put(8, "Eight");
m.put(6, "Six");
m.put(4, "Four");
m.put(2, "Two");
// RetrievingSystem.out.println(m.get(6));
// Lambda forEachm.forEach((key, value) -> {
Stringmsg = key + ": " + value;
System.out.println(msg);
});

HashSet

Set<String> set = newHashSet<>();
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 (Stringelement : set) {
System.out.println(element);
}

ArrayDeque

Deque<String> a = newArrayDeque<>();
// Using add()a.add("Dog");
// Using addFirst()a.addFirst("Cat");
// Using addLast()a.addLast("Horse");
// [Cat, Dog, Horse]System.out.println(a);
// Access elementSystem.out.println(a.peek());
// Remove elementSystem.out.println(a.pop());

Misc {.cols-3}

Access Modifiers {.col-span-2}

ModifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN
{.show-header .left-text}

Regular expressions

Stringtext = "I am learning Java";
// Removing All Whitespacetext.replaceAll("\\s+", "");
// Splitting a Stringtext.split("\\|");
text.split(Pattern.quote("|"));

See: Regex in java

Comment

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

Keywords {.col-span-2}

  • 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 {.style-none .cols-7}

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

try {
// something
} catch (Exceptione) {
e.printStackTrace();
} finally {
System.out.println("always printed");
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
775 lines (623 loc) · 16.6 KB

File metadata and controls

775 lines (623 loc) · 16.6 KB
titleJava
date2021-03-10 11:50:01 -0800
iconicon-java
backgroundbg-red-700
tags
object-oriented
class
categories
Programming
introThis cheat sheet is a crash course for Java beginners and help review the basic syntax of the Java language.
plugins
tooltip

Getting started {.cols-3}

Hello.java {.row-span-2}

publicclassHello {
// main methordpublicstaticvoidmain(String[] args)
{
// Output: Hello, world!System.out.println("Hello, world!");
}
}

Compiling and running

$ javac Hello.java
$ java Hello
Hello, world!

Variables

intnum = 5;
floatfloatNum = 5.99f;
charletter = 'D';
booleanbool = true;
Stringsite = "quickref.me";

Primitive Data Types {.row-span-2}

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

Stringfirst = "John";
Stringlast = "Doe";
Stringname = first + " " + last;
System.out.println(name);

See: Strings

Loops

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

See: Loops

Arrays

char[] chars = newchar[10];
chars[0] = 'a'chars[1] = 'b'String[] letters = {"A", "B", "C"};
int[] mylist = {100, 200};
boolean[] answers = {true, false};

See: Arrays

Swap

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

Type Casting

// Widening// byte<short<int<long<float<doubleinti = 10;
longl = i; // 10// Narrowing doubled = 10.02;
longl = (long)d; // 10String.valueOf(10); // "10"Integer.parseInt("10"); // 10Double.parseDouble("10"); // 10.0

Conditionals

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

See: Conditionals

User Input

Scannerin = newScanner(System.in);
Stringstr = in.nextLine();
System.out.println(str);
intnum = in.nextInt();
System.out.println(num);

Java Strings {.cols-3}

Basic

Stringstr1 = "value"; Stringstr2 = newString("value");
Stringstr3 = String.valueOf(123);

Concatenation

Strings = 3 + "str" + 3; // 3str3Strings = 3 + 3 + "str"; // 6strStrings = "3" + 3 + "str"; // 33strStrings = "3" + "3" + "23"; // 3323Strings = "" + 3 + 3 + "23"; // 3323Strings = 3 + 3 + 23; // 29

StringBuilder {.row-span-3}

StringBuilder sb = new StringBuilder(10);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| | | | | | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("QuickRef");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | R | e | f | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.delete(5, 9);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.insert(0, "My ");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("!");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | ! |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

Comparison

Strings1 = newString("QuickRef"); Strings2 = newString("QuickRef"); s1 == s2// falses1.equals(s2) // true"AB".equalsIgnoreCase("ab") // true

Manipulation

Stringstr = "Abcd";
str.toUpperCase(); // ABCDstr.toLowerCase(); // abcdstr.concat("#"); // Abcd#str.replace("b", "-"); // A-cd" abc ".trim(); // abc"ab".toCharArray(); // {'a', 'b'}

Information

Stringstr = "abcd";
str.charAt(2); // cstr.indexOf("a") // 0str.indexOf("z") // -1str.length(); // 4str.toString(); // abcdstr.substring(2); // cdstr.substring(2,3); // cstr.contains("c"); // truestr.endsWith("d"); // truestr.startsWith("a"); // truestr.isEmpty(); // false

Immutable

Stringstr = "hello";
str.concat("world");
// Outputs: helloSystem.out.println(str);

Stringstr = "hello";
Stringconcat = str.concat("world");
// Outputs: helloworldSystem.out.println(concat);

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

Java Arrays {.cols-3}

Declare

int[] a1;
int[] a2 = {1, 2, 3};
int[] a3 = newint[]{1, 2, 3};
int[] a4 = newint[3];
a4[0] = 1;
a4[2] = 2;
a4[3] = 3;

Modify

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

Loop (Read & Modify)

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

Loop (Read)

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

Multidimensional Arrays

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

Sort

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

Java Conditionals {.cols-3}

Operators {.row-span-2}

  • +
  • -
  • *
  • /
  • %
  • =
  • ++
  • --
  • ! {.style-none .cols-4}

  • ==
  • !=
  • >
  • >=
  • <
  • <= {.style-none .cols-4}

  • &&
  • ||
  • ?:{data-tooltip="Ternary (shorthand for if-then-else statement)"} {.style-none .cols-4}

  • instanceof {.style-none}

  • ~
  • <<
  • >>
  • >>>
  • &
  • ^
  • | {.style-none .cols-4}

If else

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

Switch {.row-span-2}

intmonth = 3;
Stringstr;
switch (month) {
case1:
str = "January";
break;
case2:
str = "February";
break;
case3:
str = "March";
break;
default:
str = "Some other month";
break;
}
// Outputs: Result MarchSystem.out.println("Result " + str);

Ternary operator

inta = 10;
intb = 20;
intmax = (a > b) ? a : b;
// Outputs: 20System.out.println(max);

Java Loops {.cols-3}

For Loop

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

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

Enhanced For Loop

int[] numbers = {1,2,3,4,5};
for (intnumber: numbers) {
System.out.print(number);
}
// Outputs: 12345

Used to loop around array's or List's

While Loop

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

Do While Loop

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

Continue Statement

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

Break Statement

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

Java Collections Framework {.cols-3}

Java Collections {.col-span-2}

CollectionInterfaceOrderedSortedThread safeDuplicateNullable
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
{.show-header .left-text}

ArrayList

List<Integer> nums = newArrayList<>();
// Addingnums.add(2);
nums.add(5);
nums.add(8);
// RetrievingSystem.out.println(nums.get(0));
// Indexed for loop iterationfor (inti = 0; i < nums.size(); i++) {
System.out.println(nums.get(i));
}
nums.remove(nums.size() - 1);
nums.remove(0); // VERY slowfor (Integervalue : nums) {
System.out.println(value);
}

HashMap

Map<Integer, String> m = newHashMap<>();
m.put(5, "Five");
m.put(8, "Eight");
m.put(6, "Six");
m.put(4, "Four");
m.put(2, "Two");
// RetrievingSystem.out.println(m.get(6));
// Lambda forEachm.forEach((key, value) -> {
Stringmsg = key + ": " + value;
System.out.println(msg);
});

HashSet

Set<String> set = newHashSet<>();
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 (Stringelement : set) {
System.out.println(element);
}

ArrayDeque

Deque<String> a = newArrayDeque<>();
// Using add()a.add("Dog");
// Using addFirst()a.addFirst("Cat");
// Using addLast()a.addLast("Horse");
// [Cat, Dog, Horse]System.out.println(a);
// Access elementSystem.out.println(a.peek());
// Remove elementSystem.out.println(a.pop());

Misc {.cols-3}

Access Modifiers {.col-span-2}

ModifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN
{.show-header .left-text}

Regular expressions

Stringtext = "I am learning Java";
// Removing All Whitespacetext.replaceAll("\\s+", "");
// Splitting a Stringtext.split("\\|");
text.split(Pattern.quote("|"));

See: Regex in java

Comment

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

Keywords {.col-span-2}

  • 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 {.style-none .cols-7}

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

try {
// something
} catch (Exceptione) {
e.printStackTrace();
} finally {
System.out.println("always printed");
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

History
775 lines (623 loc) · 16.6 KB

File metadata and controls

775 lines (623 loc) · 16.6 KB
titleJava
date2021-03-10 11:50:01 -0800
iconicon-java
backgroundbg-red-700
tags
object-oriented
class
categories
Programming
introThis cheat sheet is a crash course for Java beginners and help review the basic syntax of the Java language.
plugins
tooltip

Getting started {.cols-3}

Hello.java {.row-span-2}

publicclassHello {
// main methordpublicstaticvoidmain(String[] args)
{
// Output: Hello, world!System.out.println("Hello, world!");
}
}

Compiling and running

$ javac Hello.java
$ java Hello
Hello, world!

Variables

intnum = 5;
floatfloatNum = 5.99f;
charletter = 'D';
booleanbool = true;
Stringsite = "quickref.me";

Primitive Data Types {.row-span-2}

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

Stringfirst = "John";
Stringlast = "Doe";
Stringname = first + " " + last;
System.out.println(name);

See: Strings

Loops

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

See: Loops

Arrays

char[] chars = newchar[10];
chars[0] = 'a'chars[1] = 'b'String[] letters = {"A", "B", "C"};
int[] mylist = {100, 200};
boolean[] answers = {true, false};

See: Arrays

Swap

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

Type Casting

// Widening// byte<short<int<long<float<doubleinti = 10;
longl = i; // 10// Narrowing doubled = 10.02;
longl = (long)d; // 10String.valueOf(10); // "10"Integer.parseInt("10"); // 10Double.parseDouble("10"); // 10.0

Conditionals

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

See: Conditionals

User Input

Scannerin = newScanner(System.in);
Stringstr = in.nextLine();
System.out.println(str);
intnum = in.nextInt();
System.out.println(num);

Java Strings {.cols-3}

Basic

Stringstr1 = "value"; Stringstr2 = newString("value");
Stringstr3 = String.valueOf(123);

Concatenation

Strings = 3 + "str" + 3; // 3str3Strings = 3 + 3 + "str"; // 6strStrings = "3" + 3 + "str"; // 33strStrings = "3" + "3" + "23"; // 3323Strings = "" + 3 + 3 + "23"; // 3323Strings = 3 + 3 + 23; // 29

StringBuilder {.row-span-3}

StringBuilder sb = new StringBuilder(10);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| | | | | | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("QuickRef");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | R | e | f | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.delete(5, 9);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.insert(0, "My ");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("!");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | ! |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

Comparison

Strings1 = newString("QuickRef"); Strings2 = newString("QuickRef"); s1 == s2// falses1.equals(s2) // true"AB".equalsIgnoreCase("ab") // true

Manipulation

Stringstr = "Abcd";
str.toUpperCase(); // ABCDstr.toLowerCase(); // abcdstr.concat("#"); // Abcd#str.replace("b", "-"); // A-cd" abc ".trim(); // abc"ab".toCharArray(); // {'a', 'b'}

Information

Stringstr = "abcd";
str.charAt(2); // cstr.indexOf("a") // 0str.indexOf("z") // -1str.length(); // 4str.toString(); // abcdstr.substring(2); // cdstr.substring(2,3); // cstr.contains("c"); // truestr.endsWith("d"); // truestr.startsWith("a"); // truestr.isEmpty(); // false

Immutable

Stringstr = "hello";
str.concat("world");
// Outputs: helloSystem.out.println(str);

Stringstr = "hello";
Stringconcat = str.concat("world");
// Outputs: helloworldSystem.out.println(concat);

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

Java Arrays {.cols-3}

Declare

int[] a1;
int[] a2 = {1, 2, 3};
int[] a3 = newint[]{1, 2, 3};
int[] a4 = newint[3];
a4[0] = 1;
a4[2] = 2;
a4[3] = 3;

Modify

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

Loop (Read & Modify)

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

Loop (Read)

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

Multidimensional Arrays

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

Sort

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

Java Conditionals {.cols-3}

Operators {.row-span-2}

  • +
  • -
  • *
  • /
  • %
  • =
  • ++
  • --
  • ! {.style-none .cols-4}

  • ==
  • !=
  • >
  • >=
  • <
  • <= {.style-none .cols-4}

  • &&
  • ||
  • ?:{data-tooltip="Ternary (shorthand for if-then-else statement)"} {.style-none .cols-4}

  • instanceof {.style-none}

  • ~
  • <<
  • >>
  • >>>
  • &
  • ^
  • | {.style-none .cols-4}

If else

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

Switch {.row-span-2}

intmonth = 3;
Stringstr;
switch (month) {
case1:
str = "January";
break;
case2:
str = "February";
break;
case3:
str = "March";
break;
default:
str = "Some other month";
break;
}
// Outputs: Result MarchSystem.out.println("Result " + str);

Ternary operator

inta = 10;
intb = 20;
intmax = (a > b) ? a : b;
// Outputs: 20System.out.println(max);

Java Loops {.cols-3}

For Loop

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

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

Enhanced For Loop

int[] numbers = {1,2,3,4,5};
for (intnumber: numbers) {
System.out.print(number);
}
// Outputs: 12345

Used to loop around array's or List's

While Loop

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

Do While Loop

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

Continue Statement

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

Break Statement

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

Java Collections Framework {.cols-3}

Java Collections {.col-span-2}

CollectionInterfaceOrderedSortedThread safeDuplicateNullable
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
{.show-header .left-text}

ArrayList

List<Integer> nums = newArrayList<>();
// Addingnums.add(2);
nums.add(5);
nums.add(8);
// RetrievingSystem.out.println(nums.get(0));
// Indexed for loop iterationfor (inti = 0; i < nums.size(); i++) {
System.out.println(nums.get(i));
}
nums.remove(nums.size() - 1);
nums.remove(0); // VERY slowfor (Integervalue : nums) {
System.out.println(value);
}

HashMap

Map<Integer, String> m = newHashMap<>();
m.put(5, "Five");
m.put(8, "Eight");
m.put(6, "Six");
m.put(4, "Four");
m.put(2, "Two");
// RetrievingSystem.out.println(m.get(6));
// Lambda forEachm.forEach((key, value) -> {
Stringmsg = key + ": " + value;
System.out.println(msg);
});

HashSet

Set<String> set = newHashSet<>();
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 (Stringelement : set) {
System.out.println(element);
}

ArrayDeque

Deque<String> a = newArrayDeque<>();
// Using add()a.add("Dog");
// Using addFirst()a.addFirst("Cat");
// Using addLast()a.addLast("Horse");
// [Cat, Dog, Horse]System.out.println(a);
// Access elementSystem.out.println(a.peek());
// Remove elementSystem.out.println(a.pop());

Misc {.cols-3}

Access Modifiers {.col-span-2}

ModifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN
{.show-header .left-text}

Regular expressions

Stringtext = "I am learning Java";
// Removing All Whitespacetext.replaceAll("\\s+", "");
// Splitting a Stringtext.split("\\|");
text.split(Pattern.quote("|"));

See: Regex in java

Comment

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

Keywords {.col-span-2}

  • 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 {.style-none .cols-7}

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

try {
// something
} catch (Exceptione) {
e.printStackTrace();
} finally {
System.out.println("always printed");
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
775 lines (623 loc) · 16.6 KB

File metadata and controls

775 lines (623 loc) · 16.6 KB
titleJava
date2021-03-10 11:50:01 -0800
iconicon-java
backgroundbg-red-700
tags
object-oriented
class
categories
Programming
introThis cheat sheet is a crash course for Java beginners and help review the basic syntax of the Java language.
plugins
tooltip

Getting started {.cols-3}

Hello.java {.row-span-2}

publicclassHello {
// main methordpublicstaticvoidmain(String[] args)
{
// Output: Hello, world!System.out.println("Hello, world!");
}
}

Compiling and running

$ javac Hello.java
$ java Hello
Hello, world!

Variables

intnum = 5;
floatfloatNum = 5.99f;
charletter = 'D';
booleanbool = true;
Stringsite = "quickref.me";

Primitive Data Types {.row-span-2}

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

Stringfirst = "John";
Stringlast = "Doe";
Stringname = first + " " + last;
System.out.println(name);

See: Strings

Loops

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

See: Loops

Arrays

char[] chars = newchar[10];
chars[0] = 'a'chars[1] = 'b'String[] letters = {"A", "B", "C"};
int[] mylist = {100, 200};
boolean[] answers = {true, false};

See: Arrays

Swap

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

Type Casting

// Widening// byte<short<int<long<float<doubleinti = 10;
longl = i; // 10// Narrowing doubled = 10.02;
longl = (long)d; // 10String.valueOf(10); // "10"Integer.parseInt("10"); // 10Double.parseDouble("10"); // 10.0

Conditionals

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

See: Conditionals

User Input

Scannerin = newScanner(System.in);
Stringstr = in.nextLine();
System.out.println(str);
intnum = in.nextInt();
System.out.println(num);

Java Strings {.cols-3}

Basic

Stringstr1 = "value"; Stringstr2 = newString("value");
Stringstr3 = String.valueOf(123);

Concatenation

Strings = 3 + "str" + 3; // 3str3Strings = 3 + 3 + "str"; // 6strStrings = "3" + 3 + "str"; // 33strStrings = "3" + "3" + "23"; // 3323Strings = "" + 3 + 3 + "23"; // 3323Strings = 3 + 3 + 23; // 29

StringBuilder {.row-span-3}

StringBuilder sb = new StringBuilder(10);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| | | | | | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("QuickRef");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | R | e | f | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.delete(5, 9);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.insert(0, "My ");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("!");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | ! |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

Comparison

Strings1 = newString("QuickRef"); Strings2 = newString("QuickRef"); s1 == s2// falses1.equals(s2) // true"AB".equalsIgnoreCase("ab") // true

Manipulation

Stringstr = "Abcd";
str.toUpperCase(); // ABCDstr.toLowerCase(); // abcdstr.concat("#"); // Abcd#str.replace("b", "-"); // A-cd" abc ".trim(); // abc"ab".toCharArray(); // {'a', 'b'}

Information

Stringstr = "abcd";
str.charAt(2); // cstr.indexOf("a") // 0str.indexOf("z") // -1str.length(); // 4str.toString(); // abcdstr.substring(2); // cdstr.substring(2,3); // cstr.contains("c"); // truestr.endsWith("d"); // truestr.startsWith("a"); // truestr.isEmpty(); // false

Immutable

Stringstr = "hello";
str.concat("world");
// Outputs: helloSystem.out.println(str);

Stringstr = "hello";
Stringconcat = str.concat("world");
// Outputs: helloworldSystem.out.println(concat);

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

Java Arrays {.cols-3}

Declare

int[] a1;
int[] a2 = {1, 2, 3};
int[] a3 = newint[]{1, 2, 3};
int[] a4 = newint[3];
a4[0] = 1;
a4[2] = 2;
a4[3] = 3;

Modify

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

Loop (Read & Modify)

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

Loop (Read)

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

Multidimensional Arrays

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

Sort

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

Java Conditionals {.cols-3}

Operators {.row-span-2}

  • +
  • -
  • *
  • /
  • %
  • =
  • ++
  • --
  • ! {.style-none .cols-4}

  • ==
  • !=
  • >
  • >=
  • <
  • <= {.style-none .cols-4}

  • &&
  • ||
  • ?:{data-tooltip="Ternary (shorthand for if-then-else statement)"} {.style-none .cols-4}

  • instanceof {.style-none}

  • ~
  • <<
  • >>
  • >>>
  • &
  • ^
  • | {.style-none .cols-4}

If else

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

Switch {.row-span-2}

intmonth = 3;
Stringstr;
switch (month) {
case1:
str = "January";
break;
case2:
str = "February";
break;
case3:
str = "March";
break;
default:
str = "Some other month";
break;
}
// Outputs: Result MarchSystem.out.println("Result " + str);

Ternary operator

inta = 10;
intb = 20;
intmax = (a > b) ? a : b;
// Outputs: 20System.out.println(max);

Java Loops {.cols-3}

For Loop

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

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

Enhanced For Loop

int[] numbers = {1,2,3,4,5};
for (intnumber: numbers) {
System.out.print(number);
}
// Outputs: 12345

Used to loop around array's or List's

While Loop

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

Do While Loop

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

Continue Statement

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

Break Statement

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

Java Collections Framework {.cols-3}

Java Collections {.col-span-2}

CollectionInterfaceOrderedSortedThread safeDuplicateNullable
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
{.show-header .left-text}

ArrayList

List<Integer> nums = newArrayList<>();
// Addingnums.add(2);
nums.add(5);
nums.add(8);
// RetrievingSystem.out.println(nums.get(0));
// Indexed for loop iterationfor (inti = 0; i < nums.size(); i++) {
System.out.println(nums.get(i));
}
nums.remove(nums.size() - 1);
nums.remove(0); // VERY slowfor (Integervalue : nums) {
System.out.println(value);
}

HashMap

Map<Integer, String> m = newHashMap<>();
m.put(5, "Five");
m.put(8, "Eight");
m.put(6, "Six");
m.put(4, "Four");
m.put(2, "Two");
// RetrievingSystem.out.println(m.get(6));
// Lambda forEachm.forEach((key, value) -> {
Stringmsg = key + ": " + value;
System.out.println(msg);
});

HashSet

Set<String> set = newHashSet<>();
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 (Stringelement : set) {
System.out.println(element);
}

ArrayDeque

Deque<String> a = newArrayDeque<>();
// Using add()a.add("Dog");
// Using addFirst()a.addFirst("Cat");
// Using addLast()a.addLast("Horse");
// [Cat, Dog, Horse]System.out.println(a);
// Access elementSystem.out.println(a.peek());
// Remove elementSystem.out.println(a.pop());

Misc {.cols-3}

Access Modifiers {.col-span-2}

ModifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN
{.show-header .left-text}

Regular expressions

Stringtext = "I am learning Java";
// Removing All Whitespacetext.replaceAll("\\s+", "");
// Splitting a Stringtext.split("\\|");
text.split(Pattern.quote("|"));

See: Regex in java

Comment

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

Keywords {.col-span-2}

  • 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 {.style-none .cols-7}

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

try {
// something
} catch (Exceptione) {
e.printStackTrace();
} finally {
System.out.println("always printed");
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
775 lines (623 loc) · 16.6 KB

File metadata and controls

775 lines (623 loc) · 16.6 KB
titleJava
date2021-03-10 11:50:01 -0800
iconicon-java
backgroundbg-red-700
tags
object-oriented
class
categories
Programming
introThis cheat sheet is a crash course for Java beginners and help review the basic syntax of the Java language.
plugins
tooltip

Getting started {.cols-3}

Hello.java {.row-span-2}

publicclassHello {
// main methordpublicstaticvoidmain(String[] args)
{
// Output: Hello, world!System.out.println("Hello, world!");
}
}

Compiling and running

$ javac Hello.java
$ java Hello
Hello, world!

Variables

intnum = 5;
floatfloatNum = 5.99f;
charletter = 'D';
booleanbool = true;
Stringsite = "quickref.me";

Primitive Data Types {.row-span-2}

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

Stringfirst = "John";
Stringlast = "Doe";
Stringname = first + " " + last;
System.out.println(name);

See: Strings

Loops

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

See: Loops

Arrays

char[] chars = newchar[10];
chars[0] = 'a'chars[1] = 'b'String[] letters = {"A", "B", "C"};
int[] mylist = {100, 200};
boolean[] answers = {true, false};

See: Arrays

Swap

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

Type Casting

// Widening// byte<short<int<long<float<doubleinti = 10;
longl = i; // 10// Narrowing doubled = 10.02;
longl = (long)d; // 10String.valueOf(10); // "10"Integer.parseInt("10"); // 10Double.parseDouble("10"); // 10.0

Conditionals

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

See: Conditionals

User Input

Scannerin = newScanner(System.in);
Stringstr = in.nextLine();
System.out.println(str);
intnum = in.nextInt();
System.out.println(num);

Java Strings {.cols-3}

Basic

Stringstr1 = "value"; Stringstr2 = newString("value");
Stringstr3 = String.valueOf(123);

Concatenation

Strings = 3 + "str" + 3; // 3str3Strings = 3 + 3 + "str"; // 6strStrings = "3" + 3 + "str"; // 33strStrings = "3" + "3" + "23"; // 3323Strings = "" + 3 + 3 + "23"; // 3323Strings = 3 + 3 + 23; // 29

StringBuilder {.row-span-3}

StringBuilder sb = new StringBuilder(10);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| | | | | | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("QuickRef");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | R | e | f | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.delete(5, 9);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.insert(0, "My ");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("!");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | ! |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

Comparison

Strings1 = newString("QuickRef"); Strings2 = newString("QuickRef"); s1 == s2// falses1.equals(s2) // true"AB".equalsIgnoreCase("ab") // true

Manipulation

Stringstr = "Abcd";
str.toUpperCase(); // ABCDstr.toLowerCase(); // abcdstr.concat("#"); // Abcd#str.replace("b", "-"); // A-cd" abc ".trim(); // abc"ab".toCharArray(); // {'a', 'b'}

Information

Stringstr = "abcd";
str.charAt(2); // cstr.indexOf("a") // 0str.indexOf("z") // -1str.length(); // 4str.toString(); // abcdstr.substring(2); // cdstr.substring(2,3); // cstr.contains("c"); // truestr.endsWith("d"); // truestr.startsWith("a"); // truestr.isEmpty(); // false

Immutable

Stringstr = "hello";
str.concat("world");
// Outputs: helloSystem.out.println(str);

Stringstr = "hello";
Stringconcat = str.concat("world");
// Outputs: helloworldSystem.out.println(concat);

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

Java Arrays {.cols-3}

Declare

int[] a1;
int[] a2 = {1, 2, 3};
int[] a3 = newint[]{1, 2, 3};
int[] a4 = newint[3];
a4[0] = 1;
a4[2] = 2;
a4[3] = 3;

Modify

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

Loop (Read & Modify)

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

Loop (Read)

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

Multidimensional Arrays

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

Sort

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

Java Conditionals {.cols-3}

Operators {.row-span-2}

  • +
  • -
  • *
  • /
  • %
  • =
  • ++
  • --
  • ! {.style-none .cols-4}

  • ==
  • !=
  • >
  • >=
  • <
  • <= {.style-none .cols-4}

  • &&
  • ||
  • ?:{data-tooltip="Ternary (shorthand for if-then-else statement)"} {.style-none .cols-4}

  • instanceof {.style-none}

  • ~
  • <<
  • >>
  • >>>
  • &
  • ^
  • | {.style-none .cols-4}

If else

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

Switch {.row-span-2}

intmonth = 3;
Stringstr;
switch (month) {
case1:
str = "January";
break;
case2:
str = "February";
break;
case3:
str = "March";
break;
default:
str = "Some other month";
break;
}
// Outputs: Result MarchSystem.out.println("Result " + str);

Ternary operator

inta = 10;
intb = 20;
intmax = (a > b) ? a : b;
// Outputs: 20System.out.println(max);

Java Loops {.cols-3}

For Loop

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

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

Enhanced For Loop

int[] numbers = {1,2,3,4,5};
for (intnumber: numbers) {
System.out.print(number);
}
// Outputs: 12345

Used to loop around array's or List's

While Loop

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

Do While Loop

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

Continue Statement

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

Break Statement

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

Java Collections Framework {.cols-3}

Java Collections {.col-span-2}

CollectionInterfaceOrderedSortedThread safeDuplicateNullable
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
{.show-header .left-text}

ArrayList

List<Integer> nums = newArrayList<>();
// Addingnums.add(2);
nums.add(5);
nums.add(8);
// RetrievingSystem.out.println(nums.get(0));
// Indexed for loop iterationfor (inti = 0; i < nums.size(); i++) {
System.out.println(nums.get(i));
}
nums.remove(nums.size() - 1);
nums.remove(0); // VERY slowfor (Integervalue : nums) {
System.out.println(value);
}

HashMap

Map<Integer, String> m = newHashMap<>();
m.put(5, "Five");
m.put(8, "Eight");
m.put(6, "Six");
m.put(4, "Four");
m.put(2, "Two");
// RetrievingSystem.out.println(m.get(6));
// Lambda forEachm.forEach((key, value) -> {
Stringmsg = key + ": " + value;
System.out.println(msg);
});

HashSet

Set<String> set = newHashSet<>();
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 (Stringelement : set) {
System.out.println(element);
}

ArrayDeque

Deque<String> a = newArrayDeque<>();
// Using add()a.add("Dog");
// Using addFirst()a.addFirst("Cat");
// Using addLast()a.addLast("Horse");
// [Cat, Dog, Horse]System.out.println(a);
// Access elementSystem.out.println(a.peek());
// Remove elementSystem.out.println(a.pop());

Misc {.cols-3}

Access Modifiers {.col-span-2}

ModifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN
{.show-header .left-text}

Regular expressions

Stringtext = "I am learning Java";
// Removing All Whitespacetext.replaceAll("\\s+", "");
// Splitting a Stringtext.split("\\|");
text.split(Pattern.quote("|"));

See: Regex in java

Comment

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

Keywords {.col-span-2}

  • 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 {.style-none .cols-7}

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

try {
// something
} catch (Exceptione) {
e.printStackTrace();
} finally {
System.out.println("always printed");
}
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

History
775 lines (623 loc) · 16.6 KB

File metadata and controls

775 lines (623 loc) · 16.6 KB
titleJava
date2021-03-10 11:50:01 -0800
iconicon-java
backgroundbg-red-700
tags
object-oriented
class
categories
Programming
introThis cheat sheet is a crash course for Java beginners and help review the basic syntax of the Java language.
plugins
tooltip

Getting started {.cols-3}

Hello.java {.row-span-2}

publicclassHello {
// main methordpublicstaticvoidmain(String[] args)
{
// Output: Hello, world!System.out.println("Hello, world!");
}
}

Compiling and running

$ javac Hello.java
$ java Hello
Hello, world!

Variables

intnum = 5;
floatfloatNum = 5.99f;
charletter = 'D';
booleanbool = true;
Stringsite = "quickref.me";

Primitive Data Types {.row-span-2}

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

Stringfirst = "John";
Stringlast = "Doe";
Stringname = first + " " + last;
System.out.println(name);

See: Strings

Loops

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

See: Loops

Arrays

char[] chars = newchar[10];
chars[0] = 'a'chars[1] = 'b'String[] letters = {"A", "B", "C"};
int[] mylist = {100, 200};
boolean[] answers = {true, false};

See: Arrays

Swap

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

Type Casting

// Widening// byte<short<int<long<float<doubleinti = 10;
longl = i; // 10// Narrowing doubled = 10.02;
longl = (long)d; // 10String.valueOf(10); // "10"Integer.parseInt("10"); // 10Double.parseDouble("10"); // 10.0

Conditionals

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

See: Conditionals

User Input

Scannerin = newScanner(System.in);
Stringstr = in.nextLine();
System.out.println(str);
intnum = in.nextInt();
System.out.println(num);

Java Strings {.cols-3}

Basic

Stringstr1 = "value"; Stringstr2 = newString("value");
Stringstr3 = String.valueOf(123);

Concatenation

Strings = 3 + "str" + 3; // 3str3Strings = 3 + 3 + "str"; // 6strStrings = "3" + 3 + "str"; // 33strStrings = "3" + "3" + "23"; // 3323Strings = "" + 3 + 3 + "23"; // 3323Strings = 3 + 3 + 23; // 29

StringBuilder {.row-span-3}

StringBuilder sb = new StringBuilder(10);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| | | | | | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("QuickRef");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | R | e | f | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.delete(5, 9);

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.insert(0, "My ");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

sb.append("!");

┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | ! |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789

Comparison

Strings1 = newString("QuickRef"); Strings2 = newString("QuickRef"); s1 == s2// falses1.equals(s2) // true"AB".equalsIgnoreCase("ab") // true

Manipulation

Stringstr = "Abcd";
str.toUpperCase(); // ABCDstr.toLowerCase(); // abcdstr.concat("#"); // Abcd#str.replace("b", "-"); // A-cd" abc ".trim(); // abc"ab".toCharArray(); // {'a', 'b'}

Information

Stringstr = "abcd";
str.charAt(2); // cstr.indexOf("a") // 0str.indexOf("z") // -1str.length(); // 4str.toString(); // abcdstr.substring(2); // cdstr.substring(2,3); // cstr.contains("c"); // truestr.endsWith("d"); // truestr.startsWith("a"); // truestr.isEmpty(); // false

Immutable

Stringstr = "hello";
str.concat("world");
// Outputs: helloSystem.out.println(str);

Stringstr = "hello";
Stringconcat = str.concat("world");
// Outputs: helloworldSystem.out.println(concat);

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

Java Arrays {.cols-3}

Declare

int[] a1;
int[] a2 = {1, 2, 3};
int[] a3 = newint[]{1, 2, 3};
int[] a4 = newint[3];
a4[0] = 1;
a4[2] = 2;
a4[3] = 3;

Modify

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

Loop (Read & Modify)

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

Loop (Read)

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

Multidimensional Arrays

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

Sort

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

Java Conditionals {.cols-3}

Operators {.row-span-2}

  • +
  • -
  • *
  • /
  • %
  • =
  • ++
  • --
  • ! {.style-none .cols-4}

  • ==
  • !=
  • >
  • >=
  • <
  • <= {.style-none .cols-4}

  • &&
  • ||
  • ?:{data-tooltip="Ternary (shorthand for if-then-else statement)"} {.style-none .cols-4}

  • instanceof {.style-none}

  • ~
  • <<
  • >>
  • >>>
  • &
  • ^
  • | {.style-none .cols-4}

If else

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

Switch {.row-span-2}

intmonth = 3;
Stringstr;
switch (month) {
case1:
str = "January";
break;
case2:
str = "February";
break;
case3:
str = "March";
break;
default:
str = "Some other month";
break;
}
// Outputs: Result MarchSystem.out.println("Result " + str);

Ternary operator

inta = 10;
intb = 20;
intmax = (a > b) ? a : b;
// Outputs: 20System.out.println(max);

Java Loops {.cols-3}

For Loop

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

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

Enhanced For Loop

int[] numbers = {1,2,3,4,5};
for (intnumber: numbers) {
System.out.print(number);
}
// Outputs: 12345

Used to loop around array's or List's

While Loop

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

Do While Loop

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

Continue Statement

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

Break Statement

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

Java Collections Framework {.cols-3}

Java Collections {.col-span-2}

CollectionInterfaceOrderedSortedThread safeDuplicateNullable
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
{.show-header .left-text}

ArrayList

List<Integer> nums = newArrayList<>();
// Addingnums.add(2);
nums.add(5);
nums.add(8);
// RetrievingSystem.out.println(nums.get(0));
// Indexed for loop iterationfor (inti = 0; i < nums.size(); i++) {
System.out.println(nums.get(i));
}
nums.remove(nums.size() - 1);
nums.remove(0); // VERY slowfor (Integervalue : nums) {
System.out.println(value);
}

HashMap

Map<Integer, String> m = newHashMap<>();
m.put(5, "Five");
m.put(8, "Eight");
m.put(6, "Six");
m.put(4, "Four");
m.put(2, "Two");
// RetrievingSystem.out.println(m.get(6));
// Lambda forEachm.forEach((key, value) -> {
Stringmsg = key + ": " + value;
System.out.println(msg);
});

HashSet

Set<String> set = newHashSet<>();
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 (Stringelement : set) {
System.out.println(element);
}

ArrayDeque

Deque<String> a = newArrayDeque<>();
// Using add()a.add("Dog");
// Using addFirst()a.addFirst("Cat");
// Using addLast()a.addLast("Horse");
// [Cat, Dog, Horse]System.out.println(a);
// Access elementSystem.out.println(a.peek());
// Remove elementSystem.out.println(a.pop());

Misc {.cols-3}

Access Modifiers {.col-span-2}

ModifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN
{.show-header .left-text}

Regular expressions

Stringtext = "I am learning Java";
// Removing All Whitespacetext.replaceAll("\\s+", "");
// Splitting a Stringtext.split("\\|");
text.split(Pattern.quote("|"));

See: Regex in java

Comment

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

Keywords {.col-span-2}

  • 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 {.style-none .cols-7}

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

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