Вы находитесь на странице: 1из 10

Wrapper Methods

xxxValue() To convert a value of a wrapped numeric to a primitive


static parseXxx(String s) Takes a string (optional radix, e.g. 2, 10, 16) and returns a primitive (throws
NumberFormatException). For numeric types only.
static valueOf(String s) Takes a string (optional radix, e.g. 2, 10, 16) and returns a wrapper object
(throws NumberFormatException). Not for Character type
String toString() Returns the string representation of the value in the wrapped object
Character.valueOf(char c) Returns a Character instance representing the specified char value

Integer and Long Wrapper classes


Integer.valueOf(int i) Returns a Integer instance representing the specified int value.
Long.valueOf(long i) Returns a Long instance representing the specified long value.
String toHexString(int i) e.g. Integer.toHexString(254);
String toBinaryString(int i) e.g. Integer.toBinaryString(254);
String toOctalString(int i) e.g. Integer.toOctalString(254);
Note: Long version takes long e.g: Long.toOctalString(254L);

Methods on Strings
char charAt(int index) Returns the character on the specified index
String concat(String str) Appends one string to another (just like “+”)
boolean equalsIgnoreCase(String str) determines the equality of two strings (ignoring the case)
int length() returns the number of characters of the string
String replace( char oldChar, replaces occurences of a character with a new character
char newChar)
String substring(int beginIndex, Returns a new string that is a substring of this string.
int endIndex)
String toLowerCase() Returns a string with uppercase characters converted
String toString() Returns the value of a string
String toUpperCase() Returns a string with lowercase characters converted
String trim() Removes whitespace from the ends of the string
String[] split(String regex) Splits this string around matches of the given regular
expression.Trailing empty strings are not included in the
resulting array.

StringBuffer and StringBuilder


Methods:
public synchronized StringBuffer append(String s) will update the value of the object (also overloaded with
all primitive types except short )
public StringBuilder delete(int start, int end) will remove substring from start to end-1. If start is equal
to end, no changes are made.
public StringBuilder insert(int offset, String s) insert string in object at offset (zero-based)
public synchronized StringBuffer reverse() reverses the value of the StringBuffer object
public String toString() returns the value of the StringBuffer object

File Navigation and I/O


File: Abstract representation of file and directory names
FileReader: This class is used to read character files
BufferedReader: Read large chunks of data from a file and keep this data in a buffer (minimizing I/O)
FileWriter: This class is used to write characters or Strings to a file
BufferedWriter: Write large chunks of data to a file (minimizing I/O)
PrintWriter: An enhanced writer (no need of File being wrapped into BufferedWriter/FileWriter.
Constructor takes a File or a String.

java.io.OutputStreamWriter
OutputStreamWriter( Creates an OutputStreamWriter that uses the given charset
OutputStream out, CharsetEncoder enc) encoder.
Java io.class Key Constructor(s) Arguments Key Methods
File(File parent, String child) Creates a new File instance from a See below
parent abstract pathname and a Note read & write methods will throw
child pathname string. IOException, so needs to be caught.
File(String pathname) Creates a new File instance by
converting the given pathname string
into an abstract pathname.
File(String parent,String child) Creates a new File instance from a
parent pathname string and a child
pathname string.
FileWriter(File file)* Constructs a FileWriter object given
void close()
a File object. void flush()
FileWriter(String fileName)* Constructs a FileWriter object given
void write(int c)
* overloaded with apppend a file name. void write(String str, int off, int len)
option and throws IOException void write(char[], int off, int len)
BufferedWriter (Writer out) Creates a buffered character-output void close()
stream that uses a default-sized void flush()
output buffer. void newLine()
void write(/*as above*/)
PrintWriter(File file)~ Constructs without automatic line void close()
flushing, with the specified file. void flush()
PrintWriter(String fileName)~ Constructs without automatic line void write(/*as above*/)
flushing, with the specified file name. void write(char[] buf)
*PrintWriter(OutputStream out) Constructs without automatic line void write(String s)
flushing, from an existing format(String format, Object...args)
OutputStream. printf(String format, Object... args)
*PrintWriter(Writer out) Constructs without automatic line void print(primitive/Object)
flushing void println(primitive/Object)
*overloaded with boolean (~ throws FileNotFoundException, PrintWriter append(char c)
autoFlush. overloaded with String charset) PrintWriter append(CharSequence cs)
FileReader(File file) Creates a new FileReader, given the int read()
File to read from. int read(char[] cbuf, int off, int len)
FileReader(String fileName) Creates a new FileReader, given the void close()
name of the file to read from.
BufferedReader(Reader in) Creates a buffering character-input int read()
stream that uses a default-sized int read(char[] cbuf, int off, int len)
input buffer. String readLine()

java.io.File Description
public boolean createNewFile()* this method creates a new file if it doesn’t already exists
public boolean exists() checks if the file exists
public boolean delete() deletes a file or directory (if empty)
public boolean isDirectory() checks if the file is a directory
public boolean isFile() checks if the file is a file
public String[] list() lists the files in a directory, if the File is not a dir it returns null
public File[] listFiles() same as list expect returns a File[] instead of String[]
public boolean mkdir() creates a directory from the abstract pathname
public renameTo(File f) renames a file or directory (even if not empty)
public boolean mkdirs() creates directories including non existent parent dirs
*use in a try catch block with IOException

java.io. FileInputStream Description


FileInputStream(File file) Creates a FileInputStream by opening a connection to an actual file,
throws FileNotFoundException the file named by the File object file in the file system.
FileInputStream(String name) Creates a FileInputStream by opening a connection to an actual file,
throws FileNotFoundException the file named by the path name name in the file system.
int read() throws IOException Returns the next byte of data read, or -1 if the EOF is reached.
int read(byte[] b) throws IOException Returns the total number of bytes read into the buffer, or -1 if there is
no more data because the EOF has been reached.
java.io.Console Description
String readLine() Reads a single line of text from the console.
String readLine(String fmt, Object... args) Provides a formatted prompt, then reads a single line of text from
the console.
char[] readPassword() Reads a password or passphrase from the console with echoing
disabled
char[] readPassword(String fmt, Object... Provides a formatted prompt, then reads a password or
args) passphrase from the console with echoing disabled.
Console format(String fmt, Object... args) Writes a formatted string to this console's output stream using the
specified format string and arguments.
Console printf(String fmt, Object... args) A convenience method to write a formatted string to this console's
output stream using the specified format string and arguments.
PrintWriter writer() Retrieves the unique PrintWriter object associated with this
console.
Reader reader() Retrieves the unique Reader object associated with this console.
void flush() Flushes the console and forces any buffered output to be written
immediately.

Java.util.Calendar (abstract class) No constructor, but a factorymethods


Calendar.getInstance() Returns a Calendar using the default time zone and locale.
Calendar.getInstance(Locale l) Returns a Calendar using the default time zone and specified
locale.
void set(int field, int value) Sets the given calendar field to the given value.
void set(int year, int month, int date) Sets the values for the calendar fields YEAR, MONTH, and
DAY_OF_MONTH.
void setTime(Date date) Sets this Calendar's time with the given Date.
int get(int field) Returns the value of the given calendar field.
void add(int field, int amount) Adds or subtracts the specified amount of time to the given
calendar field, based on the calendar's rules.
void roll(int field, int amount) Adds the specified (signed) amount to the specified calendar field
without changing larger fields.
Date getTime() Returns a Date object representing this Calendar's time value
boolean after(Object when) Returns whether this Calendar represents a time after or before
boolean before(Object when) the time represented by the specified Calendar obj.

java.util.Date Date constructors


Date() Allocates a Date object and initializes to current date and time
Date(long millisec) Default constructor and a constructor with a long (no of miliseconds since 1970)
long getTime() Returns the number of milliseconds since epoch
void setTime(long time) Sets the current Date object to the date measured in milliseconds after epoch.

java.util.Locale Locale constructors


Locale.getDefault() Gets the current value of the default locale for this instance
of the Java Virtual Machine.
Locale (String Language) Construct a locale from a language code.
Locale (String Language, String Country) Construct a locale from language, country.

java.util.Locale Locale methods


String getDisplayCountry() returns a String representing the coutry’s name
String getDisplayCountry(Locale inLocale) returns a String representing the coutry’s name but in
the given locale.
String getDisplayLanguage() returns a String representing the language name
String getDisplayLanguage(Locale inLocale) returns a String representing the language name but in
given locale.
java.text.DateFormat (abstract class) No constructors, but a factorymethods
DateFormat.getInstance() Get a default date/time formatter that uses the SHORT
style for both the date and the time.
DateFormat.getDateInstance() Gets the date/time formatter with the default formatting
style for the default locale.
DateFormat.getDateInstance(int style) Gets the date formatter with the given formatting style
for the default locale.
DateFormat.getDateInstance(int style, Locale Gets the date formatter with the given formatting style
aLocale) for the given locale.
DateFormat.getDateTimeInstance() Gets the time formatter with the default formatting style
for the default locale.
DateFormat.getDateTimeInstance(int dateStyle, Gets the time formatter with the given formatting style
int timeStyle) for the given locale.
DateFormat.getDateTimeInstance(int dateStyle, Gets the date/time formatter with the given formatting
int timeStyle, Locale aLocale) styles for the given locale.

java.text.DateFormat DateFormat methods


Date parse(String) parse a string into a Date (throws a checked ParseException)
String format(date) formats a date into a String

java.text.NumberFormat (abstract class) No constructors, factory methods


NumberFormat.getInstance() Returns a number format for the default locale.
NumberFormat.getInstance(Locale l) Returns a number format for the given locale.
NumberFormat.getNumberInstance() Returns a number format for the default locale.
NumberFormat.getNumberInstance(Locale l) Returns a number format for the given locale.
NumberFormat.getCurrencyInstance() Returns a currency format for the default locale.
NumberFormat.getCurrencyInstance(Locale l) Returns a currency format for the specified locale

java.text.NumberFormat NumberFormat methods


int getMaximumFractionDigits() retuns the maximum number of digits in the fraction
int setMaximumFractionDigits() sets the maximum number of digits in the fraction
void setParseIntegerOnly(true) Sets whether or not numbers should be parsed as integers only
Number parse(String source) Parses text from the beginning of the given string to produce a number.
(throws checked exception - ParseException)
String format(long number) formats a long/double into a String
String format(double number)
java.text.NumberFormat extends from java.text.Format

java.util.regex.Pattern
static Pattern compile(String regex) Compiles the given regular expression into a pattern.
static boolean matches(String regex, Compiles the given regular expression and attempts to match
CharSequence input) the given input against it.
Matcher matcher(CharSequence input) Creates a matcher that will match the given input against this
pattern

java.util.regex.Matcher
boolean find() Attempts to find the next subsequence of the input sequence that
matches the pattern.
String group() Returns the input subsequence matched by the previous match.
int start() Returns the start index of the previous match.

int end() Returns the offset after the last character matched.

java.util.Scanner Scanner constructors


Scanner(File source) Constructs a new Scanner that produces values scanned from the
specified file. Throws FileNotFoundException - if source is not found
Scanner(String source) Constructs a new Scanner that produces values scanned from the
specified string.
Scanner(InputStream source) Constructs a new Scanner that produces values scanned from the
specified input stream

java.util.Scanner Scanner methods


Scanner useDelimiter(String pattern) Sets this scanner's delimiting pattern to a pattern constructed from
Scanner useDelimiter(Pattern pattern) the specified String or Pattern.
String findInLine(String pattern) Attempts to find the next occurrence of a pattern constructed from
String findInLine(Pattern pattern) the specified string/pattern, ignoring delimiters.
boolean hasNextLine() Returns true if there is another line in the input of this scanner.
String nextLine() Advances this scanner past the current line and returns the input
that was skipped.
boolean hasNext() Returns true if this scanner has another token in its input.
String next() Finds and returns the next complete token from this scanner.
boolean hasNextTypexxx() Returns true if the next token in this scanner's input can be
interpreted as numeric value (typexxx) in the default radix using
the nextTypexxx() method. Boolean value is also supported
typexxx nextTypexxx() Scans the next token of the input as a numeric type (byte, short,
int, long, float, double) or boolean and returns it if found.

Method of Object Class Description


boolean equals (Object o) Decides whether two objects are meaningful ly equivalent
protected void finalize() Called by the garbage collector (when the object is not referenced anymore)
(throws checked exception Throwable)
int hashCode() Returns an int (hash) so that the object can be used in hashed Collections
final void notify() Wakes up a thread that is waiting for this object’s lock
final void notifyAll() Wakes up all threads that are waiting for this object’s lock
final void wait() Causes this thread to wait until another thread calls notify or notifyAll on this
final void wait(long) object (throws checked exception - InterruptedException)
String toString() Returns a string representation of this object

java.lang.Comparable java.util.Comparator
int thisObject.compareTo(anotherObject) int compare(thisObject, anotherObject)
You must modify the class whose instances you You build a seperate class from the class whose
want to sort instances you want to sort
One sort sequence Many sort sequences (by creating many comparators)
Implemented frequently in the API by: String, Meant to be implemented to sort instances of third-party
Wrapper Classes, Date, Calendar... classes

Method Overview for Arrays and Collections


java.util.Arrays Description
static List<T> asList(T...a) Convert an array to a list (backed by the list)
static int binarySearch(Object[], key) Search a sorted array for a given value, return an index or
static int binarySearch(primitiveTypexxx[], key) an -(insertion point)-1 (= number between -1 and -length).
static int binarySearch(T[], T key, Search a Comparator-sorted array
Comparator)
static boolean equals(Object[], Object[]) Compare two arrays and determine if their contents are
static boolean equals(primitive[], primitive[]) equal
static void sort(Object[]) Sort the elements of an array by natural order
static void sort(primitiveTypexxx[])
static void sort(T[], Comparator) Sort the elements of an array using a Comparator
static String toString(Object[]) Create a string containing the elements of an array
static String toString(primitiveTypexxx [])
java.util.Collections Description
static boolean addAll(Collection c, T... elements) Adds all of the specified elements to the specified
collection.
static int binarySearch(List, T key) Search a sorted list for a given value return an index or an
static int binarySearch(List, T key, Comparator) insertion point
static void reverse(List) Reverse the order of the elements of the list
static Comparator reverseOrder() Return a Comparator that sorts the reverse of the
static Comparator reverseOrder(Comparator) collection’s current sort sequence
static void sort(List) Sort a List by natural order or by Comparator
static void sort(List, Comparator)

Method Overview for List, Set, Map and Queue


Key Interface methods List Set Que Map Description
boolean add(element) X X X Add an element. For a List optionally at a
boolean add(element, index) X given index
boolean contains(object) X X X Search a collection for an object (or
boolean containsKey(object key) X optionally for a Map a key) return the result
boolean containsValue(object value) X as a boolean
E get(int index) X Get an object from a collection via an index
V get(Object key) X or a key from a map
int indexOf(Object) X Get the location of an Object in a List
Iterator iterator() X X X Get an iterator for a List or a Set
Set<K> keySet() X Return a Set of keys of the Map
V put(K key, V value) X Add a key, value pair to a Map
boolean remove(int index) X Remove an element from a List via an
boolean remove(Object object) X X X index, or via the elements value or from a
V remove(Object key) X Map via a key
int size() X X X X Return the number of elements of a
collection
Object[] toArray() X X X Return an array containing the elements of
T[] toArray(T[] a) X the collection (not backed by the array)
Collection values() X Returns a collection with the values from
the map. The collection is backed by the
map
List<E> subList(int from, int to) X Returns a view of the portion of this list

Method Overview for PriorityQueue


Method Description
boolean offer(E e) Inserts the specified element into this priority queue.
E peek() Retrieves, but does not remove, the head of this queue, or returns null if this queue is
empty.
E poll() Retrieves and removes the head of this queue, or returns null if this queue is empty.

Method Overview for SortedSet


Key Interface methods Description
Comparator<? super E> comparator() Returns the comparator used to order the elements in this set, or
null if this set uses the natural ordering of its elements.
E first() Returns the first (lowest) element currently in this set.
E last() Returns the last (highest) element currently in this set.
SortedSet<E> headSet(E toElement) Returns a view of the portion of this set whose elements are strictly
less than toElement.
SortedSet<E> tailSet(E fromElement) Returns a view of the portion of this set whose elements are greater
than or equal to fromElement.
SortedSet<E> subSet(E fromElement, Returns a view of the portion of this set whose elements range from
E toElement) fromElement, inclusive, to toElement, exclusive.
The returned set is backed by this set, so changes in the returned
set are reflected in this set, and vice-versa.
Method Overview for NavigableSet
Key Interface Methods Description
Iterator<E> descendingIterator() Returns an iterator over the elements in descending order
NavigableSet<E> descendingSet() Returns a reverse order view of the elements in this set
E ceiling(E e) Returns the least element in this set greater than or equal to the
given element, or null if there is no such element.
E higher(E e) Returns the least element in this set strictly greater than the given
element, or null if there is no such element.
E lower(E e) Returns the greatest element in this set strictly less than the
given element, or null if there is no such element.
E floor(E e) Returns the greatest element in this set less than or equal to the
given element, or null if there is no such element.
E pollFirst() Retrieves and removes the first (lowest) element, or returns null if
this set is empty.
E pollLast() Retrieves and removes the last (highest) element, or returns null
if this set is empty.
NavigableSet<E> headSet( Returns a view of the portion of this set whose elements are less
E toElement, boolean inclusive) than (or equal to, if inclusive is true) toElement
NavigableSet<E> tailSet( Returns a view of the portion of this set whose elements are
E fromElement, boolean inclusive) greater than (or equal to, if inclusive is true) fromElement
NavigableSet<E> subSet( Returns a view of the portion of this set whose elements range
E fromElement, boolean fromInclusive, from fromElement to toElement.
E toElement, boolean toInclusive)

Method Overview for SortedMap


Key Interface methods Description
Comparator<? super E> comparator() Returns the comparator used to order the keys in this map, or null if
this map uses the natural ordering of its keys.
Set<Map.Entry<K,V>> entrySet() Returns a Set view of the mappings contained in this map.
K firstKey() Returns the first (lowest) key currently in this map.
K lastKey() Returns the last (highest) element currently in this set.
SortedMap<K,V> headMap(K toKey) Returns a view of the portion of this map whose keys are strictly
less than toKey.
SortedMap<K,V> tailMap(K fromKey) Returns a view of the portion of this map whose keys are greater
than or equal to fromKey.
SortedMap<K,V> subMap(K fromKey, Returns a view of the portion of this map whose keys range from
K toKey) fromKey, inclusive, to toKey, exclusive.
The returned map is backed by this map, so changes in the
returned map are reflected in this map, and vice-versa.

Interface Map.Entry<K,V>
Key Interface methods Description
K getKey() Returns the key corresponding to this entry.
V getValue() Returns the value corresponding to this entry.
V setValue(V value) Replaces the value corresponding to this entry with
the specified value (optional operation).
Method Overview for NavigableMap
Key Interface Methods Description
NavigableMap<K,V> descendingMap() Returns a reverse order view of the mappings contained in this map

NavigableSet<K> descendingKeySet() Returns a reverse order NavigableSet view of the keys contained in
this map. The set is backed by the map.
NavigableSet<K> navigableKeySet() Returns a NavigableSet view of the keys contained in this map.
NavigableMap<K,V> headMap( Returns a view of the portion of this map whose keys are less than
K toKey, boolean inclusive) (or equal to, if inclusive is true) toKey
NavigableMap<K,V> tailMap( Returns a view of the portion of this map whose keys are greater
K fromKey, boolean inclusive) than (or equal to, if inclusive is true) fromKey
SortedMap<K,V> subMap( Returns a view of the portion of this map whose keys range from
K fromKey, K toKey) fromKey, inclusive, to toKey, exclusive.
NavigableMap<K,V> subMap( Returns a view of the portion of this map whose keys range from
K fromKey, boolean fromInclusive, fromKey to toKey.
K toKey, boolean toInclusive) The returned map is backed by this map, so changes in the
returned map are reflected in this map, and vice-versa.
firstEntry Map.Entry<K,V> firstEntry() Returns a key-value mapping associated with the least key in this
map, or null if the map is empty.
Map.Entry<K,V> pollFirstEntry() Removes and returns a key-value mapping associated with the
least key in this map, or null if the map is empty.
Map.Entry<K,V> lastEntry() Returns a key-value mapping associated with the greatest key in
this map, or null if the map is empty.
Map.Entry<K,V> pollLastEntry() Removes and returns a key-value mapping associated with the
greatest key in this map, or null if the map is empty.
K floorKey(K key) Returns the greatest key less than or equal to the given key, or null
if there is no such key.
K ceilingKey(K key) Returns the least key greater than or equal to the given key, or null
if there is no such key.
K higherKey(K key) Returns the least key strictly greater than the given key, or null if
there is no such key.
K lowerKey(K key) Returns the greatest key strictly less than the given key, or null if
there is no such key.
Map.Entry<K,V> floorEntry(K key) Returns a key-value mapping associated with the greatest key less
than or equal to the given key, or null if there is no such key.
Map.Entry<K,V> ceilingEntry(K key) Returns a key-value mapping associated with the least key greater
than or equal to the given key, or null if there is no such key.
Map.Entry<K,V> higherEntry(K key) Returns a key-value mapping associated with the least key strictly
greater than the given key, or null if there is no such key.
Map.Entry<K,V> lowerEntry(K key) Returns a key-value mapping associated with the greatest key
strictly less than the given key, or null if there is no such key.

Method Overview for Thread


Method Description
Thread() Allocates a new Thread object. Automatically generated names are of the
form "Thread-"+n, where n is an integer.
Thread(Runnable target) Allocates a new Thread object.
Thread(String name) Allocates a new Thread object with the name of the new thread..
static Thread currentThread() Returns a reference to the currently executing thread object.
void join() Waits for this thread to die.
throws InterruptedException
static void sleep(long millis) Causes the currently executing thread to sleep (temporarily cease
throws InterruptedException execution) for the specified number of milliseconds
static void yield() Causes the currently executing thread object to temporarily pause and allow
other threads to execute.
void run() If this thread was constructed with a Runnable object, then that Runnable
object's run method is called; otherwise, this method does nothing.
void start() Causes this thread to begin execution; the Java Virtual Machine calls the
run method of this thread.
Enum Types
Inherited Final Method s Description
int compareTo(E o) Compares this enum with the specified object for order (according to their
ordinal values).
boolean equals(Object other) Returns true if the specified object is equal to this enum constant (same as
== operator as enums are final static constants).
String name() Returns the name of this enum constant, exactly as declared in its enum
declaration.
int ordinal() Returns the ordinal value of this enum constant (zero based).
Implict Method s Description
static T valueOf(String name) Returns the enum constant of the specified enum type with the specified
name. The name must match exactly an identifier used to declare an enum
constant in this type, otherwise IllegalArgumentException is thrown
static T[] values Returns an array containing the enum constants of this type, in the order
they are specified.

java.lang.System class
Field Summary Description
static PrintStream err The "standard" error output stream.
static InputStream in The "standard" input stream
static PrintStream out The "standard" output stream.

Method summary Description


static Console console() Returns the unique Console object associated with the current
Java virtual machine, if any.
static void gc() Runs the garbage collector.
static Properties getProperties() The current set of system properties for use by the
getProperty(String) method is returned as a Properties object.
static String getProperty(String key) Gets the system property indicated by the specified key.
static String setProperty(String key, Sets the system property indicated by the specified key.
String value)
static void exit(int status) Terminates the currently running Java Virtual Machine.

Checked Exceptions
java.lang.Exception Description
ClassNotFoundException This signals that the JVM tried to load a class by its string name, but the
class could not be found. E.g. when the class name is misspelled while
starting program execution with the java command.
IllegalAccessException This is thrown when an application tries to reflectively create an instance,
set or get a field, or invoke a method, but the currently executing method
does not have access to the definition of the field, method or constructor.
InterruptedException Thrown when a thread is waiting, sleeping, or otherwise occupied, and the
thread is interrupted
ParseException Signals that an error has been reached unexpectedly while parsing.
CloneNotSupportedException Thrown to indicate that the clone method in class Object has been called
but that the object's class does not implement the Cloneable interface
IOException Signals that an I/O exception of some sort has occurred.
EOFException Signals that an end of file or end of stream has been reached unexpectedly
during input.
FileNotFoundException Signals that an attempt to open the file denoted by a specified pathname
has failed.
NotSerializableException Thrown when an instance is required to have a Serializable interface.
StreamCorruptedException Thrown when control information that was read from an object stream
violates internal consistency checks.
OptionalDataException Exception indicating the failure of an object read operation due to unread
primitive data, or the end of data belonging to a serialized object in the
stream
Unchecked Exceptions
java.lang.RuntimeException Description
ArithmeticException Thrown when an exceptional arithmetic condition has occurred. For
example, an integer "divide by zero" throws an instance of this class.
ArrayIndexOutOfBoundsException Thrown to indicate that an array has been accessed with an illegal
index. The index is either negative or greater than or equal to the size
of the array.
ClassCastException Thrown to indicate that the code has attempted to cast an object to a
subclass of which it is not an instance..
IllegalArgumentException Thrown to indicate that a method has been passed an illegal or
inappropriate argument
IllegalStateException Signals that a method has been invoked at an illegal or inappropriate
time.
IllegalMonitorStateException Thrown to indicate that a thread has attempted to wait on an object's
monitor or to notify other threads waiting on an object's monitor without
owning the specified monitor.
NoSuchElementException Thrown by the nextElement method of an Enumeration to indicate that
there are no more elements in the enumeration (iterator.next()).
NullPointerException This exception is typically thrown by the JVM when an attempt is made
to use the null value as a reference value to refer to an object.
NumberFormatException Thrown to indicate that the application has attempted to convert a
string to one of the numeric types, but that the string does not have the
appropriate format. The class NumberFormatException is a subclass
of the IllegalArgumentException class

Error
java.lang.Error Description
ExceptionInInitializerError An ExceptionInInitializerError is thrown to indicate that an exception
occurred during evaluation of a static initializer or the initializer for a
static variable.
StackOverflowError Thrown when a stack overflow occurs because an method recurses too
deeply.
NoClassDefFoundError JVM can’t find a .class file
AssertionError thrown when the statement’s boolean test returns false

java.lang.Runtime class
Method summary Description
static Runtime getRuntime() Returns the runtime object associated with the current Java
application.
void gc() Runs the garbage collector.

Custom Serialization Example


private void writeObject(ObjectOutputStream oos) try { oos.defaultWriteObject();
throws IOException oos.writeInt(myclass.getSize());
} catch (Exception e) { e.printStackTrace(); }
private void readObject(ObjectInputStream ois) try { is.defaultReadObject();
throws IOException, ClassNotFoundException int size = is.readInt();
myclass = new myclass(size);
} catch (Exception e) { e.printStackTrace(); }

Вам также может понравиться