layout | title |
---|---|
../../layouts/CheatSheet.astro |
Java Cheatsheet |
Java is a general-purpose programming language that is class-based, object-oriented, and designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.
Data Type | Size |
---|---|
boolean | 1 bit |
char | 2 byte |
int | 4 byte |
short | 2 byte |
long | 8 byte |
float | 4 byte |
double | 8 byte |
system.out.print("Hello World!"); //Will not move to the next line.
system.out.println("Hello World!"); //Will move to the next line.
// There is another type of output method, which is similar to C language.
int a = 23;
system.out.printf("value of a is : %d", a);
import java.util.Scanner
Scanner s = new Scanner(System.in);
// input for an integer.
int a = s.nextInt();
// input for a string.
String str = s.nextLine();
String ss = s.next(); // Takes input till 1st whitespace.
// input for a double.
double d = s.nextDouble();
int i = Integer.parseInt(_str_);
double d = Double.parseDouble(_str_);
String s = String.valueOf(_value_);
int i = (int) _numeric expression_;
double i = (double) _numeric expression_;
long i = (long) _numeric expression_;
Operator Category | Operators |
---|---|
Arithmetic operators | +, -, /, *, % |
Relational operators | <, >, <=, >=,==, != |
Logical operators | &&, || |
Assignment operator | =, +=, −=, ×=, ÷=, %=, &=, ^=, |=, <<=, >>=, >>>= |
Increment and Decrement operator | ++ , - - |
Conditional operators | ?, : |
Bitwise operators | ^, &, | |
Special operators | . (dot operator to access methods of class) |
if ( _expression_ ) {
_statements_
} else if ( _expression_ ) {
_statements_
} else {
_statements_
}
while ( _expression_ ) {
_statements_
}
do {
_statements_
} while ( _expression_ );
for ( int i = 0; i < _max_; ++i) {
_statements_
}
for ( _var_ : _collection_ ) {
_statements_
}
switch ( _expression_ ) {
case _value_:
_statements_
break;
case _value2_:
_statements_
break;
default:
_statements_
}
try {
statements;
} catch (_ExceptionType_ _e1_) {
statements;
} catch (Exception _e2_) {
catch-all statements;
} finally {
statements;
}
A comment is the code that is not executed by the compiler, and the programmer uses it to keep track of the code.
// This is a single line command
/*
This is a multi line comment
we can add multiple lines here
x=5
y=c
*/
Constants are like variables, except that their value never changes during program execution. Constants are declared using static and final keywords
static final float pi = 3.1415;
It gives a tab space
\t
It adds a backslash
\\
It adds a single quotation mark
\'
It adds a question mark
\?
Type Casting is a process of converting one data type into another
It means converting a lower data type into a higher
int x = 49;
double new_x = x; // Outputs 49.0
It means converting a higher data type into a lower
double x = 99.2
int new_x = (int) x; // Outputs 99
// datatype array_name[] = new datatype[Size];
int number[] = new int[10]; // An Integer Array
String characters[] = new String[10]; // A String array
int[] number = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
// datatype array_name[][] = new datatype[row][column];
int number[][] = new int[10][10]; // An Integer Array of dimensions 10 x 10
String characters[][] = new String[10][10]; // A String Array of dimensions 10 x 10
// Traditional for loop
for(int i=0;i<number.length;i++) //length gives the size of the array
{
System.out.println(number[i]);
}
// Advanced for loop
for(int i:number)
{
System.out.println(i);
}
"In Java, a string is basically an object that represents sequence of char values. An array of characters works same as Java string." : Javatpoint
String s = "INPUT";
//Using the new keyword
String s = new String("INPUT");
//From a given character array
char ch[]={'I','N','P','U','T'};
String s=new String(ch);
The above mentioned methods creates a string that are immutable, to make strings mutable, we can use StringBuilder or StringBuffer
"The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences." : GFG
//Create a StringBuffer Object, i.e., empty string buffer
//By default it can take upto a sequence of 16 characters
StringBuffer sb = new StringBuffer();
// Can be initialised with a string
StringBuffer sb2 = new StringBuffer("Input");
1) append(string_data) method : Used to concatenate the entered string and the strings in the buffer
sb.append("Input"); //Now the empty string has been modified to "Input"
2) insert(beginIndex, endIndex, string_data) method : Inserts a given string literal to the specified positions
sb.insert(2," A String");
//Now the string is "In A Stringput"
3) replace(beginIndex, endIndex, string_data) method : Use to replace a sequence of characters from the specified beginIndex and endIndex-1, with another sequence
sb.replace(11,14," Literal");
//Now the string is "In A string Literal"
4) delete(beginIndex, endIndex) method : Use to delete a sequence of characters from the specified beginIndex and endIndex-1
sb.delete(11,19);
//Now the string is "In A String"
sb.reverse();
// Now the string is "gnirtS A nI"
Very similiar to the StringBuffer class but is not Synchronous and neither Thread-Safe. But high in performance, i.e., speedy
//Create a StringBuilder Object, i.e., StringBuilder with no characters
//By default it can take upto a sequence of 16 characters
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuffer("Input");
append(), insert(), replace(), delete(), reverse() are used in the same way as used in the StringBuffer
String str = sb.toString();
System.out.println(str);
The Arrays class of the java.util package contains several static methods that can be used to fill, sort, search, etc in arrays.
Methods | Action Performed |
---|---|
asList() | Returns a fixed-size list backed by the specified Arrays |
binarySearch() | Searches for the specified element in the array |
binarySearch(array, fromIndex, toIndex, key, Comparator) | Searches a range of the specified array for the specified object using the Binary Search Algorithm |
copyOf(originalArray, newLength) | Copies the specified array, truncating or padding with the default value (if necessary) so the copy has the specified length. |
copyOfRange(originalArray, fromIndex, endIndex) | Copies the specified range of the specified array into a new Arrays. |
deepEquals(Object[] a1, Object[] a2) | Returns true if the two specified arrays are deeply equal to one another. |
deepHashCode(Object[] a) | Returns a hash code based on the “deep contents” of the specified Arrays. |
deepToString(Object[] a) | Returns a string representation of the “deep contents” of the specified Arrays. |
fill(originalArray, fillValue) | Assigns this fill value to each index of this arrays. |
hashCode(originalArray) | Returns an integer hashCode of this array instance. |
mismatch(array1, array2) | Finds and returns the index of the first unmatched element between the two specified arrays. |
parallelPrefix(originalArray, fromIndex, endIndex, functionalOperator) | Performs parallelPrefix for the given range of the array with the specified functional operator. |
parallelPrefix(originalArray, operator) | Performs parallelPrefix for complete array with the specified functional operator. |
parallelSetAll(originalArray, functionalGenerator) | Sets all the elements of this array in parallel, using the provided generator function. |
parallelSort(originalArray) | Sorts the specified array using parallel sort. |
setAll(originalArray, functionalGenerator) | Sets all the elements of the specified array using the generator function provided. |
sort(originalArray) | Sorts the complete array in ascending order. |
sort(originalArray, fromIndex, endIndex) | Sorts the specified range of array in ascending order. |
sort(T[] a, int fromIndex, int toIndex, Comparator< super T> c) | Sorts the specified range of the specified array of objects according to the order induced by the specified comparator. |
sort(T[] a, Comparator< super T> c) | Sorts the specified array of objects according to the order induced by the specified comparator. |
spliterator(originalArray) | Returns a Spliterator covering all of the specified Arrays. |
spliterator(originalArray, fromIndex, endIndex) | Returns a Spliterator of the type of the array covering the specified range of the specified arrays. |
stream(originalArray) | Returns a sequential stream with the specified array as its source. |
toString(originalArray) | Returns a string representation of the contents of this array. The string representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters a comma followed by a space. Elements are converted to strings as by String.valueOf() function. |
Command | Description |
---|---|
length | length of string |
charAt(i) | extract _i_th character |
substring(start, end) | substring from start to end-1 |
toUpperCase() | returns copy of s in ALL CAPS |
toLowerCase() | returns copy of s in lowercase |
indexOf(x) | index of first occurence of x |
replace(old, new) | search and replace |
split(regex) | splits string into tokens |
trim() | trims surrounding whitespace |
equals(s2) | true if s equals s2 |
compareTo(s2) | 0 if equal/+ if s > s2/- if s < s2 |
A class in java that is used to break a string into tokens based on given delimeter(s), by default breaks at whitespaces
// To break the string at whitespaces, use the following code
StringTokenizer st = new StringTokenizer(string_value_or_variable);
// To break the string at multiple delimeters, use the following code
StringTokenizer st = new StringTokenizer(string_value_or_variable, delimiter_string);
Command | Description |
---|---|
countTokens() | Returns the number of tokens present |
hasMoreToken() | Checks if there are more tokens in the string |
nextElement() | Return the object of the next element in the stream |
hasMoreElements() | Checks if there are more elements in the string |
nextToken() | Returns the next token from the StringTokenizer. |
StringTokenizer st = new StringTokenizer("Hy there, how are you? Hoping you are doing great!");
while (st.hasMoreTokens())
{
System.out.print(st.nextToken() + " ; ");
}
The semi colon is used to seperate the tokens
// The following scheme can be used to break a punctuated string, into words
StringTokenizer st = new StringTokenizer("Hy there, how are you? Hoping you are doing great!", ":,!? ");
while (st.hasMoreTokens())
{
System.out.print(st.nextToken() + " ; ");
}
The semi colon is used to seperate the tokens
Type | Declaration |
---|---|
ArrayList | List arr = new ArrayList(); |
LinkedList | List arr = new LinkedList(); |
Type | Declaration |
---|---|
HashSet | Set set = new HashSet(); |
TreeSet | Set set = new TreeSet(); |
LinkedHashSet | Set set = new LinkedHashSet(); |
Method | Description | Declaration |
---|---|---|
add | To add an element into the list | arr.add(element) |
remove | To remove an element into the list | arr.remove(element) |
get | To get an element at particular index | arr.get(element) |
set | To set the element at a particular index | arr.set(index, element) |
size | To get size of the list | arr.size() |
contains | To check if the list contains the element | arr.contains(element) |
indexOf | To get the index of the element | arr.indexOf(element) |
Type | Declaration |
---|---|
LinkedHashMap | LinkedHashMap linkedHashMap = new LinkedHashMap(); |
HashMap | HashMap hashMap = new HashMap(); |
TreeMap | TreeMap treeMap = new TreeMap(); |
Type | Declaration |
---|---|
Queue | Queue queue = new LinkedList(); |
PriorityQueue | PriorityQueue priorityQueue = new PriorityQueue(); |
ArrayDeque | ArrayDeque arrayDeque = new ArrayDeque(); |