# Java Quick CheatSheet

By [bitfuture.eth](https://paragraph.com/@bitfuture) · 2022-12-05

---

Java Data Types
===============

Primitive Data Types
--------------------

*   `byte`
    
*   `short`
    
*   `int`
    
*   `long`
    
*   `float`: ~6-7 decimal digits
    
*   `double`: 15 decimal digits
    
*   `char`: surrounded by single quotes
    
*   `boolean`
    

### Notes:

1.  End the value with an "f" for floats and "d" for doubles
    

Non-Primitive Data Types
------------------------

*   `String` (object): surrounded by double quotes
    

### Methods

`length(), toUpperCase(), toLowerCase(), indexOf(), concat()` or `+,` see more [here](https://www.w3schools.com/java/java_ref_string.asp).

### Notes:

1.  Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot.
    
2.  A primitive type has always a value, while non-primitive types can be `null`.
    
3.  If you add a number and a string, the result will be a string concatenation.
    

Java Array
==========

    String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
    for (int i = 0; i < cars.length; i++) {
      System.out.println(cars[i]);
    }
    

or,

    int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
    

Java Class
==========

Math
----

`min(), max(), abs(), random()` see more [here](https://www.w3schools.com/java/java_ref_math.asp).

ArrayList
---------

The `ArrayList` class is a resizable array.

### Methods

`add(), get(), set(), remove(), clear(), size()` Use `Collections` for sorting lists alphabetically or numerically.

    import java.util.ArrayList;
    import java.util.Collections;  // Import the Collections class
    
    public class Main {
      public static void main(String[] args) {
        ArrayList<Integer> myNumbers = new ArrayList<Integer>();
        myNumbers.add(33);
        myNumbers.add(15);
        myNumbers.add(20);
        myNumbers.add(34);
        myNumbers.add(8);
        myNumbers.add(12);
    
        Collections.sort(myNumbers);  // Sort myNumbers
    
        for (int i : myNumbers) {
          System.out.println(i);
        }
      }
    }
    

### Notes

1.  Elements in an ArrayList are actually objects. In the examples above, we created elements (objects) of type "String". Remember that a String in Java is an object (not a primitive type). To use other types, such as `int`, you must specify an equivalent wrapper class: `Integer`. For other primitive types, use: `Boolean` for `boolean`, `Character` for `char`, `Double` for `double`, `Float` for `float`, etc.
    

LinkedList
----------

The `LinkedList` class has all of the same methods as the `ArrayList` class because they both implement the `List` interface.

### Difference

*   The `ArrayList` class has a regular array inside it. When an element is added, it is placed into the array. If the array is not big enough, a new, larger array is created to replace the old one and the old one is removed.
    
*   The `LinkedList` stores its items in "containers." The list has a link to the first container and each container has a link to the next container in the list. To add an element to the list, the element is placed into a new container and that container is linked to one of the other containers in the list.
    
*   Use an ArrayList for storing and accessing data, and LinkedList to manipulate data.
    

### Methods

`addFirst(), addLast(), removeFirst(), removeLast(), getFirst(), getLast()`

HashMap
-------

A `HashMap` however, store items in "key/value" pairs, and you can access them by an index of another type.

### Methods

`put(), get(), remove(), clear(), size(), keySet(), values()`

    // Import the HashMap class
    import java.util.HashMap;
    
    public class Main {
      public static void main(String[] args) {
        // Create a HashMap object called capitalCities
        HashMap<String, String> capitalCities = new HashMap<String, String>();
    
        // Add keys and values (Country, City)
        capitalCities.put("England", "London");
        capitalCities.put("Germany", "Berlin");
        capitalCities.get("England");
        capitalCities.remove("England");
        for (String i : capitalCities.keySet()) {
          System.out.println(i);
        }
      }
    }
    

HashSet
-------

A `HashSet` is a collection of items where every item is unique.

### Methods

`add(), contains(), remove(), clear(), size()`

    // Import the HashSet class
    import java.util.HashSet;
    
    public class Main {
      public static void main(String[] args) {
        HashSet<String> cars = new HashSet<String>();
        cars.add("Volvo");
        cars.add("BMW");
        cars.add("Ford");
        for (String i : cars) {
          System.out.println(i);
        }
      }
    }
    

Iterator
--------

An `Iterator` is an object that can be used to loop through collections, like `ArrayList` and `HashSet`.

### Methods

`hasNext(), next(), remove()`

    import java.util.ArrayList;
    import java.util.Iterator;
    
    public class Main {
      public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        numbers.add(12);
        numbers.add(8);
        numbers.add(2);
        numbers.add(23);
        Iterator<Integer> it = numbers.iterator();
        while(it.hasNext()) {
          Integer i = it.next();
          if(i < 10) {
            it.remove();
          }
        }
        System.out.println(numbers);
      }
    }
    

Enums
-----

An `enum` is a special class, cannot be used to create objects.

    enum Level {
      LOW,
      MEDIUM,
      HIGH
    }
    Level myVar = Level.MEDIUM;
    
    for (Level myVar : Level.values()) {
      System.out.println(myVar);
    }
    

Class Inheritance
-----------------

1.  To inherit from a class, use the `extends` keyword.
    
2.  Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma.
    

    interface FirstInterface {
      public void myMethod(); // interface method
    }
    
    interface SecondInterface {
      public void myOtherMethod(); // interface method
    }
    
    class DemoClass implements FirstInterface, SecondInterface {
      public void myMethod() {
        System.out.println("Some text..");
      }
      public void myOtherMethod() {
        System.out.println("Some other text...");
      }
    }
    

Java If ... Else
================

Syntax:
-------

    if (condition1) {
      // block of code to be executed if condition1 is true
    } else if (condition2) {
      // block of code to be executed if the condition1 is false and condition2 is true
    } else {
      // block of code to be executed if the condition1 is false and condition2 is false
    }
    

Java Switch
===========

Syntax:
-------

    int day = 4;
    switch (day) {
      case 6:
        System.out.println("Today is Saturday");
        break;
      case 7:
        System.out.println("Today is Sunday");
        break;
      default:
        System.out.println("Looking forward to the Weekend");
    }
    // Outputs "Looking forward to the Weekend"
    

Java For Each Loop
==================

Used exclusively to loop through elements in an array
-----------------------------------------------------

Syntax:
-------

    String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
    for (String i : cars) {
      System.out.println(i);
    }
    

Java Lambda Expressions
=======================

A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

Syntax
------

`(parameter1, parameter2) -> { code block }`

    import java.util.ArrayList;
    
    public class Main {
      public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        numbers.add(5);
        numbers.add(9);
        numbers.add(8);
        numbers.add(1);
        numbers.forEach( (n) -> { System.out.println(n); } );
      }
    }
    

Java Regular Expressions
========================

Use `java.util.regex` package to work with regular expressions. The package includes the following classes:

*   `Pattern` Class - Defines a pattern (to be used in a search)
    
*   `Matcher` Class - Used to search for the pattern
    
*   `PatternSyntaxException` Class - Indicates syntax error in a regular expression pattern
    

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Main {
      public static void main(String[] args) {
        Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher("Visit W3Schools!");
        boolean matchFound = matcher.find();
        if(matchFound) {
          System.out.println("Match found");
        } else {
          System.out.println("Match not found");
        }
      }
    }
    

Java Exception
==============

Use `try, catch, finally`:

    public class Main {
      public static void main(String[] args) {
        try {
          int[] myNumbers = {1, 2, 3};
          System.out.println(myNumbers[10]);
        } catch (Exception e) {
          System.out.println("Something went wrong.");
        } finally {
          System.out.println("The 'try catch' is finished.");
        }
      }
    }
    

Java Packages
=============

A package in Java is used to group related classes.

Import a class
--------------

`import java.util.Scanner;`

Import a whole package
----------------------

`import java.util.*;`

---

*Originally published on [bitfuture.eth](https://paragraph.com/@bitfuture/java-quick-cheatsheet)*
