Sunday, July 8, 2012

charAt( ) and setCharAt( ) and getChars( ) in java

The value of a single character can be obtained from a StringBuffer via the charAt( ) method. You can set the value of a character within a StringBuffer using setCharAt( ). Their general forms are shown here: 

  •  char charAt(int where)
  • void setCharAt(int where, char ch)

For charAt( ), where specifies the index of the character being obtained. 

For setCharAt( ), where specifies the index of the character being set, and ch specifies the
new value of that character. For both methods, where must be nonnegative and must
not specify a location beyond the end of the buffer.
The following example demonstrates charAt( ) and setCharAt( ):


 
// Demonstrate charAt() and setCharAt().
 class setCharAtDemo { public static void main(String args[]) { StringBuffer sb = new 

StringBuffer("Hello"); System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1)); sb.setCharAt(1, 'i');

sb.setLength(2); System.out.println("buffer after = " + sb); System.out.println("charAt(1) after = " + sb.charAt(1));
}
}

Here is the output generated by this program: buffer before = Hello charAt(1) before = e buffer after = Hi charAt(1) after = i

getChars( ) 

To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has this general form: 
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart) 
Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from sourceStart through sourceEnd–1. The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring.

length( ) and capacity( ) in java

The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be found through the capacity( ) method. They have the following general forms:

  • int length( ) 
  • int capacity( ) 
Here is an example:

 
// StringBuffer length vs. capacity. 
 
class StringBufferDemo
 { 
 
   public static void main(String args[]) {
   StringBuffer sb = new StringBuffer("Hello");
   System.out.println("buffer = " + sb);
   System.out.println("length = " + sb.length());
   System.out.println("capacity = " + sb.capacity());
}
}


Here is the output of this program, which shows how StringBuffer reserves extra


space for additional manipulations:
buffer = Hello
length = 5
capacity = 21


Since sb is initialized with the string “Hello” when it is created, its length is 5. Its
capacity is 21 because room for 16 additional characters is automatically added. 
ensureCapacity( )

 If you want to preallocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer. ensureCapacity( ) has this general form: 

  • void ensureCapacity(int capacity)
 Here, capacity specifies the size of the buffer. 
setLength( ) 

To set the length of the buffer within a StringBuffer object, use setLength( ). Its general form is shown here: 
void setLength(int len) 
Here, len specifies the length of the buffer. 
This value must be nonnegative. When you increase the size of the buffer, null characters are added to the end of the existing buffer. If you call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost. 
 The setCharAtDemo sample program in the following section uses setLength( ) to shorten a StringBuffer.

StringBuffer in java

StringBuffer is a peer class of String that provides much of the functionality of strings.
As you know, String represents fixed-length, immutable character sequences. In contrast,
StringBuffer represents growable and writeable character sequences. StringBuffer
may have characters and substrings inserted in the middle or appended to the end.
StringBuffer will automatically grow to make room for such additions and often has
more characters preallocated than are actually needed, to allow room for growth. Java
uses both classes heavily, but many programmers deal only with String and let Java
manipulate StringBuffers behind the scenes by using the overloaded + operator.



StringBuffer Constructors
 
StringBuffer defines these three constructors:



  1. StringBuffer( )
  2. StringBuffer(int size)
  3. StringBuffer(String str)

The default constructor (the one with no parameters) reserves room for 16
characters without reallocation. The second version accepts an integer argument that
explicitly sets the size of the buffer. The third version accepts a String argument that
sets the initial contents of the StringBuffer object and reserves room for 16 more
characters without reallocation. StringBuffer allocates room for 16 additional
characters when no specific buffer length is requested, because reallocation is a costly
process in terms of time. Also, frequent reallocations can fragment memory. By
allocating room for a few extra characters, StringBuffer reduces the number of
reallocations that take place.

Tuesday, May 15, 2012

Invalid_Viewstate ... System.FormatException: Invalid length for a Base-64 char array.

We've been running an ASP.NET 1.1 application on 4 servers for 2 years and have been getting intermittent Viewstate exceptions reported through our exception publisher emails. These emails contain quite a lot of information about a request where an exception occurs, so I can provide lots of data about this problem.

First, you should know that I have searched far and wide for the solution to this problem and am convinced that the only solution is to disable Viewstatw MAC checking on all of our servers to make this go away. Naturally, I don't want to do this for security reasons.

Second, we have synchronized the <machineKey> elements on all four servers so we are using a 128-byte encryption key and a 48-byte decryption key and SHA1 hashing.All servers in the group have the exact same settings for <machineKey> and they are not overridden anywhere.

The symptom is this: one of our users navigates into our sales application and stops at some point in the process (gets up for a cup of coffee or whatever, or goes home for the night). When they resume the ordering process, they receive this error:

EDR.IDG.IDGWEBException: Invalid_Viewstate

System.FormatException: Invalid length for a Base-64 char array.
  at System.Convert.FromBase64String(String s)
  at System.Web.UI.LosFormatter.Deserialize(String input)
  at System.Web.UI.Page.LoadPageStateFromPersistenceMedium()
  --- End of inner exception stack trace ---
  at System.Web.UI.Page.LoadPageStateFromPersistenceMedium()
  at System.Web.UI.Page.LoadPageViewState()
  at System.Web.UI.Page.ProcessRequestMain()
  --- End of inner exception stack trace ---

I can reproduce this error and it does not occur under normal circumstances when people proceed through the application and close the browser, as far as I know.

Is there a time/date element to the encryption/decryption scheme that would render the Viewstate invalid after some period of time elapses? Does anyone have the solution to this problem?

Thanks.


Saturday, April 28, 2012

String Methods Added by Java 2, Version 1.4

Java 2, version 1.4 adds several methods to the String class. 
These are summarized in the following table.
StringBuffer StringBuffer is a peer class of String that provides much of the functionality of strings. As you know, String represents fixed-length, immutable character sequences. In contrast, StringBuffer represents growable and writeable character sequences. StringBuffer may have characters and substrings inserted in the middle or appended to the end. StringBuffer will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth. Java uses both classes heavily, but many programmers deal only with String and let Java manipulate StringBuffers behind the scenes by using the overloaded + operator.


StringBuffer Constructors


StringBuffer defines these three constructors: 

StringBuffer( ) StringBuffer(int size) StringBuffer(String str)


The default constructor (the one with no parameters) reserves room for 16 characters without reallocation. The second version accepts an integer argument that explicitly sets the size of the buffer. The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation. StringBuffer allocates room for 16 additional characters when no specific buffer length is requested, because reallocation is a costly process in terms of time. Also, frequent reallocations can fragment memory. By allocating room for a few extra characters, StringBuffer reduces the number of reallocations that take place.


length( ) and capacity( )


The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be found through the capacity( ) method. They have the following general forms:


int length( )    int capacity( )


 
// StringBuffer length vs. capacity.


class StringBufferDemo { 

public static void main(String args[]) { 

StringBuffer sb = new StringBuffer("Hello"); 

System.out.println("buffer = " + sb); System.out.println("length = " + sb.length());
 System.out.println("capacity = " + sb.capacity());
} }


Here is the output of this program, which shows how StringBuffer reserves extra space for additional manipulations: buffer = Hello length = 5 capacity = 21


 Since sb is initialized with the string “Hello” when it is created, its length is 5. Its capacity is 21 because room for 16 additional characters is automatically added.


ensureCapacity( )


If you want to preallocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer. ensureCapacity( ) has this general form:

 void ensureCapacity(int capacity) Here, capacity specifies the size of the buffer.


setLength( )
 To set the length of the buffer within a StringBuffer object, use setLength( ). Its general form is shown here: void setLength(int len) Here, len specifies the length of the buffer. This value must be nonnegative. When you increase the size of the buffer, null characters are added to the end of the existing buffer. If you call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost.


THE JAVA LIBRARY The setCharAtDemo sample program in the following section uses setLength( ) to shorten a StringBuffer.]


charAt( ) and setCharAt( )


The value of a single character can be obtained from a StringBuffer via the charAt( ) method. You can set the value of a character within a StringBuffer using setCharAt( ).


Their general forms are shown here: char charAt(int where) void setCharAt(int where, char ch) For charAt( ), where specifies the index of the character being obtained. For setCharAt( ), where specifies the index of the character being set, and ch specifies the new value of that character. For both methods, where must be nonnegative and must not specify a location beyond the end of the buffer.


The following example demonstrates charAt( ) and setCharAt( ):


// Demonstrate charAt() and setCharAt().

class setCharAtDemo {
 public static void main(String args[]) {
 StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);

System.out.println("charAt(1) before = " + sb.charAt(1)); sb.setCharAt(1, 'i');
 sb.setLength(2); System.out.println("buffer after = " + sb);

 System.out.println("charAt(1) after = " + sb.charAt(1));
 } }


 Here is the output generated by this program: buffer before = Hello charAt(1) before = e buffer after = Hi charAt(1) after = i

getChars( )


To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has this general form: void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart) Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from sourceStart through sourceEnd–1. The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring.

append( )


The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object. 


It has overloaded versions for all the built-in types and for Object. Here are a few of its forms:
 StringBuffer append(String str) StringBuffer append(int num) StringBuffer append(Object obj) String.valueOf( ) is called for each parameter to obtain its string representation. The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append( ). This allows subsequent calls to be chained together, as shown in the following example: // 
Demonstrate append().
class appendDemo {
 public static void main(String args[]) { String s; int a = 42; StringBuffer sb = new StringBuffer(40); s = sb.append("a = ").append(a).append("!").toString(); System.out.println(s); } } The output of this example is shown here: a = 42!
The append( ) method is most often called when the + operator is used on String objects. Java automatically changes modifications to a String instance into similar operations on a StringBuffer instance. Thus, a concatenation invokes append( ) on a StringBuffer object. After the concatenation has been performed, the compiler inserts a call to toString( ) to turn the modifiable StringBuffer back into a constant String. All of this may seem unreasonably complicated. Why not just have one string class and have it behave more or less like StringBuffer? The answer is performance. There are many optimizations that the Java run time can make knowing that String objects are immutable. Thankfully, Java hides most of the complexity of conversion between Strings and StringBuffers. Actually, many programmers will never feel the need to use StringBuffer directly and will be able to express most operations in terms of the + operator on String variables.





insert( )
 The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects. Like append( ), it calls String.valueOf( ) to obtain the string representation of the value it is called with. This string is then inserted into the invoking StringBuffer object. These are a few of its forms: StringBuffer insert(int index, String str) StringBuffer insert(int index, char ch) StringBuffer insert(int index, Object obj) Here, index specifies the index at which point the string will be inserted into the invoking StringBuffer object. The following sample program inserts “like” between “I” and “Java”: // Demonstrate insert().
class insertDemo

{ public static void main(String args[]) {
 StringBuffer sb = new StringBuffer("I Java!"); sb.insert(2, "like "); System.out.println(sb); } } The output of this example is shown here: I like Java!




reverse( )


You can reverse the characters within a StringBuffer object using reverse( ), shown here: StringBuffer reverse( ) This method returns the reversed object on which it was called. The following program demonstrates reverse( ): // Using reverse() to reverse a StringBuffer.
class ReverseDemo
{ public static void main(String args[]) {
 StringBuffer s = new StringBuffer("abcdef");
System.out.println(s); s.reverse(); System.out.println(s); } } Here is the output produced by the program: abcdef fedcba



delete( ) and deleteCharAt( )


 Java 2 added to StringBuffer the ability to delete characters using the methods delete( ) and deleteCharAt( ). These methods are shown here: StringBuffer delete(int startIndex, int endIndex) StringBuffer deleteCharAt(int loc) The delete( ) method deletes a sequence of characters from the invoking object. Here, startIndex specifies the index of the first character to remove, and endIndex specifies an index one past the last character to remove. Thus, the substring deleted runs from startIndex to endIndex–1. The resulting StringBuffer object is returned. The deleteCharAt( ) method deletes the character at the index specified by loc. It returns the resulting StringBuffer object. Here is a program that demonstrates 


the delete( ) and deleteCharAt( ) methods: 
 
// Demonstrate delete() and deleteCharAt() 

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

StringBuffer sb = new StringBuffer("This is a test."); sb.delete(4, 7); System.out.println("After delete: " + sb); sb.deleteCharAt(0); System.out.println("After deleteCharAt: " + sb); 
} } 

The following output is produced: After delete: This a test. After deleteCharAt: his a test.


replace( )

 Another method added to StringBuffer by Java 2 is replace( ).

 It replaces one set of characters with another set inside a StringBuffer object. Its signature is shown here: StringBuffer replace(int startIndex, int endIndex, String str) The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the substring at startIndex through endIndex–1 is replaced. The replacement string is passed in str. The resulting StringBuffer object is returned. 

The following program demonstrates replace( ): 

// Demonstrate replace()
class replaceDemo { 

public static void main(String args[]) 

StringBuffer sb = new StringBuffer("This is a test.");
 sb.replace(5, 7, "was"); System.out.println("After replace: " + sb); } } Here is the output: After replace: This was a test.


substring( )


Java 2 also added the substring( ) method, which returns a portion of a StringBuffer. It has the following two forms: String substring(int startIndex) String substring(int startIndex, int endIndex) The first form returns the substring that starts at startIndex and runs to the end of the invoking StringBuffer object.


StringBuffer Methods Added by Java 2, Version 1.4

Modifying a String

Modifying a String Because String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or use one of the following String methods, which will construct a new copy of the string with your modifications complete.


substring( )
You can extract a substring using substring( ). It has two forms. 
The first is 
String substring(int startIndex)
 Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string. 

The second form of substring( ) allows you to specify both the beginning and ending index of the substring: String substring(int startIndex, int endIndex) Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index.
The following program uses substring( ) to replace all instances of one substring with another within a string:


// Substring replacement.

 class StringReplace { 

public static void main(String args[])

  
String org ="This is a test. This is, too."; 
String search = "is";

 String sub = "was"; 

 String result = ""; int i; 


do {

// replace all matching substrings

  System.out.println(org);

   i = org.indexOf(search);
 if(i != -1)
 {
   result = org.substring(0, i);


   result = result + sub; result = result +   org.substring(i + 

search.length()); org = result;
 }

 }

 while(i != -1);

 } 
}


The output from this program is shown here: 

This is a test. This is, too. Thwas is a test. This is, too. Thwas 

was a test. This is, too. Thwas was a test. Thwas is, too. Thwas
 was a test. Thwas was, too.



concat()
You can concatenate two strings using concat( ), shown here: String concat(String str) This method creates a new object that contains the invoking string with the contents of str appended to the end. concat( ) performs the same function as +. For example,
 String s1 = "one"; String s2 = s1.concat("two");


puts the string “onetwo” into s2. It generates the same result as the following sequence: String s1 = "one"; String s2 = s1 + "two";


replace( )


The replace( ) method replaces all occurrences of one character in the invoking string with another character. It has the following general form: String replace(char original, char replacement) Here, original specifies the character to be replaced by the character specified by replacement. The resulting string is returned. For example, String s = "Hello".replace('l', 'w'); puts the string “Hewwo” into s.


trim()


The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. It has this general form: String trim( ) Here is an example: String s = " Hello World ".trim(); This puts the string “Hello World” into s. The trim( ) method is quite useful when you process user commands. For example, the following program prompts the user for the name of a state and then displays that state’s capital. It uses trim( ) to remove any leading or trailing whitespace that may have inadvertently been entered by the user.


// Using trim() to process commands.

 import java.io.*;
 class UseTrim
  {
   public static void main(Strinargs[])
      throws IOException {

 // create a BufferedReader using System.in

 BufferedReader br = new BufferedReader(new 
 InputStreamReader(System.in));

String str;

System.out.println("Enter 'stop' to quit.");
System.out.println("Enter State: ");

do 


str = br.readLine(); str = str.trim();

// remove whitespace 

if(str.equals("Illinois"))

System.out.println("Capital is 
Springfield.");

else if(str.equals("Missouri"))

System.out.println("Capital is Jefferson 
City.");

 else if(str.equals("California")) 
  System.out.println("Capital is Sacramento."); 
else if(str.equals("Washington")) 

System.out.println("Capital is Olympia.");

//
... } while(!str.equals("stop")); 
}
 }

Wednesday, April 4, 2012

Earn money online link:


http://www.rupeeinbox.com/register.asp?ref=5126673-30088

<a href="http://www.twodollarclick.com/index.php?ref=sanjaybhansali"><img
src="http://www.twodollarclick.com/earnBanner.php?username=sanjaybhansali"
border=0></a>


To work from Home

https://www.elance.com/s/sanjay_bhansali/?rid=279BG

Technical blog:

http://dreamit-sanjay.blogspot.com
http://mylinkguard.blogspot.com