Archive for February, 2010
OOPS/JAVA : StringBuffer
by hkesavaraju on Feb.27, 2010, under Java
StringBuffer
It is a peer class of String that provides string functionality. It is a growable and changeable character sequences.
I. StringBuffer constructors: (i) StringBuffer(): It allocates room for 16 characters without reallocation and is the default constructor.
(ii) StringBuffer(int size): It takes string buffer size as an argument size.
-
StringBuffer(String str): It sets its initial contents as argument string str and allocates 16 more characters without reallocation.
It has length() which returns the number of characters in given string buffer where as capacity() returns total allocated capacity for a given string.
II. Modification Methods: These methods when performed in a given string buffer object that reflects in original string buffer object.
-
append(): It concatenates any other type of data to the end of invoking string. It’s versions are:
-
Stringbuffer append(String str)
-
Stringbuffer append(int num)
-
Stringbuffer append(Object obj)
-
-
insert(): It inserts one string into another. It’s forms as follows:
-
StringBuffer insert(int index, char ch): It inserts character ch at specified index .
-
StringBuffer insert(int index, String str): It inserts string str at specified index .
-
StringBuffer insert(int index, Object obj): It inserts object obj at specified index .
-
-
reverse(): It returns reverse of the characters in given StringBuffer object.
It’s form is StringBuffer reverse()
-
delete() and deletecharAt(): Its forms are
a)StringBuffer delete(int StartIndex, int endIndex) : It removes the characters in an invoking string from startIndex to endIndex-1.
b) StringBuffer deleteChatAt(int loc) : It deletes the character specified at loc index in an invoking string.
(v) replace(): It’s from is StringBuffer replace(int StartIndex, int endIndex, String str) replaces in a given string from startIndex to endIndex-1 with str.
(vi) substring(): IT returns portion of a StringBuffer object. It’s forms are
-
String substring(int startIndex): It returns a portion of string from startIndex to last index.
-
String substring(int startIndex, int endIndex): It returns a portion of string from startIndex to endIndex.-1.
OOPS/JAVA:String Handling
by hkesavaraju on Feb.27, 2010, under Java
String Handling: Java considers string as an Object where as it is treated as array of characters in many other languages. A string is a sequence of characters.
Once a string is created, that can’t be changed. It is possible to perform all types of string operations but a new string is created that contains the altered version of the string each time when a modification is performed. Therefore, a string is a fixed, immutable character sequence.
The String and Stringbuffer are defined in java.lang package. These are available to all programs automatically. Both are declared as final, so they never be sub classed.
2.15.1 String: It can be created through 3 constructors.
(i) String s=new String() means s is instance of string is created with no parameters.
(ii) String s=new String(Char[]) where a character array is initialized to string instance s.
Example is :
char c[]={‘a’,’b’,’c’};
String s=new String( c ); which initializes abc to string stance s.
(iii)String s=new String(char c[],int SI,int numchars) where numchars indicatenumber of characters to read from a character array from starting index SI in c[] .
Example is: char c[]={‘a’,’b’,’c’,’d’,’e’,’f’};
String s=new String(c,2,3}; produces cde
String also have constructors that take array of bytes as argument.
-
String(byte ac[])
-
String(byte ac[],int SI,int numchars)
There is a method length() that tells the number of characters in a string.
I. Character Extraction Methods: There are a number of methods to extract characters from a gven string.
(i) charAt(): it returns the character at the specified index or location in a given string. It’s general form is char charAt(int where) .
(ii) getChars(): It extracts the characters from a given string from SourceStsrt to SourceEnd and this is copied to target array from targetStart. It’s general from is
getChars(int SourceStart, int SourceEnd,char target[],int targetEnd).
-
getBytes(): It stores that characters in an array of bytes. It’s general form is byte[] getBytes(); It can be used where the applications use 8 bit ASCII.
-
toCharArray(): It converts all the characters in a given string into a character array.
II. String comparision methods: These are used to compare strings or substrings within strings.
-
equals() & equalsIgnoreCase(): It returns true when the invoking string contain same characters as in argument string str. It’s general form is Boolean equals(String str) where as Boolean equalsIgnoreCase(String str) returns true if invoking string ignored case difference with argument string str and contain same characters in same order. It treats alphabets A-Z to be same as a-z.
-
regionMatches(): It is used to compare a specific region in invoking string with another specific region in the another string. It’s first form is
a) boolean regionMatches(int StartIndex, String str2,int str2StartIndex,int numchars)
b) boolean regionMatches(boolean ignoreCase, int StartIndex, String str2,int str2StartIndex,int numchars)
In both cases, StartIndex specifies invoking string from starting index StartIndex is compared to str2 string from str2StartIndex and the number of characters are compared are indicated by numchars.
In second form, if ignoreCase is true, invoking string is compared with str2 by ignoring cases.
-
startsWith() and endsWith():
-
startsWith() returns true when invoking string begins with a specified string( argument string).It’s general form is boolean startsWith(String str)
The second form is boolean startsWith(String str, int StartIndex) searches from specified index from invoking string.
-
endsWith() returns true when invoking string ends with specified string. It’s general form is boolean endsWith(String str)
-
equals() versus ==: equals() compares all characters of two strings but == checks two object references refer to same instance.
-
compareTo(): It returns 0 if invoking string and argument string are identical or less than 0 if the invoking string comes before the argument string in the dictionary order or greater than 0 if invoking string comes after the argument string in the dictionary order. It’s general form is int compareTo(String str)
III. Searching Strings: String class has two methods to search for specified character or substring in an invoking string.
-
indexOf(): It searches for first occurrence of character or substring in a given string.
-
int indexOf(char ch): gives the first occurrence of character in a given string.
-
int indexOf(String str): gives the first occurrence of substring in a given string.
-
lastIndexOF(): It searches for last occurrence of a character or substring in a given string.
-
int lastindexOf(char ch): gives the last occurrence of character in a given string.
-
int lastindexOf(String str): gives the ending occurrence of substring in a given string.
-
IV. String modification Methods: There are some important methods that alters the string and that can be stored in a new string.
-
substring(): It takes part of given string. It’s forms are
-
String substring(int startindex): it returns the substring from startingindex to last index in an invoking string.
-
String subString(int startindex,int endindex): It gives a portion of a string from startindex to endindex-1.
-
An example is: s=”this a test”.
String s1=s.subString(1,4) returns his.
-
concat(): It is used to concatenate two strings. It’s general from is String concat(String s)
Example is: String s1=”one”;
String s2=s1.concat(“two”); gives “onetwo” to s1.
-
replace(): It replaces all occurrences of one character in a invoking string with another character. It’s general form is String replace(char original, char replacement)
Example is : String s=”Hello”.replace(‘l’,’w’) gives “hewwo” to s.
-
trim(): It returns an absolute string by removing any leading and trailing white spaces in an invoking string. It’s general form is String trim()
Example is String s=” Hello World “.trim() gives “Hello World”.
OOPS/JAVA:Constructors
by hkesavaraju on Feb.27, 2010, under Java
Constructors: It is tedious to initialize all the variables of a class when each time an instance is created or also using methods in a class. This work made simpler by placing all of the set up done at the time the object is first created. Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor.
A constructor has same name as class name in which it resides and is syntactically similar to a method. Once defined, constructor is called immediately after the creation of its object. Constructors have no return type, not even void because the implicit return type of a class constructor is the class type itself.
Properties of constructor:
-
It can be invoked when its class object is created first time.
-
It don’t have return type.
-
It is syntactically similar to a method.
-
It has same name as its class name.
The following program illustrates the constructor which is invoked automatically when an object is constructed.
class box
{
double w,h,d;
box()
{
System.out.println(“constructing box”);
w=h=d=10;
}
double volume()
{
return w*h*d;
}
class boxdemo
{
public static void main(String args[])
{
box m1=new box();
box m2=new box();
double vol;
vol=m1.volume();
System.out.println(“volume is”+vol);
vol=m2.volume();
System.out.println(“volume is”+vol);
}
}
Output:
constructing box
constructing box
volume is 1000.0
volume is 1000.0
In above code, m1 & m2 were initialized by box constructor when they are created.
The syntax for calling the constructor by the creation of object is
class-var=new classname();
The parentheses are needed after the classname because constructor for the class is called.
2.11.1 Parameterized constructors: These are constructors but takes parameters as arguments.
This concept is needed when a way to create objects of various dimensions. The following program illustrates parameterized constructors.
class box
{
double w,h,d;
box(double w1,double h1,double d1)
{
w=w1;
h=h1;
d=d1;
}
double volume()
{
return w*h*d;
}
}
class boxdemo
{
public static void main(String args[])
{
box m1=new box(2,3,4);
box m2=new box(10,20,30);
double vol;
vol=m1.volume();
System.out.println(“volume of m1 is”+vol);
vol=m2.volume();
System.out.println(“volume of m2 is”+vol);
}
}
Output:
volume of m1 is 24.0
volume of m2 is 6000.0
In the above code, the creation of m1 object invokes box(2,3,4) constructor which in turn assigns 2,3,4 to box variables w, h & d. Similarly, the creation of m2 object invokes box(10,20,30) constructor which assigns 10,20 & 30 to box variables w, h & d respectively.
2.11.2 Constructor overloading: Like overloading normal methods, constructor methods can also be overloaded. It means several constructors in the same class has same name but differ in the number and type of arguments.
Observe a situation where the class box has a constructor as box(double w1,double h1,double d1), then the object declaration should take three parameters, then only the constructor in box is called.
Suppose the object declaration like box ob=new box(); is done, it raises an error and it will not call box() constructor with three arguments.
Java allows constructors to overload in the same class which solves these problems.
The following program illustrates constructor overloading:
class box
{
double w,h,d;
box()
{
w=h=d=-1;
}
box(double w1,double h1,double d1)
{
w=w1;
h=h1;
d=d1;
}
box(double len)
{
w=h=d=len;
}
double volume()
{
return w*h*d;
}
}
class oconstructordemo
{
public static void main(String args[])
{
box m1=new box(2,3,4);
box m2=new box();
box m3=new box(4);
double vol;
vol=m1.volume();
System.out.println(“volume of m1 is”+vol);
vol=m2.volume();
System.out.println(“volume of m1 is”+vol);
vol=m3.volume();
System.out.println(“volume of m1 is”+vol);
}
}
Output:
volume of m1 is 24.0
volume of m1 is -1.0
volume of m1 is 64.0
In the above code, the proper constructor is called based on parameters passed in the object declaration.