Download Java API - Chalmers

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
1 (26)
Java API
A compilation of selected constructors and methods in some common Java classes.
CONTENTS
Miscellaneous
Strings
Data structures
Streams and files
Observer
Threads and timers
Communication
Reflection
GUI
JUnit
Page
1
3
6
10
16
16
18
21
21
26
Miscellaneous
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
2 (26)
void wait(long timeout) throws InterruptedException
Causes the current thread to wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount
of time has elapsed.
interface java.lang.Comparable<T>
int compareTo(T obj)
Compares this object with the specified object for order.
interface java.util.Comparator<T>
int compare(T obj1, T obj2)
Compares its two arguments for order.
class java.lang.Integer: analogous for long, float, double, char, boolean, etc.
static int parseInt(String s) throws NumberFormatException
Parses the string argument as a signed decimal integer.
class java.lang.Math:
class java.lang.Object:
protected Object clone()throws CloneNotSupportedException
Creates and returns a copy of this object.
boolean equals(Object obj)
Indicates whether some other object is "equal to" this one.
Class getClass()
Returns the runtime class of this Object.
int max(int a,int b)
long max(long a,long b)
float max(float a,float b)
double max(double a,double b)
Returns the greater of a and b.
int min(int a,int b)
long min(long a,long b)
float min(float a,float b)
double min(double a,double b)
Returns the smaller of a and b.
int hashCode()
Returns a hash code value for the object.
class java.util.Random:
void notify()
Wakes up a single thread that is waiting on this object's monitor.
Random()
Creates a new random number generator.
void notifyAll()
Wakes up all threads that are waiting on this object's monitor.
int nextInt(int bound)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the
specified value (exclusive), drawn from this random number generator's sequence.
String toString()
Returns a string representation of the object.
class java.util.Date:
void wait()throws InterruptedException
Causes the current thread to wait until another thread invokes the notify() method or
the notifyAll() method for this object.
Date()
Allocates a Date object and initializes it so that it represents the time at which it was
allocated.
Version: 2017-03-14
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
Objektorienterade applikationer 2016/2017
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
3 (26)
String toString()
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
(where dow = day of week)
class java.util.Scanner:
Scanner(File source) throws FileNotFoundException
Constructs a new Scanner that produces values scanned from the specified file.
Scanner(InputStream source)
Constructs a new Scanner that produces values scanned from the specified input stream.
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
4 (26)
characters as the argument; in other words, the newly created string is a copy of the
argument string.
char charAt(int index)
Returns the character at the specified index.
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.
Scanner(String source)
Constructs a new Scanner that produces values scanned from the specified string.
boolean contains(String str)
Returns true if and only if this string contains the specified string.
boolean hasNext()
Returns true if this scanner has another token in its input.
boolean contentEquals(StringBuffer sb)
Returns true if and only if this String represents the same sequence of characters as the
specified StringBuffer.
boolean hasNext(String pattern)
Returns true if the next token matches the pattern constructed from the specified string.
static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array specified.
boolean hasNextInt()
analogous for long, float, double, char, boolean, etc.
Returns true if the next token in this scanner's input can be interpreted as an int value
in the default radix using the nextInt() method.
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 hasNextLine()
Returns true if there is another line in the input of this scanner.
boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
String next()
Finds and returns the next complete token from this scanner.
byte[] getBytes()
Encodes this String into a sequence of bytes, storing the result into a new byte array.
String nextLine()
Advances this scanner past the current line and returns the input that was skipped.
Strings
class java.lang.String:
String()
Initializes a newly created String object so that it represents an empty
character sequence.
String(char[] value)
Allocates a new String so that it represents the sequence of characters currently
contained in the character array argument.
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(byte[] bytes)
Constructs a new String by decoding the specified array of bytes using the platform's
default charset.
int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
String(String original)
Initializes a newly created String object so that it represents the same sequence of
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.
Version: 2017-03-14
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
Objektorienterade applikationer 2016/2017
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
5 (26)
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
int length()
Returns the length (character count).
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.
char charAt(int index)
Returns the char value in this sequence 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.
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string
with newChar.
StringBuilder insert(int offset,char c)
Inserts the string representation of the char argument into this sequence.
StringBuilder insert(int offset,String str)
Inserts the string into this character sequence.
StringBuilder delete(int start,int end)
Removes the characters in a substring of this sequence.
StringBuilder deleteCharAt(int index)
Removes the char at the specified position in this sequence.
String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the
given replacement.
String toString();
Returns a string representing the data in this sequence.
String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with
the given replacement.
Data Structures
String[] split(String regex)
Splits this string around matches of the given regular expression.
boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
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.
String toUpperCase()
Converts all of the characters in this String to upper case.
6 (26)
class java.util.ArrayList<E>:
ArrayList()
Constructs an empty list.
void add(int index, E element)
Inserts the specified element at the specified position in this list.
boolean add(E o)
Appends the specified element to the end of this list.
void clear()
Removes all of the elements from this list.
Object clone()
Returns a shallow copy of this list.
boolean contains(E elem)
Returns true if this list contains the specified element.
String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
boolean equals(Object o)
Returns true if and only if the specified object is also a list, both lists have the same
size, and all corresponding pairs of elements in the two lists are equal.
class java.lang.StringBuilder:
E get(int index)
Returns the element at the specified position in this list.
StringBuilder()
Constructs a string builder with no characters in it.
StringBuilder(String str)
Constructs a string builder initialized to the contents of the specified string.
int indexOf(E elem)
Searches for the first occurence of the given argument, testing for equality using the
equals method.
StringBuilder append(char c)
Appends the string representation of the char argument to this sequence.
StringBuilder append(String s)
Appends the specified string argument to this sequence.
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
boolean isEmpty()
Tests if this list has no elements.
Iterator iterator()
Returns an iterator over the elements in this list in proper sequence.
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
7 (26)
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
E remove(int index)
Removes the element at the specified position in this list.
E get(int index)
Returns the element at the specified position in this list.
E set(int index, E element)
Replaces the element at the specified position in this list with the specified element.
int indexOf(E elem)
Searches for the first occurence of the given argument, testing for equality using the
equals method.
int size()
Returns the number of elements in this list.
E[] toArray()
Returns an array containing all of the elements in this list in the correct order.
E[] toArray(E[] a)
Returns an array containing all of the elements in this list in the correct order;
the runtime type of the returned array is that of the specified array.
boolean isEmpty()
Tests if this list has no elements.
Iterator iterator()
Returns an iterator over the elements in this list in proper sequence.
E remove(int index)
Removes the element at the specified position in this list.
class java.util.LinkedList<E>:
E set(int index, E element)
Replaces the element at the specified position in this list with the specified element.
LinkedList()
Constructs an empty list.
int size()
Returns the number of elements in this list.
boolean addFirst(E o)
Inserts the specified element at the beginning of this list..
E[] toArray()
Returns an array containing all of the elements in this list in the correct order.
boolean addLast(E o)
Appends the specified element to the end of this list.
E[] toArray(E[] a)
Returns an array containing all of the elements in this list in the correct order;
the runtime type of the returned array is that of the specified array.
E getFirst()
Returns the first element in this list.
E getLast()
Returns the last element in this list.
E removeFirst()
Removes and returns the first element from this list.
E removeLast()
Removes and returns the last element from this list.
void add(int index, E element)
Inserts the specified element at the specified position in this list.
boolean add(E o)
Appends the specified element to the end of this list.
void clear()
Removes all of the elements from this list.
class java.util.Iterator<E>:
boolean hasNext()
Returns true if the iteration has more elements. (In other words, returns true if next would
return an element rather than throwing an exception.)
E next()
Returns the next element in the iteration.
Throws: NoSuchElementException - iteration has no more elements.
void remove()
Removes from the underlying collection the last element returned by the iterator. This
method can be called only once per call to next. The behavior of an iterator is unspecified
if the underlying collection is modified while the iteration is in progress in any way other
than by calling this method.
Object clone()
Returns a shallow copy of this list.
interface java.lang.Iterable<E>:
boolean contains(E elem)
Returns true if this list contains the specified element.
Iterator<E> iterator()
Returns an iterator over a set of elements of type T.
boolean equals(Object o)
Returns true if and only if the specified object is also a list, both lists have the same
size, and all corresponding pairs of elements in the two lists are equal.
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
8 (26)
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
9 (26)
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
class java.util.HashSet<E>,
class java.util.TreeSet<E>:
Set<Map.Entry<K,V>> entrySet()
Returns a collection view of the mappings contained in this map.
HashSet()
Constructs a new, empty HashSet.
V get(Object key)
Returns the value to which the specified key is mapped in this hash map,
or null if the map contains no mapping for this key.
TreeSet()
Constructs a new, empty TreeSet sorted according to the ordering
defined by the compareTo method in class E.
TreeSet(Comparator<E> comparator)
Constructs a new, empty tree set, sorted according to the specified comparator.
Methods (both classes)
boolean add(E o)
Adds the specified element to this set if it is not already present.
void clear()
Removes all of the elements from this set.
boolean contains(E o)
Returns true if this set contains the specified element.
boolean isEmpty()
Returns true if this set contains no elements.
boolean isEmpty()
Returns true if this map contains no key-value mappings.
Set<K> keySet()
Returns a set view of the keys contained in this map.
V put(K key, V value)
Associates the specified value with the specified key in this map.
V remove(Object key)
Removes the mapping for this key from this map if present.
int size()
Returns the number of key-value mappings in this map.
String toString()
Returns a string representation of this map. The string representation consists of a list of
key-value mappings enclosed in braces ("{}"). Adjacent mappings are separated by the
characters ", " (comma and space). Each key-value mapping is rendered as the key
followed by an equals sign ("=") followed by the associated value.
Iterator<E> iterator()
Returns an iterator over the elements in this set.
Collection<V> values()
Returns a collection view of the values contained in this map.
boolean remove(E o)
Removes the specified element from this set if it is present.
interface java.util.Map.Entry<K,V>:
int size()
Returns the number of elements in this set (its cardinality).
K getKey()
Returns the key corresponding to this entry.
class java.util.HashMap<K,V>, class java.util.TreeMap<K,V>:
V getValue()
Returns the value corresponding to this entry.
HashMap()
Constructs an empty HashMap.
Streams and Files
TreeMap()
Constructs an empty TreeMap.
General
void close()
Closes the stream.
Methods (both classes)
void clear()
Removes all mappings from this map.
boolean containsKey(Object key)
Returns true if this map contains a mapping for the specified key.
class java.io.FileReader:
FileReader(String fileName) throws FileNotFoundException
Creates a new FileReader, given the name of the file to read from.
boolean containsValue(Object value)
Returns true if this map maps one or more keys to the specified value.
int read() throws IOException
Reads a single character.
Version: 2017-03-14
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
10 (26)
Objektorienterade applikationer 2016/2017
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
11 (26)
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
int read(char[] cbuf, int off, int len) throws IOException
Reads characters into a portion of an array
void newLine()throws IOException
Writes a line separator.
long skip(long n) throws IOException
Skips n characters.
void write(char[] cbuf, int off, int len) throws IOException
Writes a portion of an array of characters.
class java.io.BufferedReader:
void write(int c) throws IOException
Writes a single character.
BufferedReader(Reader in)
Creates a buffering character-input stream that uses a input buffer.
int read() throws IOException
Reads a single character.
12 (26)
void write(String s, int off, int len) throws IOException
Writes a portion of a String.
class java.io.PrintWriter:
int read(char[] cbuf, int off, int len) throws IOException
Reads characters into a portion of an array.
PrintWriter(Writer out)
Creates a new PrintWriter.
String readLine() throws IOException
Reads a line of text.
long skip(long n) throws IOException
Skips characters.
void print(String s)
Prints a string.
void println(String s)
Prints a String and then terminates the line.
class java.io.FileWriter:
class java.io.FileInputStream:
FileWriter(String fileName) throws IOException
Constructs a FileWriter object given a file name.
FileWriter(String filename,boolean append) throws IOException
Constructs a FileWriter object given a file name, with a boolean indicating whether or not
to append the data written to the end of the file rather than the beginning.
void write(char[] cbuf, int off, int len) throws IOException
Writes a portion of an array of characters.
void write(int c) throws IOException
Writes a single character.
void write(String str, int off, int len) throws IOException
Writes a portion of a string.
void flush()throws IOException
Flushes the stream.
class java.io.BufferedWriter:
BufferedWriter(Writer out)
Creates a buffered character-output stream that uses a default-sized output buffer.
void flush()throws IOException
Flushes the stream.
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
FileInputStream(String name) throws FileNotFoundException
Creates a FileInputStream by opening a connection to an actual file,
the file named by the path name name in the file system.
int read()throws IOException
Reads a byte of data from this input stream.
int read(byte[] b, int off, int len) throws IOException
Reads up to len bytes of data from this input stream into an array of bytes.
long skip(long n) throws IOException
Skips over and discards n bytes of data from the input stream.
class java.io.DataInputStream:
DataInputStream(InputStream in)
Creates a DataInputStream that uses the specified underlying InputStream.
int read(byte[] b) throws IOException
Reads some number of bytes from the contained input stream
and stores them into the buffer array b.
int read(byte[] b, int off, int len) throws IOException
Reads up to len bytes of data from the contained input stream into an array of bytes.
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
13 (26)
boolean readBoolean()throws IOException
Reads one input byte and returns true if that byte is nonzero, false if that byte is
zero.
byte readByte()throws IOException
Reads and returns one input byte.
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
void reset()throws IOException
Repositions this stream to the position at the time the mark method was last called
on this input stream.
long skip(long n) throws IOException
Skips over and discards n bytes of data from this input stream.
char readChar()throws IOException
Reads two input bytes and returns a char value.
class java.io.InputStreamReader:
double readDouble()throws IOException
Reads eight input bytes and returns a double value.
InputStreamReader(InputStream in)
Creates an InputStreamReader that uses the default charset.
float readFloat()throws IOException
Reads four input bytes and returns a float value.
14 (26)
int read()throws IOException
Reads a single character.
int readInt()throws IOException
Reads four input bytes and returns an int value.
int read(char[] cbuf, int offset, int length) throws IOException
Reads characters into a portion of an array.
long readLong()throws IOException
Reads eight input bytes and returns a long value.
class java.io.FileOutputStream:
short readShort()throws IOException
Reads two input bytes and returns a short value.
int skipBytes(int n) throws IOException
Makes an attempt to skip over n bytes of data from the input stream,
discarding the skipped bytes.
class java.io.ObjectInputStream:
ObjectInputStream(InputStream in) throws IOException
Creates an ObjectInputStream that reads from the specified InputStream.
Object readObject()throws IOException,ClassNotFoundException
Read an object from the ObjectInputStream.
class java.io.BufferedInputStream:
BufferedInputStream(InputStream in)
Creates a BufferedInputStream that reads from the specified InputStream.
int read()throws IOException
Reads the next byte of data from the input stream.
int read(byte[] b, int off, int len) throws IOException
Reads bytes from this byte-input stream into the specified byte array,
starting at the given offset.
FileOutputStream(String name) throws FileNotFoundException
Creates a file output stream to write to the file with the specified name.
void write(byte[] b, int off, int len) throws IOException
Writes len bytes from the specified byte array starting at offset off
to this file output stream.
void write(int b) throws IOException
Writes the specified byte to this file output stream.
class java.io.DataOutputStream:
DataOutputStream(OutputStream out)
Creates a new data output stream to write data to the specified underlying output stream.
void write(byte[] b, int off, int len) throws IOException
Writes len bytes from the specified byte array starting at offset off
to the underlying output stream.
void write(int b) throws IOException
Writes the specified byte (the low eight bits of the argument b)
to the underlying output stream.
void writeBoolean(boolean v) throws IOException
Writes a boolean to the underlying output stream as a 1-byte value.
void writeByte(int v) throws IOException
Writes out a byte to the underlying output stream as a 1-byte value.
void writeBytes(String s) throws IOException
Writes out the string to the underlying output stream as a sequence of bytes.
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
15 (26)
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
16 (26)
class java.io.File:
void writeChar(int v) throws IOException
Writes a char to the underlying output stream as a 2-byte value, high byte first.
void writeChars(String s) throws IOException
Writes a string to the underlying output stream as a sequence of characters.
void writeDouble(double v) throws IOException
Converts the double argument to a long using the doubleToLongBits method in
class Double, and then writes that long value to the underlying output stream
as an 8-byte quantity, high byte first.
void writeFloat(float v) throws IOException
Converts the float argument to an int using the floatToIntBits method in class
Float, and then writes that int value to the underlying output stream as a 4-byte
quantity, high byte first.
void writeInt(int v) throws IOException
Writes an int to the underlying output stream as four bytes, high byte first.
void writeLong(long v) throws IOException
Writes a long to the underlying output stream as eight bytes, high byte first.
File(String pathname)
Creates a new File instance representing the given pathname.
boolean createNewFile() throws IOException
Creates a new, empty file named by this pathname if and only if a file with this name
does not yet exist. Returns true if the named file does not exist and was successfully
created; false if the named file already exists.
boolean exists()
Tests whether the file or directory denoted by this abstract pathname exists.
String getName()
Returns the name of the file or directory denoted by this abstract pathname.
boolean isDirectory()
Tests whether the file denoted by this abstract pathname is a directory.
boolean isFile()
Tests whether the file denoted by this abstract pathname is a normal file.
void writeShort(int v) throws IOException
Writes a short to the underlying output stream as two bytes, high byte first.
File[] listFiles()
Returns an array of abstract pathnames denoting the files in the directory denoted by
this abstract pathname.
class java.io.ObjectOutputStream:
Observer
ObjectOutputStream(OutputStream out) throws IOException
Creates an ObjectOutputStream that writes to the specified OutputStream.
class java.util.Observable:
void writeObject(Object obj) throws IOException,
NotSerializableException
Write the specified object to the ObjectOutputStream.
void addObserver(Observer o)
Adds an observer to the set of observers for this object.
protected void setChanged()
Marks this Observable object as having been changed.
class java.io.BufferedOutputStream:
void notifyObservers(Object arg)
If this object has changed, then notify all of its observers.
BufferedOutputStream(OutputStream out)
Creates a new buffered output stream to write data to the specified underlying
output stream.
interface java.util.Observer:
void flush()throws IOException
Flushes this buffered output stream.
void update(Observable o, Object arg)
This method is called whenever the observed object is changed.
void write(byte[] b, int off, int len) throws IOException
Writes len bytes from the specified byte array starting at offset off to this buffered
output stream.
Threads and timers
void write(int b) throws IOException
Writes the specified byte to this buffered output stream.
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
interface java.lang.Runnable:
void run()
When an object implementing interface Runnable is used to create a thread,
starting the thread causes the object's run method to be called in that separately
executing thread.
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
17 (26)
class java.lang.Thread:
Thread()
Allocates a new Thread object.
Thread(Runnable object)
Allocates a new Thread object.
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
18 (26)
void schedule(TimerTask task, long delay, long period)
Schedules the specified task for repeated fixed-delay execution,
beginning at the specified delay.
void cancel()
Terminates this timer, discarding any currently scheduled tasks.
class java.util.TimerTask:
void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method
of this thread.
protected TimerTask()
Creates a new timer task.
static void sleep(long millis) throws InterruptedException
Causes the currently executing thread to sleep for the specified number of milliseconds.
abstract void run()
The action to be performed by this timer task.
static boolean interrupted()
Tests whether the current thread has been interrupted.
boolean cancel()
Cancels this timer task.
void join()throws InterruptedException
Waits for this thread to die.
Communication
class javax.swing.Timer:
URL(String urlString) throws MalformedURLException
Creates a URL object from the String representation.
Timer(int delay, ActionListener listener)
Creates a Timer and initializes both the initial delay and between-event delay to delay
milliseconds.
void setDelay(int delay)
Sets the Timer's between-event delay, the number of milliseconds between successive
action events.
void setInitialDelay(int initialDelay)
Sets the Timer's initial delay, the time in milliseconds to wait after the timer is started
before firing the first event
void restart()
Restarts the Timer, canceling any pending firings and causing it to fire with its initial
delay.
void start()
Starts the Timer, causing it to start sending action events to its listeners.
void stop()
Stops the Timer, causing it to stop sending action events to its listeners.
class java.net.URL:
URLConnection openConnection() throws IOException
Returns a URLConnection object that represents a connection to the remote object
referred to by the URL.
class java.net.URLConnection:
InputStream getInputStream() throws IOException
Returns an input stream that reads from this open connection.
OutputStream getOutputStream() throws IOException
Returns an output stream that writes to this connection.
class java.net.InetAddress:
static InetAddress getByName(String host) throws
UnknownHostException
Determines the IP address of a host, given the host's name.
String getHostAddress()
Returns the IP address string in textual presentation.
class java.net.DatagramSocket:
class java.util.Timer:
DatagramSocket() throws SocketException
Constructs a datagram socket and binds it to any available port on the local host.
Timer()
Creates a new timer.
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
19 (26)
DatagramSocket(int port) throws SocketException
Constructs a datagram socket and binds it to the specified port on the local host.
void setSoTimeout(int timeout)
Enable socket timeout with the specified timeout, in milliseconds. A call to receive() for
this DatagramSocket will block for only this amount of time. If the timeout expires, a
java.net.SocketTimeoutException is raised, though the DatagramSocket is
still valid. The timeout must be > 0.
class java.net.MulticastSocket:
MulticastSocket() throws IOException
Create a multicast socket.
MulticastSocket(int port) throws IOException
Create a multicast socket and bind it to a specific port.
void joinGroup(InetAddress mcastaddr) throws IOException
Join a multicast group.
void leaveGroup(InetAddress mcastaddr) throws IOException
Leave a multicast group.
DatagramSocket
void setSoTimeout(int timeout) throws SocketException
Enable/disable socket timeout with the timeout specified in milliseconds.
DatagramSocket och MulticastSocket
void send(DatagramPacket p) throws IOException
Sends a datagram packet from this socket.
void receive(DatagramPacket p) throws IOException
Receives a datagram packet from this socket.
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
class java.net.Socket:
Socket(InetAddress address, int port)
Creates a stream socket and connects it to the specified port number at the specified
IP address.
InputStream getInputStream() throws IOException
Returns an input stream for this socket.
OutputStream getOutputStream() throws IOException
Returns an output stream for this socket.
InetAddress getInetAddress()
Returns the address to which this socket is connected.
void setSoTimeout(int timeout) throws SocketException
Enable socket timeout with the specified timeout, in milliseconds (see DatagramSocket)
void close() throws IOException
Closes this socket.
boolean isClosed()
Returns the closed state of this socket.
class java.net.DatagramPacket:
DatagramPacket(byte[] buf, int length)
Constructs a DatagramPacket for receiving packets of length length.
DatagramPacket(byte[] buf, int length, InetAddress address,
int port)
Constructs a datagram packet for sending packets of length length to the specified
port number on the specified host.
class java.net.ServerSocket:
byte[] getData()
Returns the data buffer.
ServerSocket(int port) throws IOException
Creates a server socket, bound to the specified port.
int getLength()
Returns the length of the data to be sent or the length of the data received.
Socket accept() throws IOException
Listens for a connection to be made to this socket and accepts it.
InetAddress getAddress()
Returns the IP address of the machine to which this datagram is being sent
or from which the datagram was received.
void setSoTimeout(int timeout) throws SocketException
Enable socket timeout with the specified timeout, in milliseconds (see DatagramSocket)
void close() throws IOException
Closes this socket.
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
20 (26)
int getPort()
Returns the port number on the remote host to which this datagram is being sent
or from which the datagram was received.
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
21 (26)
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
Component add(Component comp)
Appends the specified component to the end of this container.
Reflection
class java.lang.Class:
static Class forName(String className) throws
ClassNotFoundException
Returns the Class object associated with the class or interface with the given name.
Object newInstance() throws InstantiationException
Creates a new instance of the class represented by this Class object.
Method getMethod(String name, Class[] parameterTypes)
throws NoSuchMethodException
Returns a Method object that reflects the specified public member method of the class
or interface represented by this Class object. If the method has zero parameters,
parameterTypes should be null.
String getName()
Returns the name of the entity (class, interface, array class, primitive type, or void)
represented by this Class object, as a String.
void setVisible(boolean b)
Shows or hides this frame depending on the value of parameter b.
class javax.swing.JMenuBar:
JMenuBar()
Creates a new menu bar.
JMenu add(JMenu c)
Appends the specified menu to the end of the menu bar.
class javax.swing.JMenu:
JMenu(String s)
Constructs a new JMenu with the supplied string as its text.
JMenuItem add(JMenuItem menuItem)
Appends a menu item to the end of this menu.
class java.lang.reflect.Method:
class javax.swing.JMenuItem:
Object invoke(Object obj, Object[] args)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
Invokes the underlying method represented by this Method object, on the specified
object with the specified parameters. If the method expects zero arguments, args
should be null.
JMenuItem(String text)
Creates a JMenuItem with the specified text.
GUI
void addActionListener(ActionListener l)
Adds an ActionListener to this menu item.
class javax.swing.JPanel:
class javax.swing.JFrame:
JPanel(LayoutManager layout)
Create a new JPanel with the specified layout manager.
JFrame()
Constructs a new frame that is initially invisible.
Component add(Component comp)
Appends the specified component to this container.
Container getContentPane()
Returns the contentPane object for this frame.
class javax.swing.JLabel:
void setTitle(String title)
Sets the title for this frame to the specified string.
void setJMenuBar(JMenuBar menubar)
Sets the menubar for this frame.
void setLayout(LayoutManager manager)
Sets the LayoutManager.
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
JLabel(String text)
Creates a JLabel instance with the specified text.
void setText(String text)
Defines the single line of text this component will display.
String getText()
Returns the label's text.
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
22 (26)
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
class javax.swing.JButton:
23 (26)
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
void setEditable(boolean b)
Sets whether or not this TextComponent should be editable.
JButton(String text)
Creates a JButton instance with the specified text.
interface java.awt.event.ActionListener:
void setText(String text)
Defines the single line of text this component will display.
void actionPerformed(ActionEvent e)
Invoked when an action occurs.
String getText()
Returns the button's text.
class java.awt.event.ActionEvent:
String getActionCommand()
Returns the command string associated with this action.
void setIcon(Icon icon)
Sets the button's default icon.
void setEnabled(boolean b)
Enables (or disables) the button.
Object getSource()
Returns the object on which the event occurred.
interface java.awt.event.KeyListener:
addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this button.
void keyReleased(KeyEvent e)
Invoked when a key has been released.
class javax.swing.JTextField:
class java.awt.event.KeyEvent:
String getText()
Returns the text contained in this textfield.
void setText(String t)
Sets the text of this textfield to the specified text.
void setEditable(boolean b)
Sets whether or not this TextComponent should be editable.
void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this textfield.
void addKeyListener(KeyListener l)
Adds the specified key listener to receive key events from this textfield.
class javax.swing.JTextArea:
JTextArea(int rows, int columns)
Constructs a new empty TextArea with the specified number of rows and columns.
void append(String str)
Appends the given text to the end of the document.
String getText()
Returns the text contained in this textfield.
Object getSource()
The object on which the Event initially occurred.
char getKeyChar()
Returns the character associated with the key in this event.
Layout managers
All layout manager classes implement the interface java.awt.LayoutManager
class java.awt.BorderLayout:
BorderLayout(int hgap, int vgap)
Constructs a border layout with the specified gaps between components.
Fields:
public static final String CENTER
The center layout constraint (middle of container).
public static final String EAST
The east layout constraint (right side of container).
public static final String WEST
The west layout constraint (left side of container).
public static final String NORTH
The north layout constraint (top of container).
public static final String SOUTH
The south layout constraint (bottom of container).
void setText(String t)
Sets the text of this textarea to the specified text. Empties the area if t is null.
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
24 (26)
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
Tentamenshjälpmedel
25 (26)
class java.awt.BoxLayout:
BoxLayout(Container target, int axis)
Creates a layout manager that will lay out components along the given axis.
Parameters:
target - the container that needs to be laid out
axis - the axis to lay out components along. Can be one of: BoxLayout.X_AXIS or
BoxLayout.Y_AXIS
class java.awt.FlowLayout:
FlowLayout(int align, int hgap, int vgap)
Creates a new flow layout manager with the indicated alignment and the indicated
horizontal and vertical gaps. The value of the alignment argument must be one of
FlowLayout.LEFT, FlowLayout.RIGHT, or FlowLayout.CENTER.
CHALMERS
Institutionen för data- och informationsteknik
Uno Holmer
holmer ’at’ chalmers.se
public
public
public
public
public
static
static
static
static
static
final
final
final
final
final
int
int
int
int
int
Tentamenshjälpmedel
OK_CANCEL_OPTION
YES_OPTION
NO_OPTION
CANCEL_OPTION
OK_OPTION
return values:
public static final int YES_OPTION
Return value from class method
if YES is chosen.
public static final int NO_OPTION
Return value from class method
if NO is chosen.
public static final int CANCEL_OPTION Return value from class method
if CANCEL is chosen.
public static final int OK_OPTION
Return value from class method
if OK is chosen.
class java.awt.GridLayout:
class org.junit.Assert:
GridLayout(int rows, int cols, int hgap, int vgap)
Creates a grid layout with the specified number of rows, columns, horizontal and vertical
gaps. All components in the layout are given equal size.
static void assertEquals(long expected,long actual)
Asserts that two longs are equal.
Popup dialogues
static void assertNotEquals(long expected,long actual)
Asserts that two longs are not equals.
class javax.swing.JOptionPane:
static void showMessageDialog(Component parentComponent,
Object message, String title, int messageType)
Brings up a dialog that displays a message using a default icon determined by
the messageType parameter.
static String showInputDialog(Object message)
Shows a question-message dialog requesting input from the user.
static int showConfirmDialog(Component parentComponent,
Object message, String title, int optionType,
int messageType)
Brings up a dialog, where the number of choices is determined by the optionType
parameter.
static void assertNotEquals(Object expected,Object actual)
Asserts that two objects are not equals.
static void assertSame(long expected,long actual)
Asserts that two references refer to the same object.
static void assertNotSame(long expected,long actual)
Asserts that two references do not refer to the same object.
static void assertTrue(boolean condition)
Asserts that a condition is true.
static void assertFalse(boolean condition)
Asserts that a condition is false.
static void assertNull(Object object)
Asserts that an object is null.
static void assertNotNull(Object object)
Asserts that an object isn’t null.
message types
static
static
static
static
static void assertEquals(Object expected,Object actual)
Asserts that two objects are equal.
int ERROR_MESSAGE
int INFORMATION_MESSAGE
int QUESTION_MESSAGE
int WARNING_MESSAGE
Used for error messages.
Used for information messages.
Used for questions.
Used for warning messages.
Junit Annotation types:
@Before, @After, @Test
option types used for showConfirmDialog:
public static final int YES_NO_OPTION
public static final int YES_NO_CANCEL_OPTION
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
Version: 2017-03-14
Objektorienterade applikationer 2016/2017
26 (26)