To Documents
Some Java Classes and Methods
- A method is a procedure (also called a function or
subroutine) that can be called to perform a computation
or other action.
- A method can be called from an object (instance method) or from a class (static method).
- Here are some classes in the Java Class Library with their commonly used methods.
- The definitive reference for classes is
the Java 11 Class Library Documentation.
String Class
A String object consists of a sequence of unicode characters of type char. The list of char characters includes every character
on a standard keyboard, but it also includes characters from all commonly used alphabets, modern and ancient.
Because the maximum size of a char variable is 2 bytes, Java cannot handle the
newer 4 byte Unicode characters. An important property of String objects
is that they are immutable (cannot be changed).
Constructors
- new String( ) Create a null string object "".
- new String(existingStr) Create copy of existing string.
- new String(char[ ] charArray) Create string out of char array.
- new String(char[ ] charArray, int offset, int count) Create string out of char array starting
at index offset and of length count.
- new String(StringBuilder sbObj) Create string from a StringBuilder object.
Methods
- str.charAt(pos) Return character at position pos in string str.
- str.compareTo(otherStr) Return a positive int if str precedes otherStr in dictionary order, return a negative int if otherStr
comes after otherStr, return 0 if str and otherStr consist of the same characters. Note: the >, <, and == operators cannot be used on String objects.
- str.compareToIgnoreCase(otherStr) Same as str.compare to, except the cases of letters in the strings is ignored.
- str.endsWith(suffix) Return true if str ends with suffix.
- String.format(formatString, arg0, arg1, arg2) Format the arguments arg0, arg1, and arg2 according to the format string.
- str.equals(otherStr) Return true if str has the same letters as otherStr.
- str.indexOf(substring) If substring is found in str, return the start index of the leftmost substring. If substring is not found
in str, return -1.
- str.lastIndexOf(substring) If substring is found in str, return the start index of the rightmost substring. If substring is not found
in str, return -1.
- str.length( ) Return the number of characters in str.
- str.replace(oldChar, newChar) Return the string with each instance of oldChar replaced with newChar in str.
- str.split(delim) Return the String array of fields obtained from str using the delim delimiter.
- str.startsWith(suffix) Return true if str starts with prefix.
- str.toString( ) Returns str as a string (which does nothing because str is already a string).
For compatibility with other classes.
- str.toLowerCase( ) Return str where the letters are converted to lower case.
- str.toUpperCase( ) Return str where the letters are converted to upper case.
- str.trim( ) Return str with leading and trailing blanks removed.
- String.valueOf(obj) Return the object obj as a string.
StringBuilder Class
Because String objects are immutable, making frequent changes to string objects
can be time consuming because an entirely new String object must be created each
time that a change is made. A faster alternative is to use mutable
StringBuilder objects to manage strings which change frequently.
Constructors
- new StringBuilder( ) Create a StringBuilder object with no characters, but with a capacity of 16.
- new StringBuilder(capacity) Create a StringBuilder object with no characters, but with a capacity of 16.
- new StringBuilder(str) Create a StringBuilder object with the characters in str. The initial capacity is
16 + str.length( ).
Methods
- strb.append(obj) Return the string representation of the object obj to the end of the StringBuilder characters.
- strb.capacity( ) Return current capacity of StringBuilder object strb.
- strb.ensureCapacity(minCap) If current capacity of StringBuilder object is less than minCap, set current capacity to minCap.
- strb.insert(pos, obj) Insert string representation of obj immediately before the character at index pos. Use append to add obj at the end.
- strb.setCharAt(pos, chr) Change character at index pos to chr.
- The String methods charAt,
indexOf, lastIndexOf,
length, replace,
substring, and toString also work for
StringBuilder objects.
Integer Class
The Integer class is a wrapper class containing int values. Wrapper
classes also exist for each of the other primitive types: Byte, Short, Long,
Float, Double, Character, and Boolean.
Constructors
- new Integer(int value) Create an Integer object that contains the specified int value.
- new Integer(String value) Create an Integer object that contains the specified string value. A NumberFormatException will
be raised if the string value cannot be converted into an integer.
Methods
- Integer.bitCount(intValue) Return number of bits in the binary representation of the intValue.
- intObj.byteValue( ), intObj.shortValue( ), intObj.intValue( ), intObj.longValue( ),
intObj.floatValue( ), intObj.doubleValue( ) Return intObj as the specified datatype.
- intObj.toBinaryString( ), intObj.toHexString( ), intObj.toOctalString( ), intObj.toString( )
Return intObj as a string of the specified base. toString returns intObj as a decimal string.
- Integer.parseInt(intStr) Convert a string to an int.
-
Static Fields
- Integer.MAX_VALUE The maximum value of the int datatype,
which is 231 - 1 = 2,147,483,647.
- Integer.MIN_VALUE The maximum value of the int datatype,
which is -231 = -2,147,483,648.
- Integer.SIZE The number of bits needed to store an int value, which is 32.
Object Class
The object class is the parent class of all Java classes. Object methods
can be overridden in derived classes.
Object Constructor
Object Methods
- obj.Clone( ) Creates and returns a copy of obj.
- obj.equals(otherObj) Returns true if obj is equal to otherObj, false otherwise.
- obj.finalize( ) Called when the garbage collector reclaims an object that has become garbage.
- obj.getClass( ) Returns an object of type Class that contains information about the type of obj.
- obj.getHashCode( ) Returns a hashcode for the object obj.
- obj.toString( ) Returns a string that represents the information in obj.
ArrayList Class
import java.util.ArrayList;
Constructors
- new ArrayList<T>( ) Create a new ArrayList object that contains objects of T type.
- new ArrayList<T>(int size) Create a new ArrayList object with capacity size.
Methods
- arrayList.add(T obj) Add the object of type T to the top of the arrayList object.
- arrayList.add(int index, T obj) Inserts the specified element at the specified index position in this list.
- arrayList.clear( ) Clear all elements from the list.
- arrayList.contains(T obj) Returns true of the list contains the object obj.
- arrayList.get(int index) Returns the object at the specified index.
- arrayList.indexOf(T obj) Returns the index of the first occurrence of the object obj in the list. Returns
-1 if obj is not found in the list.
- arrayList.isEmpty( ) Returns true if the list contains no objects.
- arrayList.lastIndexOf(T obj) Returns the index of the last occurrence of the object obj in the list. Returns
-1 of obj is not found in the list.
- arrayList.remove(int index) Removes the object at the specified index from the list.
- arrayList.remove(T obj) Removes the first occurrence of obj from the list.
- arrayList.set(int index, T obj) Sets the element of the specified index to the object obj.
- arrayList.size( ) Returns the number of objects in the list.
Scanner Class
import java.util.Scanner;
Constructors
- new Scanner(System.in) Create a new Scanner object from the BufferedInputStream object System.in.
- new Scanner(new File(filePath)) Create Scanner object that reads from disk file. Enclosing method must throw FileNotFoundException.
- new Scanner(inputString) Create Scanner that reads from input string.
Methods
- scanner.hasNext( ) Returns true if scanner has another token to return. Return false if at end of input.
- scanner.nextLine( ) Return next input line. Return null if at end of file.
- scanner.next( ) Return next character from input.
- scanner.close( ) Close the scanner.
Random Class
import java.util.Random;
Constructors
- new Random( ) Create a new Random object.
- new Random(seed long) Create a new Random object.
Methods
- scanner.nextBoolean(int n) Return true or false with probability 0.5 each.
- scanner.nextDouble( ) Return a random double in the range [0.0, 0.1).
- scanner.nextInt(int n) Return a random int in the range [0, n-1].
Color Class
The Color class is used to create colors for drawing with the Graphics class (described below).
import java.awt.Color;
Constructors
- new Color(r, g, b) Create a new Color object with specified rgb components.
- new Color(r, g, b, a) Create a new Color object with specified rgb and alpha (transparency) components.
Methods
- col.getAlpha( ) Return alpha component.
- col.getBlue( ) Return blue component.
- col.getGreen( ) Return green component.
- col.getRed( ) Return red component.
- col.lighter( ) Return a Color object that represents a lighter color than col.
- col.darker( ) Return a Color object that represents a darker color than col.
Static Fields
- Color class color names using lower Camel notation: Color.black Color.blue Color.cyan Color.darkGray Color.gray Color.green
Color.lightGray Color.magenta Color.orange Color.pink Color.red Color.white Color.yellow
- Color class color names using upper case constant notation: Color.BLACK Color.BLUE Color.CYAN Color.DARK_GRAY Color.GRAY Color.GREEN
Color.LIGHT_GRAY Color. MAGENTA Color.ORANGE Color.PINK Color.RED Color.WHITE Color.YELLOW
Font Class
The Font class is used to specify fonts for drawing strings with the Graphics class (described below).
import java.awt.Font;
Constructors
- new Font(fontName, fontStyle, fontSize) Create a new Font object with specified characteristics.
Methods
- font.getFamily( ) Return font family of font.
- font.getSize( ) Return size of font.
- font.getStyle( ) Return style of font.
- font.isBold( ) Return true if style of font is bold, false otherwise.
- font.isItalic( ) Return true if style of font is italic, false otherwise.
- font.isPlain( ) Return true if style of font is plain, false otherwise.
Static Fields
- Font.BOLD Specifies plain (neither bold not italic) style for font. Stored as bitmap 00.
- Font.BOLD Specifies bold style for font. Stored as bitmap 01.
- Font.ITALIC Specifies bold style for font. Stored as bitmap 10.
- Font.BOLD | Font.ITALIC Specifies bold and italic styles for font.
Stored as bitwise or of 01 and 10.
-
Graphics Class
The Graphic class is used to draw in an Applet or Component. Usually the
Graphics constructor is not explicitly used; the Graphics context is created in
the Applet or Component environment. The origin (0, 0) is in the upper left corner
of the drawing region.
import java.awt.Graphics;
Constructors
- new Graphics( ) Create new Graphics object.
Methods
- g.getColor(c) Get current color.
- g.setFont(c) Set the current font.
- g.setColor(c) Set the current color.
- g.setFont(c) Set the current font.
- g.drawLine(startX, startY, endX, endY) Draw line from (startX, startY) to (endX, endY).
- g.drawRect(x, y, width, height) Draw rectangle with (x, y) as upper left corner and given width and height.
- g.FillRect(x, y, width, height) Fill rectangle with (x, y) as upper left corner and given width and height.
- g.drawOval(x, y, width, height) Draw oval (actually ellipse) using bounding rectangle with (x, y) as upper left corner and given width and height
as the bounding box.
- g.FillOval(x, y, width, height) Fill oval (actually ellipse) using bounding rectangle with (x, y) as upper left corner and given width and height
as the bounding box.
- g.drawArc(x, y, width, height) Draw elliptical arc using bounding rectangle with (x, y) as upper left corner and given width and height
as the bounding box. Draw the arc from the start to the end angle.
- g.FillArc(x, y, width, height) Fill elliptical arc using bounding rectangle with (x, y) as upper left corner and given width and height
as the bounding box. Draw the arc from the start to the end angle.
- g.drawPolygon(xArray, yArray, nPoints) Draw polygon using x-coordinates specified by xArray and y-coordinates specified by yArray. Connect
last point back to first point.
- g.FillPolygon(xArray, yArray, nPoints) Fill polygon using x-coordinates specified by xArray and y-coordinates specified by yArray. Connect
last point back to first point.
- g.drawPolyline(xArray, yArray, nPoints) Same as draw polygon except that last point is not connected back to first point.
- g.drawString(str, xPos, yPos) Draw String str so that the upper left corner of the string is at (xPos, yPos).