| Java 2 Basics > The java.lang and java.util Packages | Index - Previous - Next |
The object class is the ultimate ancestor of all Java classes. If a class does not contain the extends keyword in its declaration, the compiler builds a class that extends directly from Object. You should pay attention to some methods that are inherited by every class:
Allows to compare two objects. Strings for example, may be compared using this method. If you create your own objects, you should also override this method in order to supply your own equality alogirthm.
The purpose of the toString() method is to provide a string representation of an object's state.
This class contains a collection of methods and two constants that support mathematical computation. Some important information about the Math Class:
They are declared to be public, static, final, and double.
Returns the absolute value of i: abs(-5) = 5 abs(5) = 5 Other methods: long abs(long l), float abs(float f), double abs(double d)
Returns the smallest integer that is not less than d. ceil(4.00001) = 5.0 ceil(4.99999) = 5.0 ceil(-4.00001) = -4.0 ceil(-4.99999) = -4.0
Returns the largest integer that is not greater than d. floor(4.00001) = 4.0 floor(4.99999) = 4.0 floor(-4.00001) = -5.0 floor(-4.99999) = -5.0 Other methods: double floor(double d)
Returns the greater of i1 and i2 max(1,3) = 3 Other methods: long max(long l1, long l2), float max(float f1, float f2), double max(double d1, double d2).
Returns the smaller of i1 and i2 min(1,3) = 1 Other methods: long min(long l1, long l2), float min(float f1, float f2), double min(double d1, double d2).
Returns a random number equal or greater than 0 but lower than 1.0 random() = 0.012288873641244202 random() = 0.8962267714328847 ...
Returns the closest int to f. round(4.00001) = 4 round(4.49999) = 4 round(4.5) = 5 round(4.99999) = 5 round(-4.5) = -4 round(-4.40001) = -5 Other method: long round(double d)
Returns the sine of d
Returns the cosine of d
Returns the tangent of d
Returns the square root of d
Each Java primitive data type has a corresponding wrapper class. A wrapper class is simply a class that encapsulates a single, immutable value.
Primitive Data Type Wrapper Class boolean Boolean byte Byte char Character short Short int Integer long Long float Float double Double
All wrapper classes can be constructed by passing the value to be wrapped into the appropiate constructor.
int a = 567;
Integer i = new Integer(a);
Character c = new Character('Z');
There is another way to construct classes, with the exception of Character. You can pass into the constructor a string that represents the value to be wrapped. Most of these constructors throw NumberFormatException, because there is always the possibility that the string will not represent a valid value. Only Boolean does not throw this exception.
Boolean wboolean = new Boolean("true");
try {
Byte wbyte = new Byte("124");
Short wshort = new Short("25943");
Integer wint = new Integer("532342");
Long wlong = new Long("78888900000");
Float wfloat = new Float("5.4f");
Double wdouble = new Double("1.1000004");
} catch (NumberFormatException e) { }
The value of any wrapped number can be retrieved as any numeric type. Each class has a method to do that:
The wrapper classes are useful whenever it would be convenient to treat a piece of primitive data as if it were an object.
Java uses 16-bits Unicode characters rather than 8-bits byte characters.
The String class contains an immutable string. Once an instance is created, the string it contains cannot be changed.
String s1 = new String("Hello World");
String s2 = new String("Hello World");
String s3 = "Hello World";
String s4 = "Hello World";
As strings cannot be changed, when construction strings using plain literals, the equal strings are stored only once because the compiler assumes they are constants. So (s3 == s4) is true, because the string "Hello World" is stored at the same JVM address. The first variables should be tested using the standard equals() method: (s1.equals(s2)) = true
Returns the indexed character of a string, where the index of the initial character is 0 "Ernest".charAt(2) = 'n'
This returns a new string consisting of the old string followed by addThis
"Ernest".concat(" Garbarino") = "Ernesto Garbarino"
This performs a lexical comparison, it returns an int that is:
· less than 0: if the current string is less than otherString.
· equal to 0: if the strings are identical.
· greatar than 0: if the current string is greater than otherString.
"Ernest".compareTo("Ricardo") = -13
"Ernest".compareTo("Ernest") = 0
"Ernest".compareTo("Felix") = -1
This returns true if the current string ends with suffix; otherwise it returns false.
"Ernest".endsWith("est") = true
"Ernest".endsWith("lix") = false
This returns true if ob instanceof String and the string encapsulated
by ob matches the string encapsulated by the executing object.
"Ernest".equals(new String("Ernest")) = true
"Ernest".equals(new String("ERNEST")) = false
This is like equals(), but the argument is a String and the comparision ignores case.
"Ernest".equalsIgnoreCase("Ernest") = true
"Ernest".equalsIgnoreCase("ERNEST") = true
This returns the index within the current string of the first occurence of ch.
Alternative forms return the index of a string and begin searching
from a specified offset.
"Garbarino".indexOf('a') = 1
This returns the index within the current string of the last ocurrence of ch.
Alternative forms return the index of a string and end searching at a
specified offset from the end of the string.
"Garbarino".indexOf('a') = 4
This returns the number of characters in the current string. "Ernest".length() = 6
This returns a new string, generated by replacing every occurence of oldChar
with newChar
"Garbarino".replace('a','e') = "Gerberino"
This returns true if the current string begins with prefix; otherwise
it returns false. Alternate forms begin searching from a specified offset.
"Ernest".startsWith("Ern") = true
"Ernest".startsWith("est") = false
This returns the substring, beginning at startIndex of the current string and extending to the end of the current string. An alternate form specifies starting and ending offsets. "Ernest".substring(2) = "nest"
This converts the executing object to lowercase and returns a new string. "Ernest".toLowerCase() = "ernest"
This converts the executing object to uppercase and returns a new string. "Ernest".toUpperCase() = "ERNEST"
This returns the executing object. "Ernest".toString() = "Ernest"
This returns the string that results from removing whitespace characters from the beginning and ending of the current string. " Ernest ".trim() = "Ernest"
A instance of Java's StringBuffer class represents a string that can be dynamically modified. The most commonly used constructor takes a String instance as input. You can also construct an empty string buffer.
This constructs an empty string buffer
This constructs an empty string buffer with the specified initial capacity. You may eventually set an initial capacity just to aviod memory re-allocation each time that the StringBuffer grows.
This constructs a string buffer that initially contains the specified string.
This appends str to the current string buffer. Alternative forms support
appending primitives and character arrays; these are converted to strings
before appending.
new StringBuffer("Ernesto ").append("Garbarino") = "Ernesto Garbarino"
char[] word = {'h','e','l','l','o'};
new StringBuffer().append(word) = "hello"
This calls toString() on obj and appends the result to the current string buffer.
This inserts str into the current string buffer at position offset.
There are numerous alternative forms.
new StringBuffer("Ernest").insert(3,"hi") = "Ernhiest"
This reverses the characters of the current string buffer.
new StringBuffer("Ernest").reverse() = "tsenrE"
This replaces the character at position offset with newChar
StringBuffer sb = new StringBuffer("Ernest");
sb.setCharAt(1,'l');
sb = "Elnest"
This sets the length of the string buffer to newLength. If newLength is less
than the current length, the string is truncated. If newLength is greater
than the current length, the string is padded with null characters.
StringBuffer sb = new StringBuffer("Ernest");
sb.setLength(3);
sb = "Ern"
The Collections API is a mechanism for manipulating object references. While arrays are capable of storing primitives or references, collections are not. To work with Collections using your own objects, you should:
Collections impose no order, nor restrictions, on content duplication.
Let's see the most common collection storage approaches now:
Tends to be fast to access, but it is relatively inefficient as the number of elements in the collections grows or if elements need to be inserted or deleted in the middle of the set.
Alows elements to be added to, or removed from, the collection at any location in the container, and allows the size of the collection to grow arbitrarily without the penalities associated with array copying. Indexed access is slower.
Allows easy addition and deletion of elements and arbitrary growth of the collection. Unlike a list, trees insist on a means of ordering. Indexed access is slow, but searching is faster.
It requires that some unique identifying key can be associated with each data iten, which in turn provides efficient searching. Indexed access is slow, but searching is particulary fast.
These two classes are very similar, using hashbased storage to implement a map. Hashtable does not allow the null value to be stored.
This is a set, so it does not permit duplicates and it uses hashing for storage
This is an implementation of a list, based on a linked-list storage.
This class provides an ordered map. The elements must be orderable, either by implementing the Comparable interface or by providing a Comparator class to perform the comparisions.
This class provides an ordered set, using a tree for storage. As with the TreeMap, the elements must have an order associated with them.
This class implements a list using an array internally for storage. The array is dynamically reallocated as necessary, as the number of items in the vector grows.
| © Ernesto Garbarino | Top |