Java Cheat Sheet

Sulav Jung Hamal

Data Types


TypeSizeRangeSyntax
boolean1true or falseboolean variableName = true/false;
byte8-128 to 127byte variableName;
short16-32,768 to 32,767short variableName;
int32-2,147,483,648 to 2,147,483,647int variableName;
long64-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807long variableName;
float32Approximately ±3.40282347E+38F (6-7 significant decimal digits)float variableName;
double64Approximately ±1.79769313486231570E+308 (15 significant decimal digits)double variableName;
char160 to 65,535 (Unicode characters)char variableName;

Operator Types


TypeExamples
Arithmetic+, -, *, /, %
Relational==, !=, <, >, <=, >=
Logical&&, ||, !
Bitwise&, |, ^, ~, <<, >>, >>>
Assignment=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
Conditional?, :

Input and Output

1. Output:

System.out.println("Te");
System.out.println(var);

2. Input:

import java.util.Scanner; 
Scanner inputName = new Scanner(System.in);
Type variableName = inputName.next<Type>();

File Handling

1. Creating a File Object:

File fileObject = new File("file/path");

2. Checking if File exists:

if (fileObject.exists()) {
    // file exists
} else {
    // file does not exist
}

3. Creating a new File:

fileObject.createNewFile();

4. Writing to a file:

FileWriter writer = new FileWriter(fileObject);
writer.write("Text to be written to file");
writer.close();

5. Reading from a file:

Scanner reader = new Scanner(fileObject);

while (reader.hasNextLine()) {
    // Do something with data
}

reader.close();

Interfaces and Abstract Classes

1. Defining Interfaces:

public interface InterfaceName {
    // method signatures
}

2. Implementing Interfaces:

public class ClassName implements InterfaceName {
    // method implementations
}

3. Abstract Classes:

public abstract class ClassName {
    // instance variables
    // constructors
    
    // abstract method(s)
    public abstract returnType methodName(parameter_list);
    
    // concrete method(s)
    public void methodName(parameter_list) {
        // code
    }
}

4. Abstract Methods:

// abstract method
public abstract returnType methodName(parameter_list);

Control Structures

1. if-else statement:

if (condition) {
    // code to execute if condition is true
} else {
    // code to execute if condition is false
}

2. switch statement:

switch (expression) {
    case value1:
        // expression
        break;
    case value2:
        // expression
        break;
    default:
        // expression
        break;
}

3. for loop:

for (initialization; condition; increment/decrement) {
    // code
}

4. while loop:

while (condition) {
    // code
}

5. do-while loop:

do {
    // code
} while (condition);

6. for-each loop:

for (data_type variable_name : array/collection) {
    // code
}

Note: Control structures are constructs used in computer programming to control the flow of execution of a program based on certain conditions or criteria. They are used to dictate the order in which statements or instructions are executed, as well as to determine the number of times a particular set of statements or instructions should be executed.

Exception Handling

1. Try-Catch Blocks:

try {
    // code that might throw an exception
} catch (ExceptionType e) {
    // code to handle the exception
} finally {
    // optional code to execute after try/catch block
}

2. Throwing and Catching Exceptions:

// throwing an exception
throw new ExceptionType("Exception message");

// catching an exception
try {
    // code that might throw an exception
} catch (ExceptionType e) {
    // code to handle the exception
}

3. Checked and Unchecked Exception:

// checked exception
public void methodName() throws ExceptionType {
    // code that might throw an exception
}

// unchecked exception
public void methodName() {
    // code that might throw an exception
    throw new ExceptionType("Exception message");
}

Note: Exception handling is a mechanism in Java for dealing with runtime errors and exceptional situations. The "try-catch" block is used to catch and handle exceptions. Exceptions can also be thrown manually using the "throw" keyword. Checked exceptions must be declared or caught, while unchecked exceptions do not require handling.

Classes and Objects

1. Defining Classes:

public class ClassName {
    // instance variables
    // constructors
    // methods
}

2. Creating Objects:

ClassName objectName = new ClassName();

3. Instance Variables and Methods:

public class ClassName {
    // instance variables
    data_type variable_name;
 
    // methods
    return_type method_name(parameter_list) {
        // code
    }
}

4. Constructors:

public class ClassName {
    // instance variables
    data_type variable_name;
    
    // constructors
    ClassName(data_type parameter_list) {
        variable_name = parameter_list;
    }
    
    // methods
    return_type method_name(parameter_list) {
        // code
    }
}

5. Encapsulation:

public class ClassName {
    // private instance variables
    private data_type variable_name;
    
    // public getter and setter methods
    public data_type getVariableName() {
        return variable_name;
    }
    public void setVariableName(data_type parameter_list) {
        this.variable_name = parameter_list;
    }
    // methods
    return_type method_name(parameter_list) {
        // code
    }
}

6. Inheritance:

public class ParentClass {
    // instance variables
    // constructors
    // methods
}

public class ChildClass extends ParentClass {
    // additional instance variables
    // additional constructors
    // additional methods
}

7. Polymorphism:

public class ParentClass {
    // methods
    public void methodName() {
        // code
    }
}

public class ChildClass extends ParentClass {
    // override parent method
    @Override
    public void methodName() {
        // code
    }
    
    // overload parent method
    public void methodName(parameter_list) {
        // code
    }
}

Note that these are just the basic syntax for each topic, and there are many more features and concepts to explore within each one. So, feel free to dive deep into each topic for a better understanding.

Generics

1. Generic Classes:

public class ClassName<T> {
    // T can be used as a type parameter in the class
}

2. Generic Methods:

public <T> void methodName(T parameter) {
    // T can be used as a type parameter in the method
}

3. Bounded Type Parameters:

public <T extends ClassName> void methodName(T parameter) {
    // T must extend ClassName
}

4. Wildcards:

// Upper bounded wildcard
public void methodName(List<? extends ClassName> list) {
    // list can be a List of any subclass of ClassName
}

// Lower bounded wildcard
public void methodName(List<? super ClassName> list) {
    // list can be a List of ClassName or any superclass of ClassName
}

Generics are a way to make your code more flexible and reusable by allowing classes and methods to work with different types. Type parameters are denoted by angle brackets and can be used to specify the type of a class, method, or variable at compile time. Bounded type parameters specify that the type must be a subclass or superclass of a given class. Wildcards are used to denote a range of types that a generic method or class can accept as input.

Collections

1. ArrayList:

ArrayList<Type> listName = new ArrayList<Type>();

2. LinkedList:

LinkedList<Type> listName = new LinkedList<Type>();

3. HashMap:

HashMap<KeyType, ValueType> mapName = new HashMap<KeyType, ValueType>();

4. HashSet:

HashSet<Type> setName = new HashSet<Type>();

5. TreeSet:

TreeSet<Type> setName = new TreeSet<Type>();

6. Sorting Collections:

// Sorting an ArrayList
Collections.sort(listName);

// Sorting a LinkedList
Collections.sort(listName);

// For TreeSet - The elements must implement the Comparable interface

7. Iterating Over Collections:

// Using a for-each loop
for (Type element : collectionName) {
    // code to execute for each element
}

// Using an iterator
Iterator<Type> iteratorName = collectionName.iterator();
while (iteratorName.hasNext()) {
    Type element = iteratorName.next();
    // code to execute for each element
}

Collections in Java provide a way to store and manipulate groups of objects. Here are some commonly used collection classes and techniques for working with them. An ArrayList is a dynamic array-based implementation, while a LinkedList is a doubly-linked list. HashMap is a key-value mapping, HashSet stores unique elements in no particular order, and TreeSet stores elements in sorted order. Collections can be sorted using the sort() method from the Collections class. Iteration over collections can be done using for-each loops or iterators.

Methods within Collection Types

ArrayList:

ArrayList<E> list = new ArrayList<E>();

list.add(element); // adds an element to the end of the ArrayList
list.get(index); // returns the element at the specified index
list.remove(index); // removes the element at the specified index
list.size(); // returns the number of elements in the ArrayList
list.clear(); // removes all elements from the ArrayList
list.isEmpty(); // returns true if the ArrayList contains no elements

Vector:

Vector<E> vec = new Vector<E>();

vec.addElement(obj); // Adds an element to the end of the Vector
vec.add(index, obj); // Inserts an element at the specified index
vec.removeElement(obj); // Removes the first occurrence of the specified element

vec.remove(index); // Removes the element at the specified index
vec.clear(); // Removes all elements from the Vector
vec.size(); // Returns the number of elements in the Vector
vec.elementAt(index); // Returns the element at the specified index
vec.setElementAt(obj, index); // Sets the element at the specified index to the specified object

vec.isEmpty(); // Returns true if the Vector contains no elements
vec.contains(obj); // Returns true if the Vector contains the specified element

vec.indexOf(obj); // Returns the index of the first occurrence of the specified element

vec.lastIndexOf(obj); // Returns the index of the last occurrence of the specified

vec.toArray(); // Returns an array containing all elements in the Vector

LinkedList:

LinkedList<E> list = new LinkedList<E>();

list.add(element); // adds an element to the end of the LinkedList
list.addFirst(element); // adds an element to the beginning of the LinkedList
list.addLast(element); // adds an element to the end of the LinkedList
list.get(index); // returns the element at the specified index
list.remove(index); // removes the element at the specified index
list.removeFirst(); // removes the first element from the LinkedList
list.removeLast(); // removes the last element from the LinkedList
list.size(); // returns the number of elements in the LinkedList
list.clear(); // removes all elements from the LinkedList
list.isEmpty(); // returns true if the LinkedList contains no elements, false otherwise

HashMap:

HashMap<K, V> map = new HashMap<K, V>();

map.put(key, value); // associates the specified value with the specified key in the HashMap

map.get(key); // returns the value associated with the specified key in the HashMap

map.remove(key); // removes the mapping for the specified key from the HashMap
map.containsKey(key); // returns true if the HashMap contains a mapping for the specified key, false otherwise

map.size(); // returns the number of key-value mappings in the HashMap
map.clear(); // removes all key-value mappings from the HashMap
map.isEmpty(); // returns true if the HashMap contains no key-value mappings, false otherwise

HashSet:

HashSet<E> set = new HashSet<E>();

set.add(element); // adds the specified element to the HashSet
set.remove(element); // removes the specified element from the HashSet
set.contains(element); // returns true if the HashSet contains the specified element, false otherwise

set.size(); // returns the number of elements in the HashSet
set.clear(); // removes all elements from the HashSet
set.isEmpty(); // returns true if the HashSet contains no elements, false otherwise

TreeSet:

TreeSet<E> set = new TreeSet<E>();

set.add(element); // adds the specified element to the TreeSet
set.remove(element); // removes the specified element from the TreeSet
set.contains(element); // returns true if the TreeSet contains the specified element, false otherwise

set.size(); // returns the number of elements in the TreeSet
set.clear(); // removes all elements from the TreeSet
set.isEmpty(); // returns true if the TreeSet contains no elements, false otherwise

set.first(); // returns the first (lowest) element currently in the TreeSet
set.last(); // returns the last (highest) element currently in the TreeSet

These are some commonly used methods for different collection types in Java. ArrayList, Vector, LinkedList, HashMap, HashSet, and TreeSet are popular collection classes in Java. They provide methods to add, remove, retrieve, and manipulate elements in the collections. The methods listed above are just a subset of the available methods. Refer to the Java API documentation for more details on each collection class and its methods.

Streams

Using Streams to process collections:

collection.stream().forEach(element -> /* action */);

Intermediate operations:

stream.filter(predicate)   // filters elements based on predicate
      .map(function)       // applies function to each element
      .sorted()            // sorts elements in natural order
      .distinct()          // removes duplicates
      .limit(n)            // limits number of elements to n
      .skip(n)             // skips first n elements

Terminal Operations:

// iterate over each element in stream
stream.forEach(consumer);

// perform a reduction operation on stream elements
stream.reduce(identity, accumulator);

// collect stream elements into a collection
stream.collect(collector);

// find the minimum element in the stream
stream.min(comparator);

// find the maximum element in the stream
stream.max(comparator);

// count the number of elements in the stream
stream.count();

// check if any element matches a given predicate
stream.anyMatch(predicate);

// check if all elements match a given predicate
stream.allMatch(predicate);

// check if no elements match a given predicate
stream.noneMatch(predicate);

Stream pipelines:

collection.stream()
    .filter(element -> /* condition */)
    .map(element -> /* transformation */)
    .forEach(element -> /* action */);

Parallel streams:

collection.parallelStream().forEach(element -> /* action */);

Streams provide a powerful and concise way to process collections in Java. They allow you to perform operations on elements of a collection such as filtering, mapping, sorting, and more. Intermediate operations transform the stream, while terminal operations produce a result or side-effect. Stream pipelines consist of a sequence of operations applied to a collection. Parallel streams enable concurrent processing of elements, potentially improving performance. Utilize streams to write clean and efficient code when working with collections in Java.

This cheat sheet is the intellectual property of Sulav Jung Hamal. All rights reserved. The reproduction, distribution, and sale of this cheat sheet, in whole or in part, is strictly prohibited without the prior written consent of Sulav Jung Hamal. This cheat sheet is provided as-is and makes no representations or warranties of any kind concerning the contents hereof.

This cheat sheet is intended for educational and quick reference purposes only. In order to fully understand the concepts of the Java language, it is recommended to consult books or other comprehensive resources.

Keep this cheat sheet handy and use it to quickly reference concepts. As you go through the content, create a mind map to connect the actual concepts to where they are in the cheat sheet. This will allow for quick recall.

  • It is important to note that programming is a constantly evolving field, and Java is no exception. This cheatsheet may not be up-to-date with the latest Java versions, and it is recommended to refer to the official Java documentation for the most accurate and up-to-date information.
  • If you find anything wrong in this file, please contact me.
  • Hey there! My name is Sulav Jung Hamal 💻, and I'm a computer science student at SFSU 🎓. You can find more information about me in my website 🌐: sulavhamal.com

    Daily Vibes