☕ java java cheat sheet dev

java

fukurou

the supreme coder
ADMIN
Code:
*variables*

int age = 0; // implicit var declaration
Boolean isCompleted = false; // explicit var declaration
final int num = 2; // constant takes less space than var

*strings*
String str1 = "hello";
String s1 = String.format("%s %s %d :)", "1+4", "=", 5);

*classes*
public class MyClass extends Object {
    int myProperty;

    public MyClass() {
        myProperty = 12;
    }
    // methods
}
MyClass mClass = new MyClass(); // object instance

*methods*
public Boolean myMethod() {
    return true;
}

public int methodWithParams(int a, int b) {
    return a + b;
}

*varargs*
static int sum1(int... values) {
    int total = 0;
    for (int i = 0; i < values.length; i++) {
        total += values[i];
    }
    return total;
}
System.out.println(MyClass.sum1(1, 4, 5));

*arraylist*
import java.util.ArrayList; // import the ArrayList class

ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object

*array*
// String[] cars;
String[] cars = { "Volvo", "BMW", "Ford", "Mazda" };

import java.util.Arrays;
int[] arr = new int[10];
// Fill from index 1 to index 4 the rest will be 0 :
Arrays.fill(arr, 1, 5, 10);

// access element at index 0
cars[0] = "jag";

*dictionary*
import java.util.Enumeration;
import java.util.Hashtable;

Hashtable<String, Integer> dic1 = new Hashtable<>();
dic1.put("one", 1);
dic1.put("two", 2);
Enumeration<String> e = dic1.keys();
while (e.hasMoreElements()) {
    // Getting the key of a particular entry
    String key = e.nextElement();
    // Print and display the Rank and Name
    System.out.println("key : " + key + " value " + dic1.get(key));
}

*if*
int time = 20;
if (time < 18) {
    System.out.println("Good day.");
    } else {
    System.out.println("Good evening.");
}
max = (n1 > n2) ? n1 : n2; // return exp1 if true

*loops*
for (int i = 1; i <= 10; i++) {}
for (int i : arr) {} // for each item loop
while (condition) {
  // code block to be executed
}
do {
  // code block to be executed
}
while (condition);

*switch*

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

*randomizer*
import java.util.Random;

int rand_int1 = rand.nextInt(6); // includes 0 and 5
double rand_dub1 = rand.nextDouble(); // 0->1 random
array1.randomElement()! // returns a random element from the array

*N-dimensional arrays*
int[][] arr = new int[10][20];
arr[0][0] = 1;
 
Last edited:
Top