Tech News

Java Cheat Sheet


Java Language Cheat Sheet: Built-In Java Methods

Number Methods
xxxValue()
Converts the value of this Number object to the xxx data type and returns it
compareTo()
Compares this Number object to the argument
equals()
Determines whether this number object is equal to the argument
valueOf()
Returns an Integer object holding the value of the specified primitive
toString()
Returns a String object representing the value of a specified int or Integer
parseInt()
This method is used to get the primitive data type of a certain string
abs()
Returns the absolute value of the argument
ceil()
Returns the smallest integer that is greater than or equal to the argument. Returned as a double
floor()
Returns the largest integer that is less than or equal to the argument. Returned as a double
rint()
Returns the integer that is closest in value to the argument. Returned as a double
round()
Returns the closest long or int, as indicated by the method's return type to the argument
min()
Returns the smaller of the two arguments
max()
Returns the larger of the two arguments
exp()
Returns the base of the natural logarithms, e, to the power of the argument
log()
Returns the natural logarithm of the argument
pow()
Returns the value of the first argument raised to the power of the second argument
sqrt()
Returns the square root of the argument
sin()
Returns the sine of the specified double value
cos()
Returns the cosine of the specified double value
tan()
Returns the tangent of the specified double value
asin()
Returns the arcsine of the specified double value
acos()
Returns the arccosine of the specified double value
atan()
Returns the arctangent of the specified double value
atan2()
Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta
toDegrees()
Converts the argument to degrees
toRadians()
Converts the argument to radians
random()
Returns a random number

Character Methods
isLetter()
Determines whether the specified char value is a letter
isDigit()
Determines whether the specified char value is a digit
isWhitespace()
Determines whether the specified char value is white space
isUpperCase()
Determines whether the specified char value is uppercase
isLowerCase()
Determines whether the specified char value is lowercase
toUpperCase()
Returns the uppercase form of the specified char value
toLowerCase()
Returns the lowercase form of the specified char value
toString()
Returns a string object representing the specified character value that is, a one-character string

String Methods
char charAt(int index)
Returns the character at the specified index
int compareTo(Object o)
Compares this string to another object
int compareTo(String anotherString)
Compares two strings lexicographically
int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences
String concat(String str)
Concatenates the specified string to the end of this string
boolean contentEquals(StringBuffer sb)
Returns true if and only if this string represents the same sequence of characters as the specified StringBuffer
static String copyValueOf(char[] data)
Returns a string that represents the character sequence in the array specified
static String copyValueOf(char[] data, int offset, int count)
Returns a string that represents the character sequence in the array specified
boolean endsWith(String suffix)
Tests if this string ends with the specified suffix
boolean equals(Object anObject)
Compares this string to the specified object
boolean equalsIgnoreCase(String anotherString)
Compares this string to another string, ignoring case considerations
byte getBytes()
Encodes this string into a sequence of bytes using the platform's default charset, storing the result into a new byte array
byte[] getBytes(String charsetName)
Encodes this string into a sequence of bytes using the named charset, storing the result into a new byte array
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array
int hashCode()
Returns a hash code for this string
int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character
int indexOf(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
int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index
String intern()
Returns a canonical representation for the string object
int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character
int lastIndexOf(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
int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring
int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index
int length()
Returns the length of this string
boolean matches(String regex)
Tells whether or not this string matches the given regular expression
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal
boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar
String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given replacement
String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement
String[] split(String regex)
Splits this string around matches of the given regular expression
String[] split(String regex, int limit)
Splits this string around matches of the given regular expression
boolean startsWith(String prefix)
Tests if this string starts with the specified prefix
boolean startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index
CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence
String substring(int beginIndex)
Returns a new string that is a substring of this string
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string
char[] toCharArray()
Converts this string to a new character array
String toLowerCase()
Converts all of the characters in this string to lower case using the rules of the default locale
String toLowerCase(Locale locale)
Converts all of the characters in this string to lower case using the rules of the given Locale
String toString()
This object (which is already a string!) is itself returned
String toUpperCase()
Converts all of the characters in this string to upper case using the rules of the default locale
String toUpperCase(Locale locale)
Converts all of the characters in this string to upper case using the rules of the given Locale
String trim()
Returns a copy of the string, with leading and trailing whitespace omitted
static String valueOf(primitive data type x)
Returns the string representation of the passed data type argument.

Array Class Methods
public static int binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, it returns ( – (insertion point + 1))
public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other primitive data types (Byte, short, Int, etc.)
public static void fill(int[] a, int val)
Assigns the specified int value to each element of the specified array of ints. The same method could be used by all other primitive data types (Byte, short, Int, etc.)
public static void sort(Object[] a)
Sorts the specified array of objects into an ascending order, according to the natural ordering of its elements. The same method could be used by all other primitive data types ( Byte, short, Int, etc.)

Date & Time Methods
boolean after(Date date)
Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false
boolean before(Date date)
Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false
Object clone( )
Duplicates the invoking Date object
int compareTo(Date date)
Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date
int compareTo(Object obj)
Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException
boolean equals(Object date)
Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false
long getTime( )
Returns the number of milliseconds that have elapsed since January 1, 1970
int hashCode( )
Returns a hash code for the invoking object
void setTime(long time)
Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970
String toString( )
Converts the invoking Date object into a string and returns the result

GregorianCalendar Class Methods
void add(int field, int amount)
Adds the specified (signed) amount of time to the given time field, based on the calendar's rules
protected void computeFields()
Converts UTC as milliseconds to time field values
protected void computeTime()
Overrides Calendar Converts time field values to UTC as milliseconds
boolean equals(Object obj)
Compares this GregorianCalendar to an object reference
int get(int field)
Gets the value for a given time field
int getActualMaximum(int field)
Returns the maximum value that this field could have, given the current date
int getActualMinimum(int field)
Returns the minimum value that this field could have, given the current date
int getGreatestMinimum(int field)
Returns highest minimum value for the given field if varies
Date getGregorianChange()
Gets the Gregorian Calendar change date
int getLeastMaximum(int field)
Returns lowest maximum value for the given field if varies
int getMaximum(int field)
Returns maximum value for the given field
Date getTime()
Gets this Calendar's current time
long getTimeInMillis()
Gets this Calendar's current time as a long
TimeZone getTimeZone()
Gets the time zone
int getMinimum(int field)
Returns minimum value for the given field
int hashCode()
Overrides hashCode
boolean isLeapYear(int year)
Determines if the given year is a leap year
void roll(int field, boolean up)
Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields
void set(int field, int value)
Sets the time field with the given value
void set(int year, int month, int date)
Sets the values for the fields year, month, and date
void set(int year, int month, int date, int hour, int minute)
Sets the values for the fields year, month, date, hour, and minute
void set(int year, int month, int date, int hour, int minute, int second)
Sets the values for the fields year, month, date, hour, minute, and second
void setGregorianChange(Date date)
Sets the GregorianCalendar change date
void setTime(Date date)
Sets this Calendar's current time with the given Date
void setTimeInMillis(long millis)
Sets this Calendar's current time from the given long value
void setTimeZone(TimeZone value)
Sets the time zone with the given time zone value
String toString()
Returns a string representation of this calendar

Index Methods
public int start()
Returns the start index of the previous match
public int start(int group)
Returns the start index of the subsequence captured by the given group during the previous match operation
public int end()
Returns the offset after the last character matched
public int end(int group)
Returns the offset after the last character of the subsequence captured by the given group during the previous match operation

Study Methods
public boolean lookingAt()
Attempts to match the input sequence, starting at the beginning of the region, against the pattern
public boolean find()
Attempts to find the next subsequence of the input sequence that matches the pattern
public boolean find(int start)
Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index
public boolean matches()
Attempts to match the entire region against the pattern

Replacement Methods
public Matcher appendReplacement(StringBuffer sb, String replacement)
Implements a non-terminal append-and-replace step
public StringBuffer appendTail(StringBuffer sb)
Implements a terminal append-and-replace step
public String replaceAll(String replacement)
Replaces every subsequence of the input sequence that matches the pattern with the given replacement string
public String replaceFirst(String replacement)
Replaces the first subsequence of the input sequence that matches the pattern with the given replacement string
public static String quoteReplacement(String s)
Returns a literal replacement string for the specified string. This method produces a string that will work as a literal replacement s in the appendReplacement method of the Matcher class

PatternSyntaxException Class Methods
public String getDescription()
Retrieves the description of the error
public int getIndex()
Retrieves the error index
public String getPattern()
Retrieves the erroneous regular expression pattern
public String getMessage()
Returns a multi-line string containing the description of the syntax error and its index, the erroneous regular expression pattern, and a visual indication of the error index within the pattern

InputStream Methods
public void close() throws IOException{}
Closes the file output stream. Releases any system resources associated with the file. Throws an IOException
protected void finalize()throws IOException {}
Cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException
public int read(int r)throws IOException{}
Reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it's the end of the file
public int read(byte[] r) throws IOException{}
Reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be returned
public int available() throws IOException{}
Gives the number of bytes that can be read from this file input stream. Returns an int

OutputStream Methods
public void close() throws IOException{}
Closes the file output stream. Releases any system resources associated with the file. Throws an IOException
protected void finalize()throws IOException {}
Cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException
public void write(int w)throws IOException{}
Writes the specified byte to the output stream
public void write(byte[] w)
Writes w.length bytes from the mentioned byte array to the OutputStream

Exceptions Methods
public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor
public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object
public String toString()
Returns the name of the class concatenated with the result of getMessage()
public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream
public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack
public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace

ServerSocket Class Methods
public ServerSocket(int port)
Attempts to create a server socket bound to the specified port. An exception occurs if the port is already bound by another application
public ServerSocket(int port, int backlog)
Similar to the previous constructor, the backlog parameter specifies how many incoming clients to store in a wait queue
public ServerSocket(int port, int backlog, InetAddress address)
Similar to the previous constructor, the InetAddress parameter specifies the local IP address to bind to. The InetAddress is used for servers that may have multiple IP addresses, allowing the server to specify which of its IP addresses to accept client requests on
public ServerSocket()
Creates an unbound server socket. When using this constructor, use the bind() method when you are ready to bind the server socket.
public int getLocalPort()
Returns the port that the server socket is listening on. This method is useful if you passed in 0 as the port number in a constructor and let the server find a port for you
public Socket accept()
Waits for an incoming client. This method blocks until either a client connects to the server on the specified port or the socket times out, assuming that the time-out value has been set using the setSoTimeout() method. Otherwise, this method blocks indefinitely
public void setSoTimeout(int timeout)
Sets the time-out value for how long the server socket waits for a client during the accept()
public void bind(SocketAddress host, int backlog)
Binds the socket to the specified server and port in the SocketAddress object. Use this method if you have instantiated the ServerSocket using the no-argument constructor

Socket Class Methods
public Socket(String host, int port)
Attempts to connect to the specified server at the specified port. If this constructor does not throw an exception, the connection is successful and the client is connected to the server
public Socket(InetAddress host, int port)
This method is identical to the previous constructor, except that the host is denoted by an InetAddress object
public Socket(String host, int port, InetAddress localAddress, int localPort)
Connects to the specified host and port, creating a socket on the local host at the specified address and port
public Socket(InetAddress host, int port, InetAddress localAddress, int localPort)
This method is identical to the previous constructor, except that the host is denoted by an InetAddress object instead of a string
public Socket()
Creates an unconnected socket. Use the connect() method to connect this socket to a server
public void connect(SocketAddress host, int timeout)
Connects the socket to the specified host. This method is needed only when you instantiate the Socket using the no-argument constructor
public InetAddress getInetAddress()
This method returns the address of the other computer that this socket is connected to
public int getPort()
Returns the port the socket is bound to on the remote machine
public int getLocalPort()
Returns the port the socket is bound to on the local machine
public SocketAddress getRemoteSocketAddress()
Returns the address of the remote socket
public InputStream getInputStream()
Returns the input stream of the socket. The input stream is connected to the output stream of the remote socket
public OutputStream getOutputStream()
Returns the output stream of the socket. The output stream is connected to the input stream of the remote socket
public void close()
Closes the socket, which makes this Socket object no longer capable of connecting again to any server

InetAddress Class Methods
static InetAddress getByAddress(byte[] addr)
Returns an InetAddress object given the raw IP address
static InetAddress getByAddress(String host, byte[] addr)
Creates an InetAddress based on the provided host name and IP address
static InetAddress getByName(String host)
Determines the IP address of a host, given the host's name
String getHostAddress()
Returns the IP address string in textual presentation
String getHostName()
Gets the host name for this IP address
static InetAddress InetAddress getLocalHost()
Returns the local host
String toString()
Converts this IP address to a string.

Thread Methods
public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object
public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object
public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name
public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10
public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread
public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes
public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason
public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion

Static Thread Methods
public static void yield()
Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled.
public static void sleep(long millisec)
Causes the currently running thread to block for at least the specified number of milliseconds
public static boolean holdsLock(Object x)
Returns true if the current thread holds the lock on the given Object
public static Thread currentThread()
Returns a reference to the currently running thread, which is the thread that invokes this method
public static void dumpStack()
Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application.

Methods Declared by Iterator
boolean hasNext( )
Returns true if there are more elements. Otherwise, returns false
Object next( )
Returns the next element. Throws NoSuchElementException if there is not a next element
void remove( )
Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( )

Methods Declared by ListIterator
void add(Object obj)
Inserts obj into the list in front of the element that will be returned by the next call to next( )
boolean hasNext( )
Returns true if there is a next element. Otherwise, returns false
boolean hasPrevious( )
Returns true if there is a previous element. Otherwise, returns false
Object next( )
Returns the next element. A NoSuchElementException is thrown if there is not a next element
int nextIndex( )
Returns the index of the next element. If there is not a next element, returns the size of the list.
Object previous( )
Returns the previous element. A NoSuchElementException is thrown if there is not a previous element
int previousIndex( )
Returns the index of the previous element. If there is not a previous element, returns -1
void remove( )
Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked
void set(Object obj)
Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( )

No comments:

Post a Comment