Show Menu
Cheatography

Java cheat sheet by yunshu

// import java.l­ang.Nu­mber;

Number Methods

Integer a = 20;
a.byte­Val­ue(); a.shor­tVa­lue(); a.intV­alue(); a.long­Val­ue(); a.floa­tVa­lue(); a.doub­leV­alue()
The method converts the value of the Number Object that invokes the method to the primitive data type that is returned from the method.
a.comp­are­Top­ublic int compareTo( Number­Sub­Class same_type )
Compares this Number object to the argument.
a. equals­(Object o)
Determines whether this number object is equal to the argument.
Number.va­lue­Of(int i/String s/ String s, int radix)
The valueOf method returns the Integer holding the value of the argument passed.
a. toString()
string repres­ent­ation
Math.abs()
absolute value
Math.c­eil()
The method ceil gives the smallest integer that is greater than or equal to the argument.
Math.r­int()
Returns the integer that is closest in value to the argument. Returned as a double.
Math.r­ound()
Returns the closest long or int, as indicated by the method's return type to the argument.
Math.m­in(a,b)
Returns the smaller of the two arguments.
Math.m­ax(a,b)
Returns the larger of the two arguments.
Math.exp()
Returns the base of the natural logari­thms, e, to the power of the argument.
Math.log()
Returns the natural logarithm of the argument.
Math.p­ow(a,b)
Returns the value of the first argument raised to the power of the second argument.
Math.s­qrt()
Returns the square root of the argument.
Math.sin()
Returns the sine of the specified double value.
Math.c­os(); Math.t­an(); Math.a­sin(); Math.a­cos(); Math.a­tan(); Math.a­tan2();
Math.t­oDe­gree()
Converts the argument to degrees.
Math. toRadi­ans()
Converts the argument to radians.
Math.r­andom()
Returns a random number.

String­Builder

String­Builder sb = new String­Bui­lder(capacity or string);
creat a String­Builder
sb.app­end­(obj);
append string repres­ent­ation of obj to this SB
sb.cap­aci­ty();
return the current capacity
sb.cha­rAt­(in­dex);
Returns the char value in this sequence at the specified index.
sb.del­ete­(st­art­,en­d_e­xcl­usive);
Removes the characters in a substring of this sequence.
sb.del­ete­Cha­rAt­(in­dex);
Removes the char at the specified position in this sequence.
getCha­rs(int srcBegin, int srcEnd, char[] dst, int dstBegin);
Characters are copied from this sequence into the destin­ation character array dst.
sb.ind­exO­f(s­tring,from);
Returns the index within this string of the first occurrence of the specified substring.
sb.ins­ert­(in­dex­,obj)
Inserts the string repres­ent­ation of the boolean argument into this sequence.
sb.rep­lac­e(int start, int end, String str);
Replaces the characters in a substring of this sequence with characters in the specified String.
sb.rev­erse()
Causes this character sequence to be replaced by the reverse of the sequence.
sb.set­Cha­rAt(int index, char ch);
The character at the specified index is set to ch.
sb.sub­Seq­uen­ce(int start, int end)
Returns a new character sequence that is a subseq­uence of this sequence.
sb.sub­str­ing(int start,end)
Returns a new String that contains a subseq­uence of characters currently contained in this character sequence.
sb.toS­tring()
Returns a string repres­enting the data in this sequence.

Thread

Creating a thread in Java is done like this:
Thread thread = new Thread();

To start the thread
thread.st­art();

To join the thread
thread.join()

Thread subclass
public class MyThread extends Thread {
public void run(){­Sys­tem.ou­t.p­rin­tln­("My­Thread runnin­g"); }
}
MyThread myThread = new MyThre­ad();
myTrea­d.s­tart();
OR:
Thread thread = new Thread(){
public void run(){
System.ou­t.p­rin­tln­("Thread Runnin­g");}
}`

thread.st­art();
Runnable Interface Implem­ent­ation
public interface Runnable() {public void run();}

To implement a Runnable
1. Java Class Implements Runnable
public class MyRunnable implements Runnable {
public void run(){
System.ou­t.p­rin­tln­("My­Run­nable runnin­g"); }
}
2. Anonymous Implem­ent­ation of Runnable
Runnable myRunnable =
new Runnab­le(){
public void run(){
System.ou­t.p­rin­tln­("Ru­nnable runnin­g");}
}`
3. Java Lambda Implem­ent­ation of Runnable
Runnable runnable = () -> { System.ou­t.p­rin­tln­("Lambda Runnable runnin­g"); };

Starting a Thread With a Runnable
Runnable runnable = new MyRunn­able(); // or an anonymous class, or lambda...
Thread thread = new Thread­(ru­nna­ble);
thread.st­art();
Synchr­oni­zation
1. Synchr­onized Instance Methods
public synchr­onized void synchr­oni­sed­Cal­cul­ate()
{setSu­m(g­etSum() + 1);}


2. Synchr­onized Static Methods
public static synchr­onized void syncSt­ati­cCa­lcu­late()
{staticSum = staticSum + 1;}
**

3. Synchr­onized Blocks Within Methods
public void perfor­mSy­nch­ron­ise­dTask() {
//unsy­nch­ronized part
// ...
synchr­onized (this/obj) {
setCou­nt(­get­Cou­nt(­)+1);}}

import java.time

import java.t­ime.Lo­cal­Date;
yyyy-MM-dd
LocalDate myObj = LocalD­ate.now(); System.ou­t.p­rin­tln­(my­Obj);
"­202­0-1­2-2­8"
import java.t­ime.Lo­cal­Time;
HH-mm-­ss-ns
LocalTime myObj = LocalT­ime.now(); System.ou­t.p­rin­tln­(my­Obj);
"­00:­01:­02.2­90­985­"
import java.t­ime.Lo­cal­Dat­eTime;
yyyy-M­M-d­d-H­H-m­m-ss-ns
LocalD­ateTime myDateObj = LocalD­ate­Tim­e.n­ow(); System.ou­t.p­rin­tln­(my­Dat­eObj);
"­202­0-1­2-2­8T0­0:0­1:0­2.3­111­39"

import java.u­til.Ha­shMap;

public void clear()
This method removes all of the mappings from this map.
public boolean contai­nsK­ey(­Object key)
This method returns true if this map contains a mapping for the specified key.
public boolean contai­nsV­alu­e(O­bject value)
This method returns true if this map maps one or more keys to the specified value.
public Set<Ma­p.E­ntr­y<K­,V>> entrySet()
This method returns a Set view of the mappings contained in this map.
public V get(Object key)
This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
public boolean isEmpty()
This method returns true if this map contains no key-value mapping.
public Set<K> keySet()
This method returns a Set view of the keys contained in this map.
public V put(K key, V value)
This method associates the specified value with the specified key in this map.
public void putAll­(Ma­p<? extends K,? extends V> m)
This method copies all of the mappings from the specified map to this map.
public V remove­(Object key)
This method removes the mapping for the specified key from this map if present.
public int size()
This method returns the number of key-value mappings in this map.
public Collec­tio­n<V> values()
This method returns a Collection view of the values contained in this map.

import java.u­til.Pr­ior­ity­Queue;

public boolean add(E e)
This method inserts the specified element into this priority queue.
public boolean offer(E e)
This method inserts the specified element into this priority queue.
public void clear()
This method removes all of the elements from this priority queue.
public boolean contai­ns(­Object o)
This method returns true if this queue contains the specified element.
public Iterat­or<­E> iterator()
This method returns an iterator over the elements in this queue.
public E peek()
This method retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
This method retrieves and removes the head of this queue, or returns null if this queue is empty.
This method retrieves and removes the head of this queue, or returns null if this queue is empty.
public boolean remove­(Object o)
This method removes a single instance of the specified element from this queue, if it is present.
public int size()
This method returns the number of elements in this collec­tion.
public Object[] toArray()
This method returns an array containing all of the elements in this queue.
public <T> T[] toArra­y(T[] a)
This method returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array.
The java.u­til.Pr­ior­ity­Queue class is an unbounded priority queue based on a priority heap.F­oll­owing are the important points about Priori­tyQueue

- The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue constr­uction time, depending on which constr­uctor is used.

- A priority queue does not permit null elements.

- A priority queue relying on natural ordering also does not permit insertion of non-co­mpa­rable objects.

import java.u­til.St­ream;

 

Character class

Character c = '1';
Charac­ter.is­Let­ter()
The method determines whether the specified char value is a letter.
Charac­ter.is­Digit()
The method determines whether the specified char value is a digit.
Charac­ter.is­Let­ter­OrD­igi­t(char ch)
Determines if the specified character is a letter or digit.
Charac­ter.di­git­(char ch, int radix)
Returns the numeric value of the character ch in the specified radix.
Charac­ter.fo­rDi­git(int digit, int radix)
Determines the character repres­ent­ation for a specific digit in the specified radix.
Charac­ter.is­Whi­tes­pace()
Determines whether the specified char value is white space.
Character. isUppe­rCase()
Determines whether the specified char value is uppercase.
Character. toUppe­rCase()
Determines whether the specified char value is lowercase.
Charac­ter.to­Low­erC­ase()
Returns the lowercase form of the specified char value.
Charac­ter.to­Str­ing()
Returns a String object repres­enting the specified character value that is, a one-ch­aracter string.
Character. codePo­int­At(­seq­,index)
return the ASCII value of char at index in seq
c.char­Val­ue();
return the ASCII value of this char.
Charac­ter.ge­tNu­mer­icV­alu­e(char ch)
Returns the int value that the specified Unicode character repres­ents.
Charac­ter.is­Spa­ceC­har­(char ch)
Determines if the specified character is a Unicode space character.
Charac­ter.is­Whi­tes­pac­e(char ch)
Determines if the specified character is white space according to Java.

String class

String s = "­123­"
s.charAt()
This method returns the character located at the String's specified index. The string indexes start from zero.
s.comp­areTo()
This method compares two strings lexico­gra­phi­cally.
s.comp­are­ToI­gno­reC­ase()
Compares two strings lexico­gra­phi­cally, ignoring case differ­ences.
s.concat()
This method appends one String to the end of another. The method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method.
s.cont­ent­Equ­al(­Str­ing­Builder sb)
This method returns true if and only if this String represents the same sequence of characters as specified in String­Buffer.
s.ends­With()
This method tests if this string ends with the specified suffix.
s.equals()
This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
s.equa­lsI­gno­reC­ase()
This method compares this String to another String, ignoring case consid­era­tions. Two strings are considered equal ignoring case, if they are of the same length, and corres­ponding characters in the two strings are equal ignoring case.
s.getC­har­s(int srcBegin, int srcEnd, char[] dst, int dstBegin)
This method copies characters from this string into the destin­ation character array.
s.inde­xOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
s.inde­xOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
s.last­Ind­exO­f(int ch)
Returns the index within this string of the last occurrence of the specified character.
s.last­Ind­exO­f(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
s.length()
Returns the length of this string.
s.matc­hes­(regex)
Tells whether or not this string matches the given regular expres­sion.
s.regi­onM­atc­hes­(bo­olean ignore­Cas­e,int this_o­ffs­et,­String other,int that_o­ffs­et,int len))
This method has two variants which can be used to test if two string regions are equal.
s.repl­ace­(ol­d,new)
Returns a new string resulting from replacing all occurr­ences of oldChar in this string with newChar.
s.spli­t(del,limit)
split the string
s.subS­equ­enc­e(b­eg,end)
Returns a new character sequence that is a subseq­uence of this sequence.
s.subs­tri­ng(beg,end)
Returns a new string that is a substring of this string.
s.toCh­arA­rray()
Converts this string to a new character array.
s.toLo­wer­Case()
Converts all of the characters in this String to lower case using the rules of the default locale.
s.toUp­perCase
Converts all of the characters in this String to upper case using the rules of the default locale.
s.trim()
Returns a copy of the string, with leading and trailing whitespace omitted.

import java.u­til.Ar­ray­List;

ArrayL­ist­<St­rin­g> cars = new ArrayL­ist­<St­rin­g>();
create an Arraylist
cars.g­et(­index);
get item at index
cars.s­et(0, "­Ope­l");
set item at index
cars.r­emo­ve(0);
remove item at index
cars.c­lear();
remove all items
cars.s­ize();
get size of arraylist
import java.u­til.Co­lle­ctions;
Import the Collec­tions class
Collec­tio­ns.s­or­t(m­yNu­mbers);
Sort myNumbers

import java.u­til.Ar­rays;

public static <T> List<T> asList­(T... a)
This method returns a fixed-size list backed by the specified array.
public static int binary­Sea­rch­(arr, fromInd,toInd,target,)
This method searches the specified array of bytes for the specified value using the binary search algorithm.
public static <T> T[] copyOf(T[] original, int newLength)
This method copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length.
public static T[] copyOf­Ran­ge(­ori­gin­alArr, int from, int to)
This method copies the specified range of the specified array into a new array.
public static boolean deepEq­ual­s(O­bject[] a1, Object[] a2)
This method returns true if the two specified arrays are deeply equal to one another.
public static boolean equals­(Ob­ject[] a, Object[] a2)
This method returns true if the two specified arrays of Objects are equal to one another.
public static void fill(O­bject[] a, Object val)
This method assigns the specified Object reference to each element of the specified array of Objects.
public static void fill(o­bject[] a, int fromIndex, int toIndex, object val)
This method assigns the specified Object reference to each element of the specified range of the specified array of Objects.
public static void sort(O­bject[] a)
This method sorts the specified array of objects into ascending order, according to the natural ordering of its elements.
public static void sort(O­bject[] a, int fromIndex, int toIndex)
This method sorts the specified range of the specified array of objects into ascending order, according to the natural ordering of its elements.
public static String toStri­ng(­Obj­ect[] a)
This method returns a string repres­ent­ation of the contents of the specified array of ints.

import java.u­til.Co­lle­ctions;

public static <T> boolean addAll­(Co­lle­cti­on<? super T> c, T.. a)
This method adds all of the specified elements to the specified collec­tion.
public static <T> int binary­Sea­rch­(Li­st<? extends Compar­abl­e<? super T>> list, T key)
This method searches the specified list for the specified object using the binary search algorithm.
public static <T> void copy(L­ist­<? super T> dest,L­ist­<? extends T> src)
This method copies all of the elements from one list into another.
public static boolean disjoi­nt(­Col­lec­tio­n<?> c1,Col­lec­tio­n<?> c2)
This method returns true if the two specified collec­tions have no elements in common.
public static <T> void fill(L­ist­<? super T> list, T obj)
This method returns an enumer­ation over the specified collec­tion.
public static <T> void fill(L­ist­<? super T> list, T obj)
This method replaces all of the elements of the specified list with the specified element.
public static int indexO­fSu­bLi­st(­Lis­t<?> source, List<?> target)
This method returns the starting position of the first occurrence of the specified target list within the specified source list, or -1 if there is no such occurr­ence.
public static int lastIn­dex­OfS­ubL­ist­(Li­st<­?> source, List<?> target)
This method returns the starting position of the last occurrence of the specified target list within the specified source list, or -1 if there is no such occurr­ence.
public static <T extends Object & Compar­abl­e<? super T>> T max(Co­lle­cti­on<? extends T> coll)
This method returns the maximum element of the given collec­tion, according to the natural ordering of its elements.
public static <T extends Object & Compar­abl­e<? super T>> T min(Co­lle­cti­on<? extends T> coll)
This method Returns the minimum element of the given collec­tion, according to the natural ordering of its elements.
public static <T> boolean replac­eAl­l(L­ist­<T> list,T oldVal,T newVal)
This method replaces all occurr­ences of one specified value in a list with another.
public static void shuffl­e(L­ist­<?> list)
This method randomly permutes the specified list using a default source of random­ness.
public static void rotate­(Li­st<­?> list,int distance)
This method rotates the elements in the specified list by the specified distance.
public static <T extends Compar­abl­e<? super T>> void sort(L­ist­<T> list)
This method sorts the specified list into ascending order, according to the natural ordering of its elements.
public static void swap(L­ist­<?> list,int i,int j)
This method swaps the elements at the specified positions in the specified list.

import java.u­til.Ha­shSet;

public boolean add(E e)
This method adds the specified element to this set if it is not already present.
public void clear()
This method removes all of the elements from this set.
public boolean contai­ns(­Object o)
This method returns true if this set contains the specified element.
public boolean isEmpty()
This method returns true if this set contains no elements.
public Iterat­or<­E> iterator()
This method returns an iterator over the elements in this set.
public boolean remove­(Object o)
This method removes the specified element from this set if it is present.
public int size()
This method returns returns the number of elements in this set(its cardin­ality).

import java.u­til.Stack

public boolean empty()
This method tests if this stack is empty.
public Object peek()
This method looks at the object at the top of this stack without removing it from the stack.
public Object pop()
This method removes the object at the top of this stack and returns that object as the value of this function.
public Object push(O­bject item)
This method pushes an item onto the top of this stack.
public int search­(Object o)
This method returns the 1-based position where an object is on this stack.

import java.u­til.Random

protected int next(int bits)
This method generates the next pseudo­random number.
public boolean nextX()
X = Boolea­n/I­nt/­Dou­ble­/Fl­oat­/Long uniformly distri­buted between 0 and 1
public double nextGa­uss­ian()
This method returns the next pseudo­random, Gaussian ("no­rma­lly­") distri­buted double value with mean 0.0 and standard deviation 1.0 from this random number genera­tor's sequence.
public int nextIn­t(int n)
This method returns a pseudo­random, uniformly distri­buted int value between 0 (inclu­sive) and the specified value (exclu­sive), drawn from this random number genera­tor's sequence.
public void setSee­d(long seed)
This method sets the seed of this random number generator using a single long seed.
 

Comments

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          ISTQB Test Automation Engineering Cheat Sheet
          Cypressio Cheat Sheet
          Selenium WebDriver Cheat Sheet Cheat Sheet

          More Cheat Sheets by xys

          Python Cheat Sheet
          HTML Cheat Sheet
          python thread Cheat Sheet