| title | Java | ||
|---|---|---|---|
| date | 2021-03-10 11:50:01 -0800 | ||
| icon | icon-java | ||
| background | bg-red-700 | ||
| tags |
| ||
| categories |
| ||
| intro | This cheat sheet is a crash course for Java beginners and help review the basic syntax of the Java language. | ||
| plugins |
|
publicclassHello {
// main methordpublicstaticvoidmain(String[] args)
{
// Output: Hello, world!System.out.println("Hello, world!");
}
}Compiling and running
$ javac Hello.java
$ java Hello
Hello, world!intnum = 5;
floatfloatNum = 5.99f;
charletter = 'D';
booleanbool = true;
Stringsite = "quickref.me";| Data Type | Size | Default | Range |
|---|---|---|---|
byte | 1 byte | 0 | -128 ^to^ 127 |
short | 2 byte | 0 | -2^15^ ^to^ 2^15^-1 |
int | 4 byte | 0 | -2^31^ ^to^ 2^31^-1 |
long | 8 byte | 0 | -2^63^ ^to^ 2^63^-1 |
float | 4 byte | 0.0f | N/A |
double | 8 byte | 0.0d | N/A |
char | 2 byte | \u0000 | 0 ^to^ 65535 |
boolean | N/A | false | true / false |
| {.show-header} |
Stringfirst = "John";
Stringlast = "Doe";
Stringname = first + " " + last;
System.out.println(name);See: Strings
Stringword = "QuickRef";
for (charc: word.toCharArray()) {
System.out.print(c + "-");
}
// Outputs: Q-u-i-c-k-R-e-f-See: Loops
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
inta = 1;
intb = 2;
System.out.println(a + " " + b); // 1 2inttemp = a;
a = b;
b = temp;
System.out.println(a + " " + b); // 2 1// 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.0intj = 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
Scannerin = newScanner(System.in);
Stringstr = in.nextLine();
System.out.println(str);
intnum = in.nextInt();
System.out.println(num);Stringstr1 = "value"; Stringstr2 = newString("value");
Stringstr3 = String.valueOf(123);Strings = 3 + "str" + 3; // 3str3Strings = 3 + 3 + "str"; // 6strStrings = "3" + 3 + "str"; // 33strStrings = "3" + "3" + "23"; // 3323Strings = "" + 3 + 3 + "23"; // 3323Strings = 3 + 3 + 23; // 29StringBuilder sb = new StringBuilder(10);
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| | | | | | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789sb.append("QuickRef");
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | R | e | f | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789sb.delete(5, 9);
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| Q | u | i | c | k | | | | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789sb.insert(0, "My ");
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789sb.append("!");
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
| M | y | | Q | u | i | c | k | ! |
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
0123456789Strings1 = newString("QuickRef"); Strings2 = newString("QuickRef"); s1 == s2// falses1.equals(s2) // true"AB".equalsIgnoreCase("ab") // trueStringstr = "Abcd";
str.toUpperCase(); // ABCDstr.toLowerCase(); // abcdstr.concat("#"); // Abcd#str.replace("b", "-"); // A-cd" abc ".trim(); // abc"ab".toCharArray(); // {'a', 'b'}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(); // falseStringstr = "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
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;int[] a = {1, 2, 3};
System.out.println(a[0]); // 1a[0] = 9;
System.out.println(a[0]); // 9System.out.println(a.length); // 3int[] arr = {1, 2, 3};
for (inti=0; i < arr.length; i++) {
arr[i] = arr[i] * 2;
System.out.print(arr[i] + " ");
}
// Outputs: 2 4 6String[] arr = {"a", "b", "c"};
for (inta: arr) {
System.out.print(a + " ");
}
// Outputs: a b c 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 char[] chars = {'b', 'a', 'c'};
Arrays.sort(chars);
// [a, b, c]Arrays.toString(chars);- +
- -
- *
- /
- %
- =
- ++
- --
- ! {.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}
intk = 15;
if (k > 20) {
System.out.println(1);
} elseif (k > 10) {
System.out.println(2);
} else {
System.out.println(3);
}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);inta = 10;
intb = 20;
intmax = (a > b) ? a : b;
// Outputs: 20System.out.println(max);for (inti = 0; i < 10; i++) {
System.out.print(i);
}
// Outputs: 0123456789for (inti = 0,j = 0; i < 3; i++,j--) {
System.out.print(j + "|" + i + " ");
}
// Outputs: 0|0 -1|1 -2|2int[] numbers = {1,2,3,4,5};
for (intnumber: numbers) {
System.out.print(number);
}
// Outputs: 12345Used to loop around array's or List's
intcount = 0;
while (count < 5) {
System.out.print(count);
count++;
}
// Outputs: 01234intcount = 0;
do{
System.out.print(count);
count++;
} while (count < 5);
// Outputs: 01234for (inti = 0; i < 5; i++) {
if (i == 3) {
continue;
}
System.out.print(i);
}
// Outputs: 01245for (inti = 0; i < 5; i++) {
System.out.print(i);
if (i == 3) {
break;
}
}
// Outputs: 0123| Collection | Interface | Ordered | Sorted | Thread safe | Duplicate | Nullable |
|---|---|---|---|---|---|---|
| ArrayList | List | Y | N | N | Y | Y |
| Vector | List | Y | N | Y | Y | Y |
| LinkedList | List, Deque | Y | N | N | Y | Y |
| HashSet | Set | N | N | N | N | One null |
| LinkedHashSet | Set | Y | N | N | N | One null |
| TreeSet | Set | Y | Y | N | N | N |
| HashMap | Map | N | N | N | N (key) | One null(key) |
| HashTable | Map | N | N | Y | N (key) | N (key) |
| LinkedHashMap | Map | Y | N | N | N (key) | One null(key) |
| TreeMap | Map | Y | Y | N | N (key) | N (key) |
| ArrayDeque | Deque | Y | N | N | Y | N |
| PriorityQueue | Queue | Y | N | N | Y | N |
| {.show-header .left-text} |
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);
}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);
});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);
}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());| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
| public | Y | Y | Y | Y |
| protected | Y | Y | Y | N |
| no modifier | Y | Y | N | N |
| private | Y | N | N | N |
| {.show-header .left-text} |
Stringtext = "I am learning Java";
// Removing All Whitespacetext.replaceAll("\\s+", "");
// Splitting a Stringtext.split("\\|");
text.split(Pattern.quote("|"));See: Regex in java
// I am a single line comment!/*And I am a multi-line comment!*//** * This * is * documentation * comment */- abstract
- continue
- for
- new
- switch
- assert
- default
- goto
- package
- synchronized
- boolean
- do
- if
- private
- this
- break
- double
- implements
- protected
- throw
- byte
- else
- import
- public
- throws
- case
- enum
- instanceof
- return
- transient
- catch
- extends
- int
- short
- try
- char
- final
- interface
- static
- void
- class
- finally
- long
- strictfp
- volatile
- const
- float
- native
- super
- while {.style-none .cols-7}
| Method | Description |
|---|---|
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 {
// something
} catch (Exceptione) {
e.printStackTrace();
} finally {
System.out.println("always printed");
}