Strings in java

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.

Java.lang.String class creation

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”;
String str2 = “My name is bob”;
String str3 = “My name ”+ “is bob”; //Compile time expression
String name = “bob”;
String str4 = “My name is” + name;    //run time expression
String str5 = new String(“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 рсту

Java String Functions    -  see the Oracle's documentation for details

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

StringTokenizer

The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to break a String

delimiter by default  - spaces

import java.util.StringTokenizer;
public class Test{
    public static void main(String arg[]){
        String s = "Java is a general-purpose, class-based, and object-oriented language";
        StringTokenizer st = new StringTokenizer(s);
        while(st.hasMoreTokens()){
            String word = st.nextToken();
            System.out.println(word);
        }
    }
}

delimiter   characters  '/', ':' and  '.'

import java.util.StringTokenizer;
public class Test{
    public static void main(String arg[]){
        String s1 = "http://www.javasoft.com";
        StringTokenizer st1 = new StringTokenizer(s1,"/:.");
        while(st1.hasMoreTokens()){
            String word = st1.nextToken();
            System.out.println(word);
        }
    }
}

StringBuffer, StringBuilder

Java provides three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder classes are mutable. The String class is much  more faster under most implementations than StringBuffer, and StringBuilder
 
A StringBuffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. String buffers are safe for use by multiple threads.

A StringBuilder provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

The principal operations are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

The methods  length(), deleteCharAt(index),  delete(start, end) , setCharAt(index, ch), setLength(newLength) are also commonly used. 




public class Test{
    public static void main(String arg[]){
        StringBuffer sBuf = new StringBuffer ("new ") ;
        sBuf.append("test string buffer");
        System.out.println (sBuf) ;
        sBuf.setCharAt (3, 'J'); System.out.println (sBuf) ;
        sBuf.append (" 2") ; System.out.println (sBuf) ;
        sBuf.insert (3, "langage ") ; System.out.println (sBuf) ;
    }
}

public class Test{
    public static void main(String arg[]){
        StringBuilder sBuf = new StringBuilder ("new ") ;
        sBuf.append("test string builder");
        System.out.println (sBuf) ;
        sBuf.setCharAt (3, 'J'); System.out.println (sBuf) ;
        sBuf.append (" 2") ; System.out.println (sBuf) ;
        sBuf.insert (3, "langage ") ; System.out.println (sBuf) ;
    }
}

Enum Types

An enum declaration specifies a new enum type, a special kind of class type.
EnumDeclaration:
[ClassModifier] enum <Identifier>  <EnumBody>

It is a compile-time error if an enum declaration has the modifier abstract or final.

An enum declaration is implicitly final unless it contains at least one enum constant that has a class body.

It is a compile-time error if the same keyword appears more than once as a modifier for an enum declaration.

An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type.






enum Coin { PENNY, NICKEL, DIME, QUARTER }
enum Weekday {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}


Weekday d1,d2;
d1 = Weekday. MONDAY;
d2 = Weekday. TUESDAY;

It is possible to use operator == or the method  equals().
Not possible to use the arithmetic operators.
It is possible to use the method  compareTo()  based of the order of constant's declarations.

System.out.println(d1+"");
will has as resut  " MONDAY ".

Weekday.valueOf("TUESDAY")
will result as reference to Weekday. TUESDAY.

public class Test{
    enum Weekday {
        SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
    }
    public static void main(String[] arg){
        Weekday  d1,d2,d3;
        d1 = Weekday.MONDAY;
        d2 = Weekday.MONDAY ;
        d3 = Weekday.WEDNESDAY;
        System.out.println("operator=:\t"+(d1==d2)+"\t"+(d1==d3));
        System.out.println("method equal():\t"+d1.equals(d2));   
        if(d1.compareTo(d3)<0){
            System.out.println(d1+" is before "+d3);
        }
    }
}

public class Test {
    enum Coin { PENNY, NICKEL, DIME, QUARTER }
    public static void main(String[] args) {
        Coin coin = Coin.NICKEL;
        switch (coin){
            case PENNY : System.out.println("1 cent"); break;
            case NICKEL : System.out.println("5 cents"); break;
            case DIME : System.out.println("10 cents"); break;
            case QUARTER: System.out.println("25 cents"); break;
            default : System.out.println("not possible");
        }
    }
}

 Iterating over enum constants with an enhanced for loop  for...each (after the creation an array with the méthode value() - static values() method  returns an array containing all of the values of the enum in the order they are declared)

public class Test{
    enum Weekday {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
    }
    public static void main(String[] arg){
        for(Weekday d: Weekday.values()){
            System.out.print(d+"; ");
        }
    }
}



public class Test{
    enum Weekday {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
        FRIDAY, SATURDAY, SUNDAY;
        String workTime(){
            if(this ==SUNDAY ){
                return "10 - 14";
            }
            if(this == SATURDAY){
                return "10 - 18";
            }
            return "8 - 22";
        }
    }
    public static void main(String[] arg){
        System.out.println("Working time:");
        for(Weekday d: Weekday.values()){
            System.out.println(d+": "+d.workTime());          
        }
    }
}

The class Math

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