Java.lang Package

This web page focuses on the following

String Class

Once a string object is created it can never be changed, string objects are immutable objects. String objects are create using the new keyword, the String class has many constructors.

String example

String s = new String();
s = "Using the new keyword";

String s = new String("Using a one liner");

String s = "Using the shorthand version";

As i stated above String objects can never be changed, what happens when you appear to change a string object is that a new string object is created and the string variable points to the new string object, the old string object is deposed of by the garbage collector.

String example

String s = "This is a new string";

s = s.concat("you are not supposed to be able to change this");

Note: what happens is the following

  1. A new string object is created using the original string with the concatenation
  2. the string variable s now points to the new string object
  3. the old string object is removed by the garbage collector as long as nothing else is attached to it.

Strings and Memory

To make Java more efficient the JVM sets aside a special area of memory called the "String constant pool", When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new String is directed to the existing String and no new String object is created (The existing String simply has an additional reference). To stop stop any problems in the String pool, the String class is marked final nobody can override the behaviors of any of the String methods, so you can be assured that the String objects you are counting on to be immutable will in fact be immutable.

String Methods

Here are some of the more commonly used String methods


String x = "Hello World!";
System.out.println("Character 3 in String x is " + x.charAt(2));

Note: The charAt returns the character at a specific index, remember we start at zero


String t = "Hello";
String t1 = "World";
String t2 = t;

System.out.println( t + " compareTo " + t2 + " results in " + t.compareTo(t2));   // results in 0 (match)
System.out.println( t + " compareTo " + t1 + " results in " + t.compareTo(t1));   // results in -15

Note: a reult of zero means that they are equal, a negative values means it is less than the string passed, and a positive values means it is more than the value passed


String x = "Taxi";

System.out.println( x.concat(" cab");
System.out.println("Original String x has now been changed : " + x);

Note: concat method does not update x as there was no assignment


String x = "hello";

if ( x.equalsIgnoreCase("hello")
   System.out.prinln("String x is equal to Hello, hello, etc");

Note: see equals for more information on this method


String x = "hello";

if ( x.equalsIgnoreCase("Hello")
   System.out.prinln("String x is equal to Hello, hello, etc");

Note: the equalsIgnoreCase returns true if the value is the same as the argument passed, otherwise false


# getChars(int srcBegin, int srcEnd, char[] dest, int destBegin)

String h = "Hello World";
char[] ca = new char[5];

h.getChars(0, 5, ca, 0);

indexOf and lastIndexOf String s1 = "abcdefghijklmabcdefghijklm";

System.out.println("String is: " + s1 + "\n");

System.out.println("first c is found @ position: " + s1.indexOf('c') );
System.out.println("fgh is found @ position: " + s1.indexOf("fgh") );
System.out.println("fgh is found @ position (skip first 7 characters): " + s1.indexOf("fgh", 7) );

System.out.println("unknown $ is not found: " + s1.indexOf('$') );

System.out.println("last c is found @ position: " + s1.lastIndexOf('c') );

String t1 = "abcdefghiklmnopqrstuvwxyz";
String t2;

t2 = t1.intern();   // see note below

if ( t1 == t2)
   System.out.println("t1 and t2 are the same object");

if ( t1.equals(t2) )
   System.out.println("t1 and t2 have the same contents");

Note: a lookup is performed


String x = "this is a very long string that hopefully will have a total of 76 characters";

System.out.println("String x has " + x.length() + " Character");

Note: return the length of a String (includes whitespace)

regionMatches # regionMatches(start offset, string, start offset of the subregion, number of characters to compare)
# regionMatches(ignore case, start offset, string, start offset of the subregion, number of characters to compare)

String t = "Hello";
String match = "hello";

if ( t.regionMatches(0, match, 0, 5) )
   System.out.println("A perfect match");
   System.out.println("Not a perfect match");

if ( t.regionMatches(true, 0, match, 0, 5) )
   System.out.println("A perfect match");
   System.out.println("Not a perfect match");

String x = "XXaXX";

System.out.println("String before: " + x);
System.out.println("String replaced: " + x.replace('X','x'));


String x = "1234567890";

System.out.println("Part of String x: " + x.substring(5));    // start from position 5 return rest of string
System.out.println("Part of String x: " + x.substring(5,8));  // start from position 5 return upto character 8

Note: used to return part of a string

toLowerCase toUpperCase

String lower = "all lower case";
String upper = "ALL UPPER CASE";

System.out.println("String lower is now upper case: " + lower.toUpperCase());
System.out.println("String upper is now lower case: " + upper.toLowerCase());


String x = "Hello World!";

System.out.println("toString method returns: " + x.toString());

Note: all objects in Java have a toString method, normally returns a meaningful way to describe the object


String x = "     x     ";

System.out.println("Blank spaces removed from x: " + x.trim());

Note: trim removes any leading or trailing blank spaces

valueOf int i = 20;
boolean b = true;
double d = 100.20;

System.out.println("integer string is: " + String.valueOf(i) );
System.out.println("boolean string is: " + String.valueOf(b) );
System.out.println("double string is: " + String.valueOf(d) );

The StringBuffer Class

If you modify a String object many times you end up will lots of abandoned String objects in the String pool, this is where the StringBuffer comes in as it is not immutable, which means they can be modified over and over without leaving any abandoned objects. A common use for StringBuffers is file I/O, especially if we are talking large amounts of data.


StringBuffer sb1 = new StringBuffer();              // this will have an initial capacity of 16 characters
StringBuffer sb2 = new StringBuffer(10);            // this will have a capacity of 10 characters

StringBuffer sb3 = new StringBuffer("Hello World!");  // the capacity will be string size 12 plus 16 = 32

System.out.println("StringBuffer sb3 is: " + sb3);    // Just use it like a String

Again the StringBuffer class has many methods, here are some of the more common ones


StringBuffer sb = new StringBuffer("abcd");

System.out.println("Appends efgh to StringBuffer sb :" + sb.append("efgh");
System.out.println("StringBuffer sb is now: " + sb);

Note: There are 10 overloaded append methods which allow you to add various data type values


StringBuffer sb1 = new StringBuffer();
StringBuffer sb1 = new StringBuffer(10);
StringBuffer sb1 = new StringBuffer("Hello World");

System.out.prntln("StringBuffer sb1(character count): " + sb1);     // displays 0
System.out.prntln("StringBuffer sb2(character count): " + sb2);     // displays 0
System.out.prntln("StringBuffer sb3(character count): " + sb3);     // displays 11

System.out.prntln("StringBuffer sb1(capacity): " + sb1);     // displays 16
System.out.prntln("StringBuffer sb2(capacity): " + sb2);     // displays 10
System.out.prntln("StringBuffer sb3(capacity): " + sb3);     // displays 27

Note: increasing the size is a performance hit, so if you do change the StringBuffer make sure it has the capacity already so it does not need to grow

charAt, setCharAt, getChars These are the same the String methods above

StringBuffer sb1 = new StringBuffer();
sb1.ensureCapacity(75);                 // minimum capacity will be 75 characters

Note: if the character length is greater then the method ensures a capacity that is the greater of the number specified as an argument or twice the original capacity plus 2.


## sb.delete(start position, end position)
StringBuffer sb = new StringBuffer("1234567890");

System.out.println("Inserted text into StringBuffer sb: " + sb.delete(4, 6));  / displays 12347890


## sb.insert(start, data type) there are many diffrent data types i.e boolean, char, String, etc
StringBuffer sb = new StringBuffer("1234567890");

System.out.println("Inserted text into StringBuffer sb: " + sb.insert(4, "----"));

Note: again the offset is zero based


StringBuffer sb1 = new StringBuffer();
StringBuffer sb1 = new StringBuffer(10);
StringBuffer sb1 = new StringBuffer("Hello World");

System.out.prntln("StringBuffer sb1: " + sb1);     // displays 0
System.out.prntln("StringBuffer sb2: " + sb2);     // displays 0
System.out.prntln("StringBuffer sb3: " + sb3);     // displays 11

Note: the length method only returns the character count not the size of the StringBuffer - see capacity


StringBuffer sb = new StringBuffer("1234567890");

System.out.println("Reversed StringBuffer sb:" + sb.reverse());


StringBuffer sb1 = new StringBuffer("Hello World");
System.out.prntln("sb1: " + sb1);     // displays Hello, it truncated the original

Note: setLength will truncate any characters if the capacity is less than the String contained inside it


StringBuffer sb = new StringBuffer("1234567890");

System.out.println("StringBuffer sb:" + sb.toString());

StringTokenizer Class

When you read a sentence you break it up into words, or tokens, StringTokenizer breaks a string into its component tokens. Tokens are sperated by a delimiter such as white space, coma, colo, etc.


import java.util.StringTokenizer;

public class stringTokenizerTest {
   public static void main(String[] args) {

      String s = "This is the string to be tokenized by delimiting whitespaces";
      StringTokenizer tokens = new StringTokenerizer(s);

      System.out.println("There are " + tokens.countTokens() + " tokens" );

      System.out.println("The tokens are: ")
      while( tokens.hasMoreTokens() )
         System.out.println( tokens.nextToken() );

StringTokenizer (delimiter)

String s = "This:is:the:string:to:be:tokenized:by:delimiting:whitespaces";
String delimiter = ":";
StringTokenizer tokens = new StringTokenerizer(s, delimiter);   // here we change the delimiter

StringTokenizer has other methods that you can use: hasMoreElements, nextElement

Chained Methods

You can use a bit of Java tricky to chain methods (any methods)

General Form result = method1().method2().method3();
Example using String

String x = "hello have a nice day     ";

x = x.trim().concat(" and a jolly good evening").replace('hello'.'Hello');

Note: the statement is processed from left to right, so the trim method is called first, etc

Math Class

The Math class is used to perform basic mathematical operations. The Math class defines approximations for the mathematical constants pi and e.

PI public final static double Math.PI
E public final static double Math.E

Because all methods in the Math class are static you do not need to create an instance for them, it is impossible as the constructor for the Math class is marked private. You cannot extend the Math class either as it is marked final.

The Math class has a number of different methods, here are some of the more common ones


x = Math.abs(99);       // returns 99
x = Math.abs(-99);      // returns the absolute value 99

Note: there are many overloaded methods that can take int, long, float, etc


x = Math.ceil(9.0);     // result is 9.0
x = Math.ceil(8.8);     // result is 9.0
x = Math.ceil(8.01);    // still rises to 9.0

Note: there is only one ceil method, ceil(double a)

exp() x = Math.exp(1.0);       // result is 2.71828
x = Math.exp(2.0);       // result is 7.38906

x = Math.floor(9.0);     // result is 9.0
x = Math.floor(9.4);     // result is 9.0
x = Math.floor(9.99);    // still drops to 9.0

Note: there is only one ceil method, ceil(double a)


x = Math.max(1024, 1023);    // result is 1024

Note: there are many overloaded methods that can take int, long, float, etc


x = Math.min(1024, 1023);    // result is 1023

Note: there are many overloaded methods that can take int, long, float, etc

pow() x = Math.pow(2.0, 7.0);      // result is 128.0 (2*2*2*2*2*2*2)
x = Math.pow(9.0, 0.5);      // result is 3.0   (9.0 * 0.5)

for ( int i = 1; i < 5; i++) {
   System.out.println( (int) (Math.random()*10) + " ");

Note: returns a random double number between 0.0 and 1.0

round() x = Math.round(-10.5);       // result is -10

Note: if equal to or greater that 0.5 then number is rounded up, otherwise rounded down
sin(), cos() and tan() x = Math.sin(Math.toRadians(90.0));   // result is 1.0

x = Math.cos(Math.toRadians(0.0));    // result is 1.0

x = Math.tan(Math.toRadians(45.0));   // result is 1.0
sqrt() x = Math.sqrt(9.0);          // result is 3.0
toDegrees() x = Math.toDegrees(Math.PI * 2.0);    // result 360.0
toRadians() x = Math.toRadians(360.0);   // result is 6.283185

Wrapper Classes

Wrapper classes serve two primary purposes

There is a wrapper class for every primitive, the one for int is Integer, for float is Float and so on. below is a table detailing the wrapper classes and their constructor arguments

Primitive Wrapper Class Constructor Arguments
boolean Boolean boolean or String
byte Byte byte or String
char Character char
double Double double or String
float Float float, double or String
int Integer int or String
long Long long or String
short Short short or String

A note before i show some examples is that wrapper classes are immutable, thus they cannot be changed, also a Boolean object can't be used like a boolean primitive.

Creating Integer i1 = new Integer(42);
Integer i2 = new Integer("42");
Character c1 = new Character('c');
Creating using valueOf() method

Integer i3 = Integer.valueOf("101011", 2);     // converts 101011 to 43

Float f2 = Float.valueOf("3.14f");             // assign 3.14 to Float object f2

Creating using parseXXX() method

String s1 = "42";

int i1 = Integer.parseInt(s1);                 // converts the String to a int primitive

Using Wrappers

String num1 = "42";
String num2 = "58";

System.out.println("Total: " + (num1 + num2)); // results in 4258 not what we was hoping for

Integer i1 = new Integer(num1);                // convert the String value into a primitive value
Integer i2 = new Integer(num2);

System.out.println("Total: " + (i1 + i2));     // results in 100 what we wanted

System.out.println("Total: " + (Integer.parseInt(num1) + Integer.parseInt(num2))); // another way

Using toString()

String num1 = "42";

Integer i1 = new Integer(num1);

System.out.println("toString reports: " + i1.toString());     // now print out a String

Each class has many methods for data integrity, for example the Character class has the following methods: isDefined, isDigit, isLowerCase, isUpperCase and so on.

Using Equals

There are three kinds of entities in Java that we might want to compare, primitive variables, reference variables and objects. There are two ways to compare primitive variables, reference variables and objects.

You always compare primitive variable with the = = operator, it will return true if the variables are the same otherwise false. When we compare to reference variables using the = = operator we are testing to see if the two variables refer to the same object, so you are comparing two sets of bit patterns. Using the = = operator you can only compare objects that are in the same class or class hierarchy, if they are in different classes you will get a compiler error.

The key facts to remember are

To actual compare two Strings (contents so to speak) we using the equals() method.

example String s1 = "hello";
String s2 = "hell";
s2 += "o";

String s3 = s1;

System.out.println("s1: " + s1 + "\n");
System.out.println("s2: " + s2 + "\n");
System.out.println("s3: " + s3 + "\n");

// Check that Strings reference the same object
if ( s1 == s2 ) {
   System.out.println("S1 has same ref as S2");
} else {
   System.out.println("S1 does not has same ref as S2");

// Check that strings have the same contents
if ( s2.equals(s1) ) {
   System.out.println("S1 has same contents S2");
} else {
   System.out.println("S1 does not have same contents S2");

// Check that Strings reference the same object
if ( s1 == s3 ) {
   System.out.println("S1 has same ref as S3");
} else {
   System.out.println("S1 does not has same ref as S3");

// Check that strings have the same contents
if ( s3.equals(s1) ) {
   System.out.println("S1 has same contents S3");
} else {
  System.out.println("S1 does not have same contents S3");

The class Object has an equals() method which means that every other Java class inherits an equals() method, however a number of classes override this method(String, wrapper).

The key fact to remember regarding the equals() method are

There are occasions when you want to override the equals() method yourself, more details can be found here.