GARBA.ORG
Java 2 Basics > The java.lang and java.util Packages Index - Previous - Next

The java.lang and java.util Packages

The Object Class

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:

equals()

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.

toString()

The purpose of the toString() method is to provide a string representation of an object's state.

The Math Class

This class contains a collection of methods and two constants that support mathematical computation. Some important information about the Math Class:

Math constants

They are declared to be public, static, final, and double.

Methods of the Math Class

int abs(int i)

	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)

double ceil(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

double floor(double d)

	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) 

int max(int i1, int i2)

	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). 

int min(int i1, int i2)

	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). 

double random()

	Returns a random number equal or greater than 0 but lower than 1.0

		random() = 0.012288873641244202
		random() = 0.8962267714328847
		...

int round(float f)

	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) 

double sin(double d)

	Returns the sine of d

double cos(double d)

	Returns the cosine of d

double tan(double d)

	Returns the tangent of d

double sqrt(double d)

	Returns the square root of d

The Wrapper Classes

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

Constructing instances of wrapper types

All wrapper classes can be constructed by passing the value to be wrapped into the appropiate constructor.

Examples:

	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.

Example:

	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) { }

Getting values that have been wrapped

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.

Summary:

Strings

Java uses 16-bits Unicode characters rather than 8-bits byte characters.

The String class

The String class contains an immutable string. Once an instance is created, the string it contains cannot be changed.

Construction:

	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

Most useful String methods

char charAt(int index)

	Returns the indexed character of a string, where the index of the initial character is 0

		"Ernest".charAt(2) = 'n'

String concat(String addThis)

	This returns a new string consisting of the old string followed by addThis

		"Ernest".concat(" Garbarino") = "Ernesto Garbarino"

int compareTo(String otherString)

	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

boolean endsWith(String suffix)

	This returns true if the current string ends with suffix; otherwise it returns false. 

		"Ernest".endsWith("est") = true
		"Ernest".endsWith("lix") = false

boolean equals(Object ob)

	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

boolean equalsIgnoreCase(String s)

	This is like equals(), but the argument is a String and the comparision ignores case. 

		"Ernest".equalsIgnoreCase("Ernest") = true
		"Ernest".equalsIgnoreCase("ERNEST") = true

int indexOf(int ch)

	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

int lastIndexOf(int ch)

	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

int length()

	This returns the number of characters in the current string.

		"Ernest".length() = 6

replace(char oldChar, char newChar)

	This returns a new string, generated by replacing every occurence of oldChar
	with newChar

		"Garbarino".replace('a','e') = "Gerberino"

boolean startsWith(String prefix)

	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

String substring(int startIndex)

	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"

String toLowerCase()

	This converts the executing object to lowercase and returns a new string.

		"Ernest".toLowerCase() = "ernest"

String toUpperCase()

	This converts the executing object to uppercase and returns a new string.

		"Ernest".toUpperCase() = "ERNEST"

String toString()

	This returns the executing object.

		"Ernest".toString() = "Ernest"

String trim()

	This returns the string that results from removing whitespace characters
	from the beginning and ending of the current string.

		"   Ernest ".trim() = "Ernest"

The StringBuffer Class

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.

StringBuffer constructors

StringBuffer()

This constructs an empty string buffer

StringBuffer(int capacity)

	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.

StringBuffer(String initialString)

	This constructs a string buffer that initially contains the specified string.

Most useful StringBuffer methods

StringBuffer append(String str)

	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"

StringBuffer append(Object obj)

	This calls toString() on obj and appends the result to the current string buffer.

StringBuffer insert(int offset, String str)

	This inserts str into the current string buffer at position offset. 
	There are numerous alternative forms.

		new StringBuffer("Ernest").insert(3,"hi") = "Ernhiest"

StringBuffer reverse()

	This reverses the characters of the current string buffer.

		new StringBuffer("Ernest").reverse() = "tsenrE" 

void setCharAt(int offset, char newChar)

	This replaces the character at position offset with newChar

		StringBuffer sb = new StringBuffer("Ernest");
		sb.setCharAt(1,'l');

		sb = "Elnest"

void setLength(int newLength)

	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

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.

Some concepts:

Let's see the most common collection storage approaches now:

Array storage

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.

A linked list

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.

A tree

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.

A hash table

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.

Collection Implementations in the API

HashMap/Hashtable

These two classes are very similar, using hashbased storage to implement a map. Hashtable does not allow the null value to be stored.

HashSet

This is a set, so it does not permit duplicates and it uses hashing for storage

LinkedList

This is an implementation of a list, based on a linked-list storage.

TreeMap

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.

TreeSet

This class provides an ordered set, using a tree for storage. As with the TreeMap, the elements must have an order associated with them.

Vector

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