Monday, 29 August 2011


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;
String str5 = new String(“My name is bob”);
<br /><font size=-1>
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.
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 = {2, 4, 6, 8};
 
      char[] characters = {'a', 'b', 'C', 'D'};
 
      StringBuffer strBuffer = new StringBuffer("abcde");
 
//          Examples of Creation of Strings
 
      String byteStr = new String(bytes);      
 
      String charStr = new String(characters); 
 
      String buffStr = new String(strBuffer);
 
      System.out.println("byteStr : "+byteStr);
 
      System.out.println("charStr : "+charStr);
 
      System.out.println("buffStr : "+buffStr);
 
    }
 
}
Download StringDemo1.java
Output
byteStr : [1]


charStr : abCD
buffStr : abcde
–~~~~~~~~~~~~–

String Equality

public class StringsDemo2 {
 
        public static void main(String[] args) {
               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;
               String str5 = new String("My name is bob");
               System.out.println("str1 == str2 : " + (str1 == str2));
               System.out.println("str2 == str3 : " + (str2 == str3));
               System.out.println("str3 == str1 : " + (str3 == str1));
               System.out.println("str4 == str5 : " + (str4 == str5));
               System.out.println("str1 == str4 : " + (str1 == str4));
               System.out.println("str1 == str5 : " + (str1 == str5));
               System.out.println("str1.equals(str2) : " + str1.equals(str2));
               System.out.println("str2.equals(str3) : " + str2.equals(str3));
               System.out.println("str3.equals(str1) : " + str3.equals(str1));
               System.out.println("str4.equals(str5) : " + str4.equals(str5));
               System.out.println("str1.equals(str4) : " + str1.equals(str4));
               System.out.println("str1.equals(str5) : " + str1.equals(str5));
        }
}
Download StringDemo2.java
Output
str1 == str2 : true
str2 == str3 : true
str3 == str1 : true
str4 == str5 : false
str1 == str4 : false
str1 == str5 : false
str1.equals(str2) : true
str2.equals(str3) : true
str3.equals(str1) : true
str4.equals(str5) : true
str1.equals(str4) : true
str1.equals(str5) : true

Java String Functions

The following program explains the usage of the some of the basic String methods like ;
1. compareTo(String anotherString)
Compares two strings lexicographically.
2. charAt(int index)
Returns the character at the specified index.
3. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
4. length()
Returns the length of this string.
5. equals(Object anObject)
Compares this string to the specified object.
6. equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
7. toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
7. toLowerCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
9. concat(String str)
Concatenates the specified string to the end of this string.
10. indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
11. 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. indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
13. 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. lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
15. 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. lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
17. 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.
18. substring(int beginIndex)
Returns a new string that is a substring of this string.
19. substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
20. replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
21. trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
22. toString()
This object (which is already a string!) is itself returned.
public class StringsDemo3 {
 
        public static void main(String[] args) {
               String str1 = "My name is bob";
               char str2[] = new char[str1.length()];
               String str3 = "bob";
               String str4 = "cob";
               String str5 = "BoB";
               String str6 = "bob";
               System.out.println("Length of the String str1 : " + str1.length());
               System.out.println("Character at position 3 is : "
                               + str1.charAt(3));
               str1.getChars(0, str1.length(), str2, 0);
               System.out.print("The String str2 is : ");
               for (int i = 0; i < str2.length; i++) {
                       System.out.print(str2[i]);
               }
               System.out.println();
               System.out.print("Comparision Test : ");
               if (str3.compareTo(str4) < 0) {
                       System.out.print(str3 + " < " + str4);
               } else if (str3.compareTo(str4) > 0) {
                       System.out.print(str3 + " > " + str4);
               } else {
                       System.out.print(str3 + " equals " + str4);
               }
               System.out.println();
               System.out.print("Equals Test");
               System.out.println("str3.equalsIgnoreCase(5) : "
                               + str3.equalsIgnoreCase(str5));
               System.out.println("str3.equals(6) : " + str3.equals(str6));
               System.out.println("str1.equals(3) : " + str1.equals(str3));
               str5.toUpperCase(); //Strings are immutable
               System.out.println("str5 : " + str5);
               String temp = str5.toUpperCase();
               System.out.println("str5 Uppercase: " + temp);
               temp = str1.toLowerCase();
               System.out.println("str1 Lowercase: " + str1);
               System.out.println("str1.concat(str4): " + str1.concat(str4));
               String str7temp = "  \t\n Now for some Search and Replace Examples    ";
               String str7 = str7temp.trim();
               System.out.println("str7 : " + str7);
               String newStr = str7.replace('s', 'T');
               System.out.println("newStr : " + newStr);
               System.out.println("indexof Operations on Strings");
               System.out.println("Index of p in " + str7 + " : "
                               + str7.indexOf('p'));
               System.out.println("Index of for in " + str7 + " : "
                               + str7.indexOf("for"));
               System.out.println("str7.indexOf(for, 30) : "
                               + str7.indexOf("for", 30));
               System.out.println("str7.indexOf('p', 30) : "
                               + str7.indexOf('p', 30));
               System.out.println("str7.lastIndexOf('p') : "
                               + str7.lastIndexOf('p'));
               System.out.println("str7.lastIndexOf('p', 4) : "
                               + str7.lastIndexOf('p', 4));
               System.out.print("SubString Operations on Strings");
               String str8 = "SubString Example";
               String sub5 = str8.substring(5); // "ring Example"
               String sub3_6 = str8.substring(3, 6); // "Str"
               System.out.println("str8 : " + str8);
               System.out.println("str8.substring(5) : " + sub5);
               System.out.println("str8.substring(3,6) : " + sub3_6);
        }
}
Download StringDemo3.java
Output
Length of the String str1 : 14
Character at position 3 is : n
The String str2 is : My name is bob
Comparision Test : bob < cob
Equals Teststr3.equalsIgnoreCase(5) : true
str3.equals(6) : true
str1.equals(3) : false
str5 : BoB
str5 Uppercase: BOB
str1 Lowercase: My name is bob
str1.concat(str4): My name is bobcob
str7 : Now for some Search and Replace Examples
newStr : Now for Tome Search and Replace ExampleT
Indexof Operations on Strings
Index of p in Now for some Search and Replace Examples : 26
Index of for in Now for some Search and Replace Examples : 4
str7.indexOf(for, 30) : -1
str7.indexOf(’p', 30) : 36
str7.lastIndexOf(’p') : 36
str7.lastIndexOf(’p', 4) : -1
SubString Operations on Stringsstr8 : SubString Example
str8.substring(5) : ring Example
str8.substring(3,6) : Str
Below is a program to check for Alpha Numeric character’s in the string.
public class TestAlphaNumericCharacters {
 
      private void isAlphaNumeric(final String input) {
            boolean isCharFlag = false;
            boolean isNumberFlag = false;
            final char[] chars = input.toCharArray();
            for (int x = 0; x < chars.length; x++) {
                  char c = chars[x];
                  //                 lowercase && uppercase alphabet
                  if ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z')) {
                        isCharFlag = true;
                        continue;
                  }
                  if ((c >= '0') && (c <= '9')) { // numeric
                        isNumberFlag = true;
                        continue;
                  }
            }
            System.out.println("characters are present:" + isCharFlag);
            System.out.println("Numbers are present :" + isNumberFlag);
      }
      public static void main(String[] args) {
            TestAlphaNumericCharacters tANC = new TestAlphaNumericCharacters();
            tANC.isAlphaNumeric("beginn3ers");
      }
}
Download TestAlphaNumericCharacters.java
Output
characters are present:true
Numbers are present :true
Below is a java program to Reverse a string (Reverse by words / characters)
import java.util.*;
 
public class StringReverse {
 
        public static void main(String[] args) {
               String input = "beginner java tutorial";
               Stack stack = new Stack(); //A Stack is a Last In First Out Data Structure
               StringTokenizer stringTokenizer = new StringTokenizer(input);
               while (stringTokenizer.hasMoreTokens()) {
                       stack.push(stringTokenizer.nextElement());
               }
               System.out.println("Original String: " + input);
               System.out.print("Reversed String by Words: ");
               while (!stack.empty()) {
                       System.out.print(stack.pop());
                       System.out.print(" ");
               }
               System.out.println();
               System.out.print("Reversed String by characters: ");
               StringBuffer rev = new StringBuffer(input).reverse();
               System.out.print(rev);
        }
}
Download StringReverse.java
Output
Original String: beginner java tutorial
Reversed String by Words: tutorial java beginner
Reversed String by characters: lairotut avaj rennigeb
Java String Comparison:
Java String compare to determine Equality
java string compare can be done in many ways as shown below. Depending on the type of java string compare you need, each of them is used.
* == Operator
* equals method
* compareTo method
Comparing using the == Operator
The == operator is used when we have to compare the String object references. If two String variables point to the same object in memory, the comparison returns true. Otherwise, the comparison returns false. Note that the ‘==’ operator does not compare the content of the text present in the String objects. It only compares the references the 2 Strings are pointing to. The following Program would print “The strings are unequal” In the first case and “The strings are equal” in the second case.
<br /><font size=-1>

public class StringComparision1 {

        public static void main(String[] args) {
               String name1 = "Bob";
               String name2 = new String("Bob");
               String name3 = "Bob";
               // 1st case
               if (name1 == name2) {
                       System.out.println("The strings are equal.");
               } else {
                       System.out.println("The strings are unequal.");
               }
               // 2nd case
               if (name1 == name3) {
                       System.out.println("The strings are equal.");
               } else {
                       System.out.println("The strings are unequal.");
               }
        }
}
Download StringComparision1.java
Comparing using the equals Method
The equals method is used when we need to compare the content of the text present in the String objects. This method returns true when two String objects hold the same content (i.e. the same values). The following Program would print “The strings are unequal” In the first case and “The strings are equal” in the second case.
public class StringComparision2 {

        public static void main(String[] args) {
               String name1 = "Bob";
               String name2 = new String("Bob1");
               String name3 = "Bob";
               // 1st case
               if (name1.equals(name2)) {
                       System.out.println("The strings are equal.");
               } else {
                       System.out.println("The strings are unequal.");
               }
               // 2nd case
               if (name1.equals(name3)) {
                       System.out.println("The strings are equal.");
               } else {
                       System.out.println("The strings are unequal.");
               }
        }
}
Download StringComparision2.java
Comparing using the compareTo Method
The compareTo method is used when we need to determine the order of Strings lexicographically. It compares char values similar to the equals method. The compareTo method returns a negative integer if the first String object precedes the second string. It returns zero if the 2 strings being compared are equal. It returns a positive integer if the first String object follows the second string. The following Program would print “name2 follows name1” In the first case and “name1 follows name3” in the second case.
public class StringComparision3 {

        public static void main(String[] args) {
               String name1 = "bob";
               String name2 = new String("cob");
               String name3 = "Bob";
               // 1st case
               if (name1.compareTo(name2) == 0) {
                       System.out.println("The strings are equal.");
               } else if (name1.compareTo(name2) < 0) {
                       System.out.println("name2 follows name1");
               } else {
                       System.out.println("name1 follows name2");
               }
               // 2nd case. Comparing Ascii Uppercase will be smaller then Lower Case
               if (name1.compareTo(name3) == 0) {
                       System.out.println("The strings are equal.");
               } else if (name1.compareTo(name3) < 0) {
                       System.out.println("name3 follows name1");
               } else {
                       System.out.println("name1 follows name3");
               }
        }
}
Download StringComparision3.java
Java String Buffer:

StringBuffer Class

StringBuffer class is a mutable class unlike the String class which is immutable. Both the capacity and character string of a StringBuffer Class. StringBuffer can be changed dynamically. String buffers are preferred when heavy modification of character strings is involved (appending, inserting, deleting, modifying etc).
Strings can be obtained from string buffers. Since the StringBuffer class does not override the equals() method from the Object class, contents of string buffers should be converted to String objects for string comparison.
A StringIndexOutOfBoundsException is thrown if an index is not valid when using wrong index in String Buffer manipulations

Creation of StringBuffers

StringBuffer Constructors
public class StringBufferDemo {
 
        public static void main(String[] args) {
               //      Examples of Creation of Strings
               StringBuffer strBuf1 = new StringBuffer("Bob");
               StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100
               StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16
               System.out.println("strBuf1 : " + strBuf1);
               System.out.println("strBuf2 capacity : " + strBuf2.capacity());
               System.out.println("strBuf3 capacity : " + strBuf3.capacity());
        }
}
Download StringBufferDemo.java
&lt;br /&gt;&lt;font size=-1&gt;
Output
strBuf1 : Bob
strBuf2 capacity : 100
strBuf3 capacity : 16

StringBuffer Functions

The following program explains the usage of the some of the basic StringBuffer methods like ;
1. capacity()
Returns the current capacity of the String buffer.
2. length()
Returns the length (character count) of this string buffer.
3. charAt(int index)
The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.
4. setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to ch
5. toString()
Converts to a string representing the data in this string buffer
6. insert(int offset, char c)
Inserts the string representation of the char argument into this string buffer.
Note that the StringBuffer class has got many overloaded ‘insert’ methods which can be used based on the application need.
7. delete(int start, int end)
Removes the characters in a substring of this StringBuffer
8. replace(int start, int end, String str)
Replaces the characters in a substring of this StringBuffer with characters in the specified String.
9. reverse()
The character sequence contained in this string buffer is replaced by the reverse of the sequence.
10. append(String str)
Appends the string to this string buffer.
Note that the StringBuffer class has got many overloaded ‘append’ methods which can be used based on the application need.
11. setLength(int newLength)
Sets the length of this String buffer.
public class StringBufferFunctionsDemo {
 
        public static void main(String[] args) {
               //      Examples of Creation of Strings
               StringBuffer strBuf1 = new StringBuffer("Bobby");
               StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100
               StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16
               System.out.println("strBuf1 : " + strBuf1);
               System.out.println("strBuf1 capacity : " + strBuf1.capacity());
               System.out.println("strBuf2 capacity : " + strBuf2.capacity());
               System.out.println("strBuf3 capacity : " + strBuf3.capacity());
               System.out.println("strBuf1 length : " + strBuf1.length());
               System.out.println("strBuf1 charAt 2 : " + strBuf1.charAt(2));
               //      A StringIndexOutOfBoundsException is thrown if the index is not valid.
               strBuf1.setCharAt(1, 't');
               System.out.println("strBuf1 after setCharAt 1 to t is : "
                               + strBuf1);
               System.out
                               .println("strBuf1 toString() is : " + strBuf1.toString());
               strBuf3.append("beginner-java-tutorial");
               System.out.println("strBuf3 when appended with a String : "
                               + strBuf3.toString());
               strBuf3.insert(1, 'c');
               System.out.println("strBuf3 when c is inserted at 1 : "
                               + strBuf3.toString());
               strBuf3.delete(1, 'c');
               System.out.println("strBuf3 when c is deleted at 1 : "
                               + strBuf3.toString());
               strBuf3.reverse();
               System.out.println("Reversed strBuf3 : " + strBuf3);
               strBuf2.setLength(5);
               strBuf2.append("jdbc-tutorial");
               System.out.println("strBuf2 : " + strBuf2);
               //      We can clear a StringBuffer using the following line
               strBuf2.setLength(0);
               System.out.println("strBuf2 when cleared using setLength(0): "
                               + strBuf2);
        }
}

Download
StringBufferFunctionsDemo.java
Output
strBuf1 : Bobby
strBuf1 capacity : 21
strBuf2 capacity : 100
strBuf3 capacity : 16
strBuf1 length : 5
strBuf1 charAt 2 : b
strBuf1 after setCharAt 1 to t is : Btbby
strBuf1 toString() is : Btbby
strBuf3 when appended with a String : beginner-java-tutorial
strBuf3 when c is inserted at 1 : bceginner-java-tutorial
strBuf3 when c is deleted at 1 : b
Reversed strBuf3 : b
strBuf2 :
Java Exceptions:
Exceptions in java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime. They could be file not found exception, unable to get connection exception and so on. On such conditions java throws an exception object. Java Exceptions are basically Java objects. No Project can never escape a java error exception.
Java exception handling is used to handle error conditions in a program systematically by taking the necessary action. Exception handlers can be written to catch a specific exception such as Number Format exception, or an entire group of exceptions by using a generic exception handlers. Any exceptions not specifically handled within a Java program are caught by the Java run time environment
An exception is a subclass of the Exception/Error class, both of which are subclasses of the Throwable class. Java exceptions are raised with the throw keyword and handled within a catch block.
A Program Showing How the JVM throws an Exception at runtime
public class DivideException {
 
    public static void main(String[] args) {
      division(100,4);        // Line 1
      division(100,0);        // Line 2
        System.out.println("Exit main().");
    }
 
    public static void division(int totalSum, int totalNumber) {

  
&lt;font size=-1&gt;
  
  
 
      System.out.println("Computing Division.");
      int average  = totalSum/totalNumber;
        System.out.println("Average : "+ average);
    }
}
Download DivideException.java
An ArithmeticException is thrown at runtime when Line 11 is executed because integer division by 0 is an illegal operation. The “Exit main()” message is never reached in the main method
Output
Computing Division.
java.lang.ArithmeticException: / by zero
Average : 25
Computing Division.
at DivideException.division(DivideException.java:11)
at DivideException.main(DivideException.java:5)
Exception in thread “main”

No comments: