Showing posts with label Java String. Show all posts
Showing posts with label Java String. Show all posts

Friday, 19 June 2015

Java StringBuffer Class

StringBuffer is a peer class of String that provides much of the functionality of Strings. In contrast to String, 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 pre-allocated than are actually needed, to allow room for growth.

Few important point related to StringBuffer class

  • StringBuffer is an Object like String.
  • StringBuffer class is also final like String class.
  • StringBuffer objects are mutable (can be modified) unlike String objects.

Constructors of StringBuffer Class


Methods of StringBuffer Class



Example:

class SBDemo1

{ public static void main(String args[])

{ StringBuffer sb1 = new StringBuffer();

System.out.println("sb1: length: "+sb1.length() + " capacity: " + sb1.capacity());

StringBuffer sb2 = new StringBuffer(100);

System.out.println("sb2: length: "+sb2.length() + " capacity: " + sb2.capacity());

StringBuffer sb3 = new StringBuffer("Hello");

System.out.println("sb3: length: "+sb3.length() + " capacity: " + sb3.capacity());

sb1.ensureCapacity(200);

System.out.println("sb1: length: "+sb1.length() + " capacity: " + sb1.capacity());

sb3.setLength(10);

System.out.println("sb3: length: "+sb3.length() + " capacity: " + sb3.capacity());

System.out.println("sb3: "+sb3);

sb3.setLength(3);

System.out.println("sb3: length: "+sb3.length() + " capacity: " + sb3.capacity());

System.out.println("sb3: "+sb3);

}

}

Output:

sb1: length: 0 capacity: 16

sb2: length: 0 capacity: 100

sb3: length: 5 capacity: 21

sb1: length: 0 capacity: 200

sb3: length: 10 capacity: 21

sb3: Hello

sb3: length: 3 capacity: 21

sb3: Hel

append() Method

It has overloaded versions for all the built-in types and for Object. These are the few of its form:

public StringBuffer append(char c)

public StringBuffer append(String str)

public StringBuffer append(boolean b)

public StringBuffer append(Object obj)

public StringBuffer append(int num)

public StringBuffer append(double

public StringBuffer append(char[] str)

public StringBuffer append(StringBuffer sb)

String.valueOf() method 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.

Note: If null string is appended then “null” gets appended.

insert() Method

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() method, it calls String.valueOf() method to obtain the string representation of the argument passed to it. This string is then inserted into the invoking StringBuffer object. These are the few of its form:

public StringBuffer insert(int offset, char c)

public StringBuffer insert(int offset, int c)

public StringBuffer insert(int offset, long l)

public StringBuffer insert(int offset, char[] str)

public StringBuffer insert(int offset, double d)

public StringBuffer insert(int offset, float f)

public StringBuffer insert(int offset, String str)

public StringBuffer insert(int offset, Object obj)

Example: The following example illustrates some of the methods discussed above.

class SBDemo2

{ 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);

StringBuffer sb1=new StringBuffer("I Java!");

sb1.insert(2, "like ");

System.out.println(sb1);

System.out.println("Reverse of "+sb1+" is: "+sb1.reverse());

}

}

Output:

a= 42!

I like Java!

Reverse of I like Java! is: !avaJ ekil I

Monday, 15 June 2015

Java String important methods

Character Extraction Methods

The String class provides a number of ways in which characters can be extracted from a String object. Although the characters that comprise string within a String object cannot be indexed as if they were a character array, many of the String methods employ an index (or offset) into the string for their operation. Like arrays, the string indexes begin at zero.


Example: The following example illustrates the use of character extraction methods discussed above:

class ExtractionDemo

{ public static void main(String args[])

{ String s = "This is a Demo of character extraction methods";

char c = s.charAt(10);

System.out.println("Character at position 10: " + c);

char carray[] = s.toCharArray();

System.out.print("Character Array: ");

for(int i=0; i<carray.length; i++)

System.out.print(carray[i]);

System.out.println();

byte b[] = s.getBytes();

System.out.print("Byte Array: ");

for(int i=0; i<b.length; i++)

System.out.print((char) b[i]);

System.out.println();

int start = 10; int end = 14;

char buf[] - new char[end-start];

s.getChars(start, end, buf, 0);

System.out.println(buf);

}

}

Output:


Character at position 10: D

Character Array: This is a Demo of character extraction methods

Byte Array: This is a Demo of character extraction methods

Demo

String Comparison Methods



The regionMatches() method compares a specific region inside a styring with another specific region in another string. Thre is an overloaded form that allows you to ignore case in such comparisions.

For both versions, startIndex specifies the index at which the region begins within the invoking string object. The string being compared is specified by str2. The index at which the comparison will starts within the str2 is specified by str2StartIndex. The length of the substring being compared is passed in len.

Example: The following example illustrates the use of regionMatches() method.

class Region

{ public static void main(String args[])

{ String s="Yahoo!";

String s2="yahoo.com";

System.out.println(s.regionMatches(0,s2,0,5));

System.out.println(s.regionMatches(true,0,s2,0,5));//ignore case

System.out.println(s.resionMatches(-1,s2,-1,5));

}

}

Output:

false

true

false

Example: The following example illustrates the use of compareTo() method.

class CompareToDemo

{ public static void main(String args[])

{ String s="yahoo!";

String s2="Yahoo!";

String s3="yahoo";

System.out.println(s.compareTo(s2));

System.out.println(s.compareToIgnoreCase(s2));//ignore case

System.out.println(s.compareTo(s3));

}

}

Output:

32

0

1

startsWith( ) and endsWith( )


Example: The following example illustrates the use of startsWith() and endsWith() methods.

class ComparisonDemo

{ public static void main(String args[])

{ String name="Rahul Jain Januthariya";

System.out.println(name.startsWith("Rahul"));

System.out.println(name.startsWith("rahul"));

System.out.println(name.endsWith("Januthariya"));

System.out.println(name.startsWith("Jain",7));

}

}

Output:

true

false

true

true

The equals( ) v/s = =

The equals() method compares the characters inside a String object. The == compares two object references to see whether they refer to the same instance.

String Search Methods

String class provides methods that allow you to search a string for a specified character or substring. In all cases, methods return the index at which the character or substring is found or –1 on failure.


Methods for String Modification

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.





Note: The substring() methods throw IndexOutOfBoundsException if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.




Java Special String operations

1. String Literals

For each String literal in your program java automatically constructs String object. Thus, you can use a string literal to initialize a String object.

String s = “abc”;

Because a String object is created for every string literal, you can use a string literal at any place you can use a String object.

For example, you can call methods directly on a quoted string as it uses an object reference.

System.out.println(“abc”.length());

2. String Concatenation


In general, Java does not allow operators to be applied to String objects. The one exception to this rule is + operator, which concatenates two strings producing a String object as a result.

Example: The reference of the concatenated string “Rahul Jain Januthariya” will be stored in the reference variable name.

String name = “Rahul” + “ ”  +  “Jain”  +  “ ” + “Januthariya”

String Concatenation with other data types

If a string is concatenated with any data of type other than the string, the compiler converts the other operand (non-string) to its string equivalent.

Example:

String s = “four: “+ 2 + 2 ; System.out.println(s);

Output: four:22

String Conversion and toString( )

When Java converts data into its String representation during concatenation, it does so by calling one of the overloaded versions of the String conversion method valueOf() defined by String class. The valueOf() is a static method overloaded for all simple types and for type Object.

For the simple types, valueOf() returns string that contains the human-readable equivalent of the value with which it is called. For objects, valueOf() calls the toString() method on the object.

Every class inherits toString(), because it is defined by the Object class. However, the default implementation of the toString() is seldom sufficient. It displays name of the class followed by symbol “@” and then object-id (e.g. Box@ab1232), which is normally of no use. For most important classes that you create, you will want to override toString() and provide your own string representations.

You can do so by overriding the toString( ) method:

String toString()

Example:

class Box

{ double w, h, d;

Box( double w, double h, double d)

{ this.w=w; this.h=h; this.d=d;

}

public String toString()

{ return "Dimensions are "+w+" by "+h+" by "+d+".";

}

class ToStringDemo1

{ public static void main(String args[])

{ Box b=new Box(10,12,14);

String s="Box b: "+b; //concates box object

System.out.println(b);

System.out.println(s);

}

}

Output:

Dimensions are 10.0 by 12.0 by 14.0.

Box b: Dimensions are 10.0 by 12.0 by 14.0

Note: If toString() is not overridden, the output of this program will be something like:

Box@b8df17

Box b: Box@b8df17

Java String Constructors

The class String supports many constructors to create String objects. The simplest way to

construct a string is to assign a literal value to a String type variable:

String str = "This is a string";

The above statement will create a string object with the specified contents.

Some of the commonly used constructors are described below:

String()


Initializes a newly created String object so that it represents an empty character sequence:

String str = new String();

String (String str)

Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.

Examples:

String str = new String("This is a string");

String str1 = new String(str);

The string str1 is a copy of string str. Although contents are same but str and str1 point to different string objects.

String(char[] value)

Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.

Example: String str in the following example will hold “abc”.

char cr[] = { ‘a’,’b’,’c’};

            String str = new String (cr);

String(char value[], int offset, int count)

Allocates a new String that contains characters from a sub-array of the character array argument.

Example: String str in the following example will hold “cde”.

char cr[] = { ‘a’,’b’,’c’,’d’,’e’,’f’ };

            String s = new String (cr,2,3);

String(byte b[])

Constructs a new String by decoding the specified array of bytes using the platform's default charset.

String(byte[]  b, int offset, int length)

Constructs a new String by decoding the specified subarray of bytes using the platform's default charset.

Even though Java's char type uses 16 bits to represent the Unicode character set, the typical format for strings on the Internet uses arrays of 8-bit bytes constructed from the ASCII character set. Because 8-bit ASCII strings are common, the String class provides constructors that initialize a string when given a byte array. In each of the above constructors the byte to character
conversion is done by using the default character encoding of the platform.

Example: The following example illustrates the use of the constructors, which convert byte array into string.

class SubStringCons

{ public static void main(String args[])

{ byte ascii[] = { 65,66,67,68,69,70 };

String s = new String (ascii);

System.out.println(s);

String s1 = new String (ascii, 2, 3);

System.out.println(s1);

}

}

Output:

ABCDEF

CDE

Java String introduction

The classes String and StringBuffer are part of the java.lang package.

(i) String in Java is an Object

String is a sequence of characters. But, unlike many other languages that implement strings as character arrays, Java implements strings as objects of type String.

Implementing strings as built in objects allows java to provide a full complement of features that make string handling convenient. Also string objects can be constructed a number of ways, making it easy to obtain a string when needed.

(ii) Strings are Immutable

Strings are immutable i.e. you cannot change the string after creation. However, a variable declared as a String reference can be changed to point at some other String object at any time.

You can still perform all types of string operations. Each time you need an altered version of an existing string, a new string object is created that contains the modifications. The original string is left unchanged. This approach is used because fixed, immutable strings can be implemented more efficiently than changeable ones. For those cases in which a modifiable string is desired, there is a companion class called StringBuffer, whose objects contain strings that can be
modified after they are created.

(iii) String class is final

Both String and StringBuffer classes are final. This allows certain optimizations that increase performance of common string operations as discussed in the previous chapter on modifiers.