Java String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on the same reference. A java.lang.String class is final which implies no class can extend it. The java.lang.String class differs from other classes, one difference being that the String objects can be used with the += and + operators for concatenation.
Two useful methods for String objects are equals( ) and substring( ). The equals( ) method is used for testing whether two Strings contain the same value. The substring( ) method is used to obtain a selected portion of a String.
A simple String can be created using a string literal enclosed inside double quotes as shown;
String str1 = “My name is bob”;
Since a string literal is a reference, it can be manipulated like any other String reference. The reference value of a string literal can be assigned to another String reference.
If 2 or more Strings have the same set of characters in the same sequence then they share the same reference in memory. Below illustrates this phenomenon.
String str1 = “My name is bob”;In the above code all the String references str1, str2 and str3 denote the same String object, initialized with the character string: “My name is bob”. But the Strings str4 and str5 denote new String objects.
public class
Test { public static void main (String[] arg){ String str1 = "My name is bob"; String str2 = "My name is bob"; String name = "bob"; String str3 = "My name "+ "is bob"; //Compile time expression String str4 = "My name is" + name; String str5 = new String("My name is bob"); System.out.println("1-2: "+(str1==str2)); System.out.println("1-3: "+(str1==str3)); System.out.println("1-4: "+(str1==str4)); System.out.println("1-5: "+(str1==str5)); System.out.println("4-5: "+(str4==str5)); } } |
1-2: true 1-3: true 1-4: false 1-5: false 4-5: false |
Constructing String objects can also be done from arrays of bytes, arrays of characters, or string buffers. A simple way to convert any primitive value to its string representation is by concatenating it with the empty string (""), using the string concatenation operator (+).
public
class
StringsDemo { public static void main(String[] args) { byte[] bytes = {65, 66, 67, 68}; char[] characters = {'a', 'b', 'C', 'D',' ',0x440,0x441,0x442,0x443}; // Examples of Creation of Strings String byteStr = new String(bytes); String charStr = new String(characters); System.out.println("byteStr : "+byteStr); System.out.println("charStr : "+charStr); } } |
byteStr : ABCD charStr : abCD рсту |
The following program explains the usage of the some of the basic String methods like ;
1. int compareTo(String anotherString)
Compares two strings lexicographically ((based on the alphabetical
order of their component letters)).
public
class TestCt { public static void main(String [] arg){ String s1 = new String("table"); String s2 = new String("room"); String s3 = new String ("Table"); String s4 = new String ("table"); System.out.println("1: "+s1.compareTo(s2)); System.out.println("2: "+s2.compareTo(s1)); System.out.println("3: "+s1.compareTo(s3)); System.out.println("4: "+s1.compareTo(s4)+ "\t"+(s1!=s4)); } } |
1: 2 2: -2 3: 32 4: 0 true |
Exemple - compare and print in the lexicographical order two names.
2. char charAt(int index)
Returns the character at the specified index.
public
class TestCa { public static void main(String [] arg){ String s1 = new String("table"); String s2 = new String("room"); System.out.println("1:"+s1.charAt(2)); System.out.println("2:"+s2.charAt(0)); } } |
1:b 2:r |
3. void getChars(int srcBegin, int srcEnd, char[]
dst, int dstBegin)
Copies characters from this string into the destination character array.
4. int length()
Returns the length of this string.
public
class Test { public static void main(String [] arg){ String s1 = new String("table"); String s2 = new String("room"); System.out.println("1:"+s1.length()); System.out.println("2:"+(s1+s2).length()); } } |
1:5 2:9 |
5. boolean equals(Object anObject)
Compares this string to the specified object.
public
class Test { public static void main(String [] arg){ String s1 = new String("table"); String s2 = new String("table"); System.out.println("1:"+(s1!=s2)); System.out.println("2:"+s1.equals(s2)); } } |
1:true 2:true |
6. boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
public
class Test { public static void main(String [] arg){ String s1 = new String("table"); String s2 = new String("TABLE"); System.out.println("1:"+s1.equalsIgnoreCase(s2)); System.out.println("2:"+s1.equals(s2)); } } |
1:true 2:false |
7. String toUpperCase()
Converts all of the characters in this String to upper case using the
rules of the default locale.
8. String toLowerCase()
Converts all of the characters in this String to upper case using the
rules of the default locale.
public
class Test { public static void main(String [] arg){ String s1 = new String("table"); String s2 = new String("TABLE"); System.out.println(s1 +" "+s1.toUpperCase()); System.out.println(s2 +" "+s2.toLowerCase()); } } |
table TABLE TABLE table |
9. String concat(String
str)
Concatenates the specified string to the end of this string.
10. int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
11. int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
12. int indexOf(String str)Returns the index within this string of the first occurrence of the specified substring.
13. int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
14. int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
15. int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
16. int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
17. int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
public
class Test { public static void main(String [] arg){ String s1 = new String("tabalabama"); System.out.println(s1 +" "+s1.indexOf('a')); System.out.println(s1 +" "+s1.indexOf('a',4)); System.out.println(s1 +" "+s1.lastIndexOf('a')); System.out.println(s1 +" "+s1.indexOf("ab")); System.out.println(s1 +" "+s1.indexOf("ab",3)); System.out.println(s1 +" "+s1.lastIndexOf("ab")); } } |
tabalabama 1 tabalabama 5 tabalabama 9 tabalabama 1 tabalabama 5 tabalabama 5 |
18. String substring(int beginIndex)
Returns a new string that is a substring of this string.
19. String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
20. String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
21. String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
public
class Test { public static void main(String [] arg){ String s1 = new String("tabalabama "); System.out.println(s1 +" "+s1.indexOf('a')); System.out.println(s1 +" "+s1.indexOf('a',4)); System.out.println(s1 +" "+s1.lastIndexOf('a')); System.out.println(s1 +" "+s1.indexOf("ab")); System.out.println(s1 +" "+s1.indexOf("ab",3)); System.out.println(s1 +" "+s1.lastIndexOf("ab")); System.out.println("/"+s1+"/" +" trim: "+"/"+s1.trim()+"/"); } } |
tabalabama 1 tabalabama 5 tabalabama 9 tabalabama 1 tabalabama 5 tabalabama 5 /tabalabama / trim: /tabalabama/ |
Converting from String
float f
=
Float.parseFloat("14.75");
//radix
= 10
int k =
Integer.parseInt("234");
//radix = 10
int j =
Integer.parseInt("ef",16);
//radix = 16
long l
= Long.parseLong("6754",8);
//radix = 8
Integer.parseInt("0",
10)
-> 0
Integer.parseInt("473",
10)
-> 473
Integer.parseInt("-0",
10)
-> 0
Integer.parseInt("-FF",
16)
-> -255
Integer.parseInt("1100110",
2)
-> 102
Integer.parseInt("2147483647",
10) -> 2147483647
Integer.parseInt("-2147483648",
10) -> -2147483648
Integer.parseInt("2147483648",
10)
NumberFormatException
Integer.parseInt("99",
8)
NumberFormatException
Integer.parseInt("Kona",
10)
NumberFormatException
Integer.parseInt("Kona",
27)
-> 411787
public class
StringEx{ public static void main(String a[]){ String names [ ] = {"Rose","Anabelle", "Gerard", "Francoise", "Erik","Constance"},name; for(boolean ok = false; !ok; ){ ok=true; for(int i = 0; i < names.length-1; i++){ if(names[i].compareTo(names[i+1])>0){ name = names[i]; names[i] = names[i+1]; names[i+1] = name; ok = false; } } } for(int i = 0; i <names.length;i++) System.out.println (names[i] + " : "+names[i].length()+" letters"); } } |
Anabelle : 8
letters Constance : 9 letters Erik : 4 letters Francoise : 9 letters Gerard : 6 letters Rose : 4 letters |
values()
method returns an array
containing all of the values of the enum in the order they are declared)The class Math
contains
methods for performing basic numeric operations such as the elementary
exponential, logarithm, square root, and trigonometric functions. You
can find a detailed description of the class here
public class MathApp { public static void main(String args[]) { int k = 7; int j = -9; double x = -72.6; double y = 0.34; System.out.println("E:"+Math.E); System.out.println("Pi:"+Math.PI); System.out.println("Abs value:"+Math.abs(j)); System.out.println(x + " is approximately " + Math.round(x)); System.out.println(y + " is approximately " + Math.round(y)); // The "ceiling" of a number is the smallest // integer greater than or equal to the number. System.out.println("\nThe ceiling of " + k + " is " + Math.ceil(k)); System.out.println("The ceiling of " + j + " is " + Math.ceil(j)); System.out.println("The ceiling of " + x + " is " + Math.ceil(x)); System.out.println("The ceiling of " + y + " is " + Math.ceil(y)); // The "floor" of a number is the largest // integer less than or equal to the number System.out.println("\nThe floor of " + k + " is " + Math.floor(k)); System.out.println("The floor of " + j + " is " + Math.floor(j)); System.out.println("The floor of " + x + " is " + Math.floor(x)); System.out.println("The floor of " + y + " is " + Math.floor(y)); System.out.println("\ncos Pi/4:"+Math.cos(Math.PI/4)); System.out.println("sin Pi/2:"+Math.sin(Math.PI/2)); System.out.println("tan Pi/4:"+Math.tan(Math.PI/4)); System.out.println("log(1):"+Math.log(1)); System.out.println("\n3.1 on the power 2.2:"+Math.pow(3.1,2.2)+"\n"); for(int i=0;i<3;++i) System.out.println("random "+i+": "+Math.random()+" "); // in [0, 1.0) } } |
E:2.718281828459045 Pi:3.141592653589793 Abs value:9 -72.6 is approximately -73 0.34 is approximately 0 The ceiling of 7 is 7.0 The ceiling of -9 is -9.0 The ceiling of -72.6 is -72.0 The ceiling of 0.34 is 1.0 The floor of 7 is 7.0 The floor of -9 is -9.0 The floor of -72.6 is -73.0 The floor of 0.34 is 0.0 cos Pi/4:0.7071067811865476 sin Pi/2:1.0 tan Pi/4:0.9999999999999999 log(1):0.0 3.1 on the power 2.2:12.050240825798763 random 0: 0.11718206515957219 random 1: 0.3345471330122952 random 2: 0.14391454743454424 |
I will take for example the method
public static double random()
which returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range