Saturday, June 29, 2013

Sanjay Bhansali invites you to Freelancer.com

freelancer
freelancer elite
Sanjay Bhansali
wants you to join Freelancer.com - the world's largest outsourcing marketplace!
Sanjay I've been using Freelancer.com to hire talented professionals for a fraction of the cost, and to make money by completing work.
Accept Invitation

Unsubscribe from this mailing list.

Monday, April 1, 2013

Create android mobile application free

Create android moblie application online free by using following website :

www.appyet.com

I like this site. I sugget all my visiter for this site id u have not knowledge about amdroid programming..

Monday, July 23, 2012

Lexical Issues,Whitespace,Identifiers, Literals,Separators,The Java Keywords

--> Lexical Issues

Java programs are a collection of whitespace,identifiers, comments, literals, operators, separators, and keywords.

Whitespace

Control Statements in java

--> The if Statement

The Java if statement works much like the IF statement in any other language. Further,
it is syntactically identical to the if statements in C, C++, and C#. Its simplest form is
shown here:

if(condition) statement;

Here, condition is a Boolean expression. If condition is true, then the statement is
executed. If condition is false, then the statement is bypassed. Here is an example:

if(num < 100)
println("num is less than 100");
In this case, if num contains a value that is less than 100, the conditional expression
is true, and println( ) will execute. If num contains a value greater than or equal to 100,
then the println( ) method is bypassed.

 Java defines a full complement of relational operators
which may be used in a conditional expression. Here are a few:

Operator          Meaning
<                 Less than
>                 Greater than
==                   Equal to
Notice that the test for equality is the double equal sign.

Here is a program that illustrates the if statement:




/*
Demonstrate the if.
Call this file "IfSample.java".
*/
class IfSample {
public static void main(String args[]) {
int x, y;
x = 10;
y = 20;
if(x &lt; y) System.out.println("x is less than y");
x = x * 2;
if(x == y) System.out.println("x now equal to y");
x = x * 2;
if(x &gt; y) System.out.println("x now greater than y");
// this won't display anything
if(x == y) System.out.println("you won't see this");
}
}
The output generated by this program is shown here:
x is less than y
x now equal to y
x now greater than y


The for Loop


loop statements are an important part of nearly any programming language. Java is no exception. In fact, Java supplies a powerful assortment of loop constructs.
Perhaps the most versatile is the for loop. If you are familiar with C, C++, or C#, then
you will be pleased to know that the for loop in Java works the same way it does in
those languages. If you don’t know C/C++/C#, the for loop is still easy to use. The
simplest form of the for loop is shown here:

for(initialization; condition; iteration) statement;

In its most common form, the initialization portion of the loop sets a loop control
variable to an initial value. The condition is a Boolean expression that tests the loop
control variable. If the outcome of that test is true, the for loop continues to iterate. If it
is false, the loop terminates. The iteration expression determines how the loop control
variable is changed each time the loop iterates. Here is a short program that illustrates
the for loop:
/*
Demonstrate the for loop.
Call this file "ForTest.java".


class ForTest {
public static void main(String args[]) {
int x;
for(x = 0; x<10; x = x+1)
System.out.println("This is x: " + x);
}
}
This program generates the following output:
This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
This is x: 5
This is x: 6
This is x: 7
This is x: 8
This is x: 9

In this example, x is the loop control variable. It is initialized to zero in the initialization
portion of the for. At the start of each iteration (including the first one), the conditional
test x < 10 is performed. If the outcome of this test is true, the println( ) statement is
executed, and then the iteration portion of the loop is executed. This process continues
until the conditional test is false.

Thursday, July 19, 2012

A First Simple Java Program



Now that the basic object-oriented underpinning of Java has been discussed, let’s
look at some actual Java programs. Let’s start by compiling and running the short
sample program shown here. As you will see, this involves a little more work than
you might imagine.

/*
This is a simple Java program.
Call this file "Example.java".
*/

class Example {
// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("This is a simple Java program.");
}
}
Entering the Program

 For most computer languages, the name of the file that holds the source code to a program is arbitrary. However, this is not the case with Java. The first thing that you must learn about Java is that the name you give to a source file is very important. For this example, the name of the source file should be Example.java. Let’s see why. In Java, a source file is officially called a compilation unit. It is a text file that contains one or more class definitions. The Java compiler requires that a source file use the .java filename extension. Notice that the file extension is four characters long. As you might guess, your operating system must be capable of supporting long filenames. This means
that DOS and Windows 3.1 are not capable of supporting Java. However, Windows
95/98 and Windows NT/2000/XP work just fine.
As you can see by looking at the program, the name of the class defined by the
program is also Example. This is not a coincidence. In Java, all code must reside inside
a class. By convention, the name of that class should match the name of the file that
holds the program. You should also make sure that the capitalization of the filename
matches the class name. The reason for this is that Java is case-sensitive. At this point,
the convention that filenames correspond to class names may seem arbitrary. However,
this convention makes it easier to maintain and organize your programs.

Compiling the Program
To compile the Example program, execute the compiler, javac, specifying the name of
the source file on the command line, as shown here:

C:\>javac Example.java

The javac compiler creates a file called Example.class that contains the bytecode version
of the program. As discussed earlier, the Java bytecode is the intermediate representation
of your program that contains instructions the Java interpreter will execute. Thus, the
output of javac is not code that can be directly executed.
To actually run the program, you must use the Java interpreter, called java. To do
so, pass the class name Example as a command-line argument, as shown here:

C:\>java Example

When the program is run, the following output is displayed:

This is a simple Java program.

When Java source code is compiled, each individual class is put into its own output
file named after the class and using the .class extension. This is why it is a good idea to
give your Java source files the same name as the class they contain—the name of the
source file will match the name of the .class file. When you execute the Java interpreter
as just shown, you are actually specifying the name of the class that you want the
interpreter to execute. It will automatically search for a file by that name that has
the .class extension. If it finds the file, it will execute the code contained in the
specified class.

Object-Oriented Programming

Object-oriented programming is at the core of Java. In fact, all Java programs are objectoriented—
this isn’t an option the way that it is in C++, for example. OOP is so integral
to Java that you must understand its basic principles before you can write even simple
Java programs. Therefore, this chapter begins with a discussion of the theoretical aspects
of OOP.
Two Paradigms
As you know, all computer programs consist of two elements: code and data. Furthermore,
a program can be conceptually organized around its code or around its data. That is,
some programs are written around “what is happening” and others are written around
“who is being affected.” These are the two paradigms that govern how a program is
constructed. The first way is called the process-oriented model. This approach characterizes
a program as a series of linear steps (that is, code). The process-oriented model can be
thought of as code acting on data. Procedural languages such as C employ this model to
considerable success. However, as mentioned in Chapter 1, problems with this approach
appear as programs grow larger and more complex.
To manage increasing complexity, the second approach, called object-oriented
programming, was conceived. Object-oriented programming organizes a program around
its data (that is, objects) and a set of well-defined interfaces to that data. An object-oriented
program can be characterized as data controlling access to code. As you will see, by switching
the controlling entity to data, you can achieve several organizational benefits.
Abstraction
An essential element of object-oriented programming is abstraction. Humans manage
complexity through abstraction. For example, people do not think of a car as a set of
tens of thousands of individual parts. They think of it as a well-defined object with its
own unique behavior. This abstraction allows people to use a car to drive to the grocery
store without being overwhelmed by the complexity of the parts that form the car. They
can ignore the details of how the engine, transmission, and braking systems work. Instead
they are free to utilize the object as a whole.


A powerful way to manage abstraction is through the use of hierarchical classifications.
This allows you to layer the semantics of complex systems, breaking them into more
manageable pieces. From the outside, the car is a single object. Once inside, you see
that the car consists of several subsystems: steering, brakes, sound system, seat belts,
heating, cellular phone, and so on. In turn, each of these subsystems is made up of more
specialized units. For instance, the sound system consists of a radio, a CD player, and/or
a tape player. The point is that you manage the complexity of the car (or any other
complex system) through the use of hierarchical abstractions.

 The Three OOP Principles
All object-oriented programming languages provide mechanisms that help you implement
the object-oriented model. They are encapsulation, inheritance, and polymorphism.
Let’s take a look at these concepts now.

Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates,
and keeps both safe from outside interference and misuse. One way to think about
encapsulation is as a protective wrapper that prevents the code and data from being
arbitrarily accessed by other code defined outside the wrapper. Access to the code
and data inside the wrapper is tightly controlled through a well-defined interface.
To relate this to the real world, consider the automatic transmission on an automobile.
It encapsulates hundreds of bits of information about your engine, such as how much
you are accelerating, the pitch of the surface you are on, and the position of the shift
lever. You, as the user, have only one method of affecting this complex encapsulation:
by moving the gear-shift lever. You can’t affect the transmission by using the turn signal
or windshield wipers, for example. Thus, the gear-shift lever is a well-defined (indeed,
unique) interface to the transmission. Further, what occurs inside the transmission does
not affect objects outside the transmission. For example, shifting gears does not turn
on the headlights! Because an automatic transmission is encapsulated, dozens of car
manufacturers can implement one in any way they please. However, from the driver’s
point of view, they all work the same. This same idea can be applied to programming.
The power of encapsulated code is that everyone knows how to access it and thus
can use it regardless of the implementation details—and without fear of unexpected
side effects.
In Java the basis of encapsulation is the class. Although the class will be examined
in great detail later in this book, the following brief discussion will be helpful now. A
class defines the structure and behavior (data and code) that will be shared by a set of
objects. Each object of a given class contains the structure and behavior defined by the
class, as if it were stamped out by a mold in the shape of the class. For this reason, objects
are sometimes referred to as instances of a class. Thus, a class is a logical construct; an
object has physical reality.
When you create a class, you will specify the code and data that constitute that
class. Collectively, these elements are called members of the class. Specifically, the data
defined by the class are referred to as member variables or instance variables. The code
that operates on that data is referred to as member methods or just methods. (If you are
familiar with C/C++, it may help to know that what a Java programmer calls a method,
a C/C++ programmer calls a function.) In properly written Java programs, the methods
define how the member variables can be used. This means that the behavior and interface
of a class are defined by the methods that operate on its instance data.

Inheritance
Inheritance is the process by which one object acquires the properties of another object.
This is important because it supports the concept of hierarchical classification. As
mentioned earlier, most knowledge is made manageable by hierarchical (that is, top-down)
classifications. For example, a Golden Retriever is part of the classification dog, which
in turn is part of the mammal class, which is under the larger class animal. Without the
use of hierarchies, each object would need to define all of its characteristics explicitly.
However, by use of inheritance, an object need only define those qualities that make it
unique within its class. It can inherit its general attributes from its parent. Thus, it is the
inheritance mechanism that makes it possible for one object to be a specific instance of
a more general case. Let’s take a closer look at this process.

Polymorphism 

Polymorphism (from the Greek, meaning “many forms”) is a feature that allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation. Consider a stack (which is a last-in, first-out list). You might have a program that requires three types of stacks. One stack is used for integer values, one for floating-point values, and one for characters. The algorithm that implements each stack is the same, even though the data being stored differs. In a non– object-oriented language, you would be required to create three different sets of stack routines, with each set using different names. However, because of polymorphism, in Java you can specify a general set of stack routines that all share the same names. More generally, the concept of polymorphism is often expressed by the phrase “one interface, multiple methods.” This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler’s job to select the specific action (that is, method) as it applies to each situation. You, the programmer, do not need to make this selection manually. You need only remember and utilize the general interface.

Sunday, July 8, 2012

append( ) in java

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 areimmutable. 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.

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

Wednesday, March 28, 2012

Data Conversion Using valueOf( )

The valueOf( ) method converts data from its internal format into a human-readable
form. It is a static method that is overloaded within String for all of Java’s built-in types,
so that each type can be converted properly into a string. valueOf( ) is also overloaded
for type Object, so an object of any class type you create can also be used as an argument.
(Recall that Object is a superclass for all classes.) Here are a few of its forms:


static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ])

As we discussed earlier, valueOf( ) is called when a string representation of some
other type of data is needed—for example, during concatenation operations. You can call
this method directly with any data type and get a reasonable String representation. All
of the simple types are converted to their common String representation. Any object that
you pass to valueOf( ) will return the result of a call to the object’s toString( ) method. In
fact, you could just call toString( ) directly and get the same result.
For most arrays, valueOf( ) returns a rather cryptic string, which indicates that it
is an array of some type. For arrays of char, however, a String object is created that
contains the characters in the char array. There is a special version of valueOf( ) that
allows you to specify a subset of a char array. It has this general form:

static String valueOf(char chars[ ], int startIndex, int numChars)
Here, chars is the array that holds the characters, startIndex is the index into the array of
characters at which the desired substring begins, and numChars specifies the length of
the substring.

Changing the Case of Characters
Within a String


The method toLowerCase( ) converts all the characters in a string from uppercase to
lowercase. The toUpperCase( ) method converts all the characters in a string from
lowercase to uppercase. Nonalphabetical characters, such as digits, are unaffected.
Here are the general forms of these methods:

String toLowerCase( )
String toUpperCase( )


Both methods return a String object that contains the uppercase or lowercase
equivalent of the invoking String.
Here is an example that uses toLowerCase( ) and toUpperCase( ):


// Demonstrate toUpperCase() and toLowerCase().

class ChangeCase {
public static void main(String args[])
{
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}
The output produced by the program is shown here:
Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.

Tuesday, March 27, 2012

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(String args[])
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"));
}
}

Searching Strings

The String class provides two methods that allow you to search a string for a specified
character or substring:

■ indexOf( )      Searches for the first occurrence of a character or substring.
■ lastIndexOf( )  Searches for the last occurrence of a character or substring.


These two methods are overloaded in several different ways. In all cases, the methods
return the index at which the character or substring was found, or –1 on failure.
To search for the first occurrence of a character, use

int indexOf(int ch)

To search for the last occurrence of a character, use

int lastIndexOf(int ch)
Here, ch is the character being sought.

To search for the first or last occurrence of a substring, use

int indexOf(String str)
int lastIndexOf(String str)


Here, str specifies the substring.

You can specify a starting point for the search using these forms:

int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)

Here, startIndex specifies the index at which point the search begins. For indexOf( ),

the search runs from startIndex to the end of the string. For lastIndexOf( ), the search
runs from startIndex to zero.
The following example shows how to use the various index methods to search
inside of Strings:

// Demonstrate indexOf() and lastIndexOf().


class indexOfDemo {
public static void main(String args[]) {
String s = "Now is the time for all good men " +
"to come to the aid of their country.";
System.out.println(s);
System.out.println("indexOf(t) = " +
s.indexOf('t'));
System.out.println("lastIndexOf(t) = " +
s.lastIndexOf('t'));
System.out.println("indexOf(the) = " +
s.indexOf("the"));
System.out.println("lastIndexOf(the) = " +
s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " +
s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " +
s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " +
s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " +
s.lastIndexOf("the", 60));
}
}

Here is the output of this program:
Now is the time for all good men to come to the aid of their country.

indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55