# Java Quick CheatSheet **Published by:** [bitfuture.eth](https://paragraph.com/@bitfuture/) **Published on:** 2022-12-05 **URL:** https://paragraph.com/@bitfuture/java-quick-cheatsheet ## Content Java Data TypesPrimitive Data Typesbyteshortintlongfloat: ~6-7 decimal digitsdouble: 15 decimal digitschar: surrounded by single quotesbooleanNotes:End the value with an "f" for floats and "d" for doublesNon-Primitive Data TypesString (object): surrounded by double quotesMethodslength(), toUpperCase(), toLowerCase(), indexOf(), concat() or +, see more here.Notes:Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot.A primitive type has always a value, while non-primitive types can be null.If you add a number and a string, the result will be a string concatenation.Java ArrayString[] 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 ClassMathmin(), max(), abs(), random() see more here.ArrayListThe ArrayList class is a resizable array.Methodsadd(), 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); } } } NotesElements 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.LinkedListThe LinkedList class has all of the same methods as the ArrayList class because they both implement the List interface.DifferenceThe 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.MethodsaddFirst(), addLast(), removeFirst(), removeLast(), getFirst(), getLast()HashMapA HashMap however, store items in "key/value" pairs, and you can access them by an index of another type.Methodsput(), 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); } } } HashSetA HashSet is a collection of items where every item is unique.Methodsadd(), 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); } } } IteratorAn Iterator is an object that can be used to loop through collections, like ArrayList and HashSet.MethodshasNext(), 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); } } EnumsAn 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 InheritanceTo inherit from a class, use the extends keyword.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 ... ElseSyntax: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 SwitchSyntax: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 LoopUsed exclusively to loop through elements in an arraySyntax:String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (String i : cars) { System.out.println(i); } Java Lambda ExpressionsA 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 ExpressionsUse 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 patternPatternSyntaxException Class - Indicates syntax error in a regular expression patternimport 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 ExceptionUse 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 PackagesA package in Java is used to group related classes.Import a classimport java.util.Scanner;Import a whole packageimport java.util.*; ## Publication Information - [bitfuture.eth](https://paragraph.com/@bitfuture/): Publication homepage - [All Posts](https://paragraph.com/@bitfuture/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@bitfuture): Subscribe to updates