Java CheatSheet

Indulge in the power of Java with our comprehensive and sophisticated cheat sheet. Whether you're a professional developer or just starting on your coding journey, our Java Cheat Sheet is the ultimate reference guide for mastering the language. With its concise yet expansive layout, our cheat sheet provides an extensive list of all the essential syntax, keywords, and concepts that are crucial to developing high-performing, scalable applications using Java.

Designed by seasoned experts, our Java Cheat Sheet showcases the best practices and advanced techniques that will take your coding skills to new heights. Inside, you'll find carefully curated examples that demonstrate how to leverage the full potential of Java, from object-oriented programming and multithreading to exception handling and stream processing.

With our Java Cheat Sheet, you can say goodbye to tedious searches through endless documentation and hello to streamlined productivity. Whether you need a quick refresher or an in-depth exploration of Java's capabilities, our cheat sheet has got you covered. Download it today and unlock the full potential of this powerful programming language!


Table of Content




# Getting started Java


Java Introduction

Java is a class-based, object-oriented programming language and is designed to have as few implementation dependencies as possible. A general-purpose programming language made for developers to write once run anywhere that is compiled Java code can run on all platforms that support Java. Java applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of Java is similar to c/c++.



Object-Oriented Programming Language: based on the concepts of objects.

Open Source: Readily available for development.

Platform-neutral: Java code is independent of any particular hardware or software. This is because Java code is compiled by the compiler and converted into byte code. Thus, byte code is platform-independent and can run on multiple systems. The only requirement is Java needs a runtime environment, i.e., JRE, which is a set of tools used for developing Java applications.

Memory Management: Garbage collected language, i.e., deallocation of memory.

Exception Handling: Catches a series of errors or abnormality, thus eliminating any risk of crashing the system.

HelloWorld.java

public class HelloWorld {
    // main methord
    public static void main(String[] args)
    {
        System.out.println("Getting Started, Hello world!");
    }
    // Output: Getting Started, Hello world!
}

Compiling and running

$ javac HelloWorld.java

$ java HelloWorld

Getting Started, Hello world!

Variables

int num = 5; // Integer
float floatNum = 5.99f; // Float
char letter = 'D'; // Character
boolean bool = true; // Boolean true/false
String name = "Jack Willsion"; // String

Strings

String first = "Jack";
String last = "Will";
String name = first + " " + last;
System.out.println(name);

// Outputs: Jack Will

Primitive Data Types

Data Type Size Default Range
byte 1 byte 0 -128 to 127
short 2 byte 0 -215 to 215-1
int 4 byte 0 -231 to 231-1
long 8 byte 0 -263 to 263-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

Loops

String word = "Google";
for (char c: word.toCharArray()) {
  System.out.print(c + "-");
}
// Outputs: G-o-o-g-l-e

Arrays

char[] chars = new char[10];
chars[0] = 'c'
chars[1] = 'd'

String[] letters = {"D", "E", "F"};
int[] mylist = {351, 469};
boolean[] answers = {true, false};

Swap

int a = 1;
int b = 2;
System.out.println(a + " " + b); 
// Outputs: 1 2

int temp = a;
a = b;
b = temp;
System.out.println(a + " " + b); 
// Outputs: 2 1

Type Casting

int i = 11;
long l = i;               // 11

// Narrowing 
double d = 11.02;
long l = (long) d;         // 11

String.valueOf(11);       // "11"
Integer.parseInt("11");   // 11
Double.parseDouble("11"); // 11.0

Conditionals

int j = 11;

if (j == 11) {
  System.out.println("Equal 11");
} else if (j > 11) {
  System.out.println("Greater than 11");
} else {
  System.out.println("Less than 11");
}

// Outputs: Equal 11

User Input

Scanner in = new Scanner(System.in);
String str = in.nextLine();
System.out.println(str);

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

# Strings in Java


Basic

In Java, a string is an object that represents a sequence of characters or char values. The java.lang.String class is used to create a Java string object.

// By string literal
String str1 = "your string";

// By new keyword
String str2 = new String("your string");

String str3 = String.valueOf(12345);

Concatenation

String s = 3 + "str" + 3;     // 3str3
String s = 3 + 3 + "str";     // 6str
String s = "3" + 3 + "str";   // 33str
String s = "3" + "3" + "23";  // 3323
String s = "" + 3 + 3 + "23"; // 3323
String s = 3 + 3 + 23;        // 29

StringBuilder

StringBuilder sb = new StringBuilder(10);
    
        ?????????????????????????????????????
        |   |   |   |   |   |   |   |   |   |
        ?????????????????????????????????????
        0   1   2   3   4   5   6   7   8   9
    

sb.append("Google");
    
        ?????????????????????????????????????
        | G | o | o | g | l | e |   |   |   |
        ?????????????????????????????????????
        0   1   2   3   4   5   6   7   8   9
    

sb.delete(5, 9);
    
        ?????????????????????????????????????
        | G | o | o | g | l |   |   |   |   |
        ?????????????????????????????????????
        0   1   2   3   4   5   6   7   8   9
    

sb.insert(0, "My ");
    
        ?????????????????????????????????????
        | M | y |   | G | o | o | g | l |   |
        ?????????????????????????????????????
        0   1   2   3   4   5   6   7   8   9
    

sb.append("!");
    
        ?????????????????????????????????????
        | M | y |   | G | o | o | g | l | ! |
        ?????????????????????????????????????
        0   1   2   3   4   5   6   7   8   9
    

Comparison

String s1 = new String("Google"); 
String s2 = new String("Google"); 

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

"AB".equalsIgnoreCase("ab")  // true

Manipulation

String str = "Google";

str.toUpperCase();     // GOOGLE
str.toLowerCase();     // google
str.concat("#");       // Google#
str.replace("G", "-"); // -oogle

"  abc ".trim();       // abc
"ab".toCharArray();    // {'a', 'b'}

Information

String str = "abcd";

str.charAt(2);       // c
str.indexOf("a")     // 0
str.indexOf("z")     // -1
str.length();        // 4
str.toString();      // abcd
str.substring(2);    // cd
str.substring(2,3);  // c
str.contains("c");   // true
str.endsWith("d");   // true
str.startsWith("a"); // true
str.isEmpty();       // false

Immutable

In Java, String is a final and immutable class, which makes it the most special. It cannot be inherited, and once created, we can not alter the object. String object is one of the most-used objects in any of the programs.

String str = "My name is";
str.concat("Jack");

System.out.println(str);
// Outputs: My name is


// ----------------------
String str = "My name is ";
String concat = str.concat("Jack");

System.out.println(concat);
// Outputs: My name is Jack

# Arrays in Java


Declare

int[] a1;
int[] a2 = {4, 5, 6};
int[] a3 = new int[]{1, 2, 3};

int[] a4 = new int[3];
a4[0] = 1;
a4[2] = 2;
a4[3] = 3;

Modify

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

a[0] = 10;
System.out.println(a[0]); // 10

System.out.println(a.length); // 3

Loop (Read & Modify)

int[] arr = {2, 3, 4};

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

Loop (Read)

String[] arr = {"h", "e", "l", "l", "o"};

for (int a: arr) {
    System.out.print(a + " ");
}
// Outputs: h e l l o

Multidimensional Arrays

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

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

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

Sort

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

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

# Conditionals in Java


Operators

+ - * /
% = ++ --
! == != >
>= < <= &&
|| ?: instanceof ~
<< >> >>> &
^ |

If else

int k = 16;

if (k > 21) {
  System.out.println(1);
} else if (k > 11) {
  System.out.println(2);
} else {
  System.out.println(3);
}

// Outputs: 2

Ternary operator

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

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

Switch

int month = 3;
String str;
switch (month) {
  case 1:
    str = "January";
    break;
  case 2:
    str = "February";
    break;
  case 3:
    str = "March";
    break;
  default:
    str = "Some other month";
    break;
}

System.out.println("Result " + str);
// Outputs: Result March

# Loops in Java


For Loop

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

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

Enhanced For Loop

int[] numbers = {1, 2, 3, 4, 5, 6 , 7, 8, 9, 0};

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

While

int count = 0;

while (count < 7) {
  System.out.print(count);
  count++;
}
// Outputs: 0123456

Do While

int count = 0;

do{
  System.out.print(count);
  count++;
} while (count < 7);

// Outputs: 0123456

Continue Statement

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

Break Statement

for (int i = 0; i < 9; i++) {
  System.out.print(i);
  if (i == 4) {
    break;
  }
}
// Outputs: 01234

# Collections Framework in Java


Java Collections

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

ArrayList

List nums = new ArrayList<>();

// Adding
nums.add(2);
nums.add(5);
nums.add(8);

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

// Indexed for loop iteration
for (int i = 0; i < nums.size(); i++) {
    System.out.println(nums.get(i));
}

nums.remove(nums.size() - 1);
nums.remove(0); // VERY slow

for (Integer value : nums) {
    System.out.println(value);
}

HashMap

Map m = new HashMap<>();
m.put(5, "Five");
m.put(8, "Eight");
m.put(6, "Six");
m.put(4, "Four");
m.put(2, "Two");

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

// Lambda forEach
m.forEach((key, value) -> {
    String msg = key + ": " + value;
    System.out.println(msg);
});

HashSet

Set set = new HashSet<>();
if (set.isEmpty()) {
    System.out.println("Empty!");
}

set.add("dog");
set.add("cat");
set.add("mouse");
set.add("snake");
set.add("bear");

if (set.contains("cat")) {
    System.out.println("Contains cat");
}

set.remove("cat");
for (String element : set) {
    System.out.println(element);
}

ArrayDeque

Deque a = new ArrayDeque<>();

// Using add()
a.add("Dog");

// Using addFirst()
a.addFirst("Cat");

// Using addLast()
a.addLast("Horse");

// [Cat, Dog, Horse]
System.out.println(a);

// Access element
System.out.println(a.peek());

// Remove element
System.out.println(a.pop());

# Misc in Java


Access Modifiers

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

Regular expressions

String text = "I am learning Java";
// Removing All Whitespace
text.replaceAll("\\s+", "");

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

Comment

// This is single line comment!
 
/*
And this is
multi-line comment!
*/

/**
 * This  
 * is  
 * documentation  
 * comment 
 */

Keywords

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

Math methods

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 {
  // do something at here .....
} catch (Exception e) {
  e.printStackTrace();
} finally {
  System.out.println("This finally text will always print!!!");
}

// Outputs: This finally text will always print!!!


Best Suggest