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(); 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
|
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
charAt | String x = "Hello World!"; Note: The charAt returns the character at a specific index, remember we start at zero |
compareTo | String t = "Hello"; 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 |
concat | String x = "Taxi"; System.out.println( x.concat(" cab"); Note: concat method does not update x as there was no assignment |
equals | String x = "hello"; if ( x.equalsIgnoreCase("hello") Note: see equals for more information on this method |
equalsIgnoreCase | String x = "hello"; if ( x.equalsIgnoreCase("Hello") |
getChars | # getChars(int srcBegin, int srcEnd, char[] dest, int destBegin) String h = "Hello World"; 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') ); |
intern | String t1 = "abcdefghiklmnopqrstuvwxyz"; Note: a lookup is performed |
length | 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"); else System.out.println("Not a perfect match"); if ( t.regionMatches(true, 0, match, 0, 5) ) System.out.println("A perfect match"); else System.out.println("Not a perfect match"); } |
replace | String x = "XXaXX"; System.out.println("String before: " + x); |
substring | String x = "1234567890"; System.out.println("Part of String x: " + x.substring(5)); // start from position 5 return rest of string |
toLowerCase toUpperCase | String lower = "all lower case"; System.out.println("String lower is now upper case: " + lower.toUpperCase()); |
toString | String x = "Hello World!"; System.out.println("toString method returns: " + x.toString()); |
trim | String x = " x "; System.out.println("Blank spaces removed from x: " + x.trim()); |
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) ); |
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 | StringBuffer sb1 = new StringBuffer(); // this will have an initial capacity of 16 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
append | StringBuffer sb = new StringBuffer("abcd"); Note: There are 10 overloaded append methods which allow you to add various data type values |
capacity | StringBuffer sb1 = new StringBuffer(); System.out.prntln("StringBuffer sb1(character count): " + sb1); // displays 0 System.out.prntln("StringBuffer sb1(capacity): " + sb1); // displays 16 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 |
ensureCapacity | StringBuffer sb1 = new StringBuffer(); 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. |
delete | ## sb.delete(start position, end position) System.out.println("Inserted text into StringBuffer sb: " + sb.delete(4, 6)); / displays 12347890 |
insert | ## sb.insert(start, data type) there are many diffrent data types i.e boolean, char, String, etc System.out.println("Inserted text into StringBuffer sb: " + sb.insert(4, "----")); Note: again the offset is zero based |
length | StringBuffer sb1 = new StringBuffer(); System.out.prntln("StringBuffer sb1: " + sb1); // displays 0 Note: the length method only returns the character count not the size of the StringBuffer - see capacity |
reverse | StringBuffer sb = new StringBuffer("1234567890"); System.out.println("Reversed StringBuffer sb:" + sb.reverse()); |
setLength | StringBuffer sb1 = new StringBuffer("Hello World"); Note: setLength will truncate any characters if the capacity is less than the String contained inside it |
toString | StringBuffer sb = new StringBuffer("1234567890"); System.out.println("StringBuffer sb:" + sb.toString()); |
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.
StringTokenizer | import java.util.StringTokenizer; public class stringTokenizerTest { System.out.println("There are " + tokens.countTokens() + " tokens" ); System.out.println("The tokens are: ") |
StringTokenizer (delimiter) | String s = "This:is:the:string:to:be:tokenized:by:delimiting:whitespaces"; |
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 |
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
abs() | x = Math.abs(99); // returns 99 Note: there are many overloaded methods that can take int, long, float, etc |
ceil() | x = Math.ceil(9.0); // result is 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 |
floor() | x = Math.floor(9.0); // result is 9.0 Note: there is only one ceil method, ceil(double a) |
max() | x = Math.max(1024, 1023); // result is 1024 Note: there are many overloaded methods that can take int, long, float, etc |
min() | 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) |
random() | for ( int i = 1; i < 5; i++) { 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 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"; 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 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.
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.