Sulav Jung Hamal
Type | Size | Range | Syntax |
---|---|---|---|
boolean | 1 | true or false | boolean variableName = true/false; |
byte | 8 | -128 to 127 | byte variableName; |
short | 16 | -32,768 to 32,767 | short variableName; |
int | 32 | -2,147,483,648 to 2,147,483,647 | int variableName; |
long | 64 | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | long variableName; |
float | 32 | Approximately ±3.40282347E+38F (6-7 significant decimal digits) | float variableName; |
double | 64 | Approximately ±1.79769313486231570E+308 (15 significant decimal digits) | double variableName; |
char | 16 | 0 to 65,535 (Unicode characters) | char variableName; |
Type | Examples |
---|---|
Arithmetic | + , - , * , / , % |
Relational | == , != , < , > , <= , >= |
Logical | && , || , ! |
Bitwise | & , | , ^ , ~ , << , >> , >>> |
Assignment | = , += , -= , *= , /= , %= , &= , |= , ^= , <<= , >>= |
Conditional | ? , : |
System.out.println("Te");
System.out.println(var);
import java.util.Scanner;
Scanner inputName = new Scanner(System.in);
Type variableName = inputName.next<Type>();
File fileObject = new File("file/path");
if (fileObject.exists()) {
// file exists
} else {
// file does not exist
}
fileObject.createNewFile();
FileWriter writer = new FileWriter(fileObject);
writer.write("Text to be written to file");
writer.close();
Scanner reader = new Scanner(fileObject);
while (reader.hasNextLine()) {
// Do something with data
}
reader.close();
public interface InterfaceName {
// method signatures
}
public class ClassName implements InterfaceName {
// method implementations
}
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
}
}
// abstract method
public abstract returnType methodName(parameter_list);
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
switch (expression) {
case value1:
// expression
break;
case value2:
// expression
break;
default:
// expression
break;
}
for (initialization; condition; increment/decrement) {
// code
}
while (condition) {
// code
}
do {
// code
} while (condition);
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.
try {
// code that might throw an exception
} catch (ExceptionType e) {
// code to handle the exception
} finally {
// optional code to execute after try/catch block
}
// 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
}
// 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.
public class ClassName {
// instance variables
// constructors
// methods
}
ClassName objectName = new ClassName();
public class ClassName {
// instance variables
data_type variable_name;
// methods
return_type method_name(parameter_list) {
// code
}
}
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
}
}
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
}
}
public class ParentClass {
// instance variables
// constructors
// methods
}
public class ChildClass extends ParentClass {
// additional instance variables
// additional constructors
// additional methods
}
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.
public class ClassName<T> {
// T can be used as a type parameter in the class
}
public <T> void methodName(T parameter) {
// T can be used as a type parameter in the method
}
public <T extends ClassName> void methodName(T parameter) {
// T must extend ClassName
}
// 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.
ArrayList<Type> listName = new ArrayList<Type>();
LinkedList<Type> listName = new LinkedList<Type>();
HashMap<KeyType, ValueType> mapName = new HashMap<KeyType, ValueType>();
HashSet<Type> setName = new HashSet<Type>();
TreeSet<Type> setName = new TreeSet<Type>();
// Sorting an ArrayList
Collections.sort(listName);
// Sorting a LinkedList
Collections.sort(listName);
// For TreeSet - The elements must implement the Comparable interface
// 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.
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<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<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<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<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<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.
collection.stream().forEach(element -> /* action */);
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
// 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);
collection.stream()
.filter(element -> /* condition */)
.map(element -> /* transformation */)
.forEach(element -> /* action */);
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.
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