String & String buffer class in java

                 String  & String  buffer class in java  


Before starting with string and string buffer class lets get te concept about string .

                                                        What is string..? 

we can say that string is a sequence of characters so induvidually charactes make a string .
OR we can say that string is an array of characters.

Suppose we take an example how we did in c and c++

char a[5]="hii"; OR char a[]={'s','t','r','i','n','g',};

so java stated a new concept about storing strings 

Java gave a readymade class for storing string they 

1) string class 
2)string buffer class 

Normally whatever we write in java that is the sequence of charater represent the object of string class. 

As usual we write some string in java keep in mind that is the object representing string class .

And that string is immutable i.e. cannot be altered or we can say cannot be modified once written gets final "No changes can be done to it"

So to change we have two methods 
1)Either you can make a new string object by writing a new string 
2)Use string buffer class .

So first difference indicated that why two bifurcations are made by string class you cannot change or modify the string and by using string buffer class we can modify the string .

Java String provides a lot of concepts that can be performed on a string such as compare, concat, equals, split, length, replace, compareTo, intern, substring etc.

An array of characters works same as java string. For example:
  1. char[] ch={'j','a','v','a'};  
  2. String s=new String(ch);  
The java.lang.String class implements SerializableComparable and CharSequence interfaces.

How to create String object?

There are two ways to create String object:
  1. By string literal
  2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

String S= "java"

Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:

String S= "java"

String Sp= "java"

The refrence is the same for both the string so will not assign the new one only one copy of the string will be created .

Here i would like to say about the difference of 
1) = =
2)equals operator

== operator checks wheather both the string has same refrence or not if the refrence are same then returns true else false .

where as equals operator says that what is written in both string is same thing or not if same characters than return true and if not returns false so both the keyword have same return type that is boolean and boolean occupies one bit for storage either true or false so either 0 or 1.

String objects are stored in a special memory area known as string constant pool.


2) By new keyword

example String S= new string("hello java");

Java provides some methods for string 

list of methods 

No.MethodDescription
1char charAt(int index)returns char value for the particular index
2int length()returns string length
3static String format(String format, Object... args)returns formatted string
4static String format(Locale l, String format, Object... args)returns formatted string with given locale
5String substring(int beginIndex)returns substring for given begin index
6String substring(int beginIndex, int endIndex)returns substring for given begin index and end index
7boolean contains(CharSequence s)returns true or false after matching the sequence of char value
8static String join(CharSequence delimiter, CharSequence... elements)returns a joined string
9static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)returns a joined string
10boolean equals(Object another)checks the equality of string with object
11boolean isEmpty()checks if string is empty
12String concat(String str)concatinates specified string
13String replace(char old, char new)replaces all occurrences of specified char value
14String replace(CharSequence old, CharSequence new)replaces all occurrences of specified CharSequence
15String trim()returns trimmed string omitting leading and trailing spaces
16String split(String regex)returns splitted string matching regex
17String split(String regex, int limit)returns splitted string matching regex and limit
18String intern()returns interned string
19int indexOf(int ch)returns specified char value index
20int indexOf(int ch, int fromIndex)returns specified char value index starting with given index
21int indexOf(String substring)returns specified substring index
22int indexOf(String substring, int fromIndex)returns specified substring index starting with given index
23String toLowerCase()returns string in lowercase.
24String toLowerCase(Locale l)returns string in lowercase using specified locale.
25String toUpperCase()returns string in uppercase.
26String toUpperCase(Locale l)returns string in uppercase using specified locale.

All these methods are provided by java.lang.String class

String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method.

StringBuffer class doesn't override the equals() method of Object class.

Some methods taken in brief
                                              Java String charAt
  • The java string charAt() method returns a char value at the given index number. The index number starts from 0.
  • syntax public char charAt(int index)

     Parameter

  • index : index number, starts with 
program

  1. public class CharAtHAHAHA{  
  2. public static void main(String args[]){  
  3. String name="I love java";  
  4. char ch=name.charAt(4);//returns the char value at the 4th index  
  5. System.out.println(ch);  
  6. }}  

                                          Java String compareTo

The java string compareTo() method compares the given string with current string .It returns positive number, negative number or 0.

  1. s1 > s2 => positive number  
  2. s1 < s2 => negative number  
  3. s1 == s2 => 0  

Syntax 
  1. public int compareTo(String second string)  

Parameters

second string : represents string that is to be compared with current string,returns an integer value

  1. public class simpleexample{  
  2. public static void main(String args[]){  
  3. String s1="hello";  
  4. String s2="hello";  
  5. String s3="mello";  
  6. String s4="hemlo";  
  7. System.out.println(s1.compareTo(s2));  
  8. System.out.println(s1.compareTo(s3));  
  9. System.out.println(s1.compareTo(s4));  
  10. }}  

Here s1 and s2 will be 0 .

                                              Java String concat

  The java string concat() method combines specified string at the end of this string. It          returns combined string. It is like appending another string.

  1. public String concat(String second string)  
  2. Parameter

    second String : another string i.e. to be combined at the end of this string.
  3. Returns

    combined string

example

  1. public class ConcatExample{  
  2. public static void main(String args[]){  
  3. String s1="java string";  
  4. s1.concat("hifi");  
  5. System.out.println(s1);  
  6. s1=s1.concat(" hii");  
  7. System.out.println(s1);  
  8. }}  

                                                  Java String indexOf

The java string indexOf() method returns index of given character value or substring. If it is not found, it returns -1. The index counter starts from zero.

There are 4 types of indexOf method in java. The signature of indexOf methods are given below:
No.MethodDescription
1int indexOf(int ch)returns index position for the given char value
2int indexOf(int ch, int fromIndex)returns index position for the given char value and from index
3int indexOf(String substring)returns index position for the given substring
4int indexOf(String substring, int fromIndex)returns index position for the given substring and from index

Parameters

ch: char value i.e. a single character e.g. 'a'
fromIndex: index position from where index of the char value or substring is retured
substring: substring to be searched in this string .

examples of it are easy not going in it. keeping in mind all are instance method so call with the string object...!!

Another method is lastIndexof(parameters)

same is the case as in the index of but returns the indexof last character that is say we input a string HAHAHA now H and A are appearing say we find for H then by using the indexof method we will get the first occurence of H that is 0th index but if we find by the way of lastIndexof method we get 4th index.

                                                Java String isEmpty

The java string isEmpty() method checks if this string is empty. It returns true, if length of string is 0 otherwise false.
The isEmpty() method of String class is included in java string since JDK 1.6.
  1. public boolean isEmpty()  
Some methods of string buffer class 

                             StringBuffer insert() method

The insert() method inserts the given string with this string at the given position.
  1. class A{  
  2. public static void main(String args[]){  
  3. StringBuffer sb=new StringBuffer("Hello ");  
  4. sb.insert(1,"Java");//now original string is changed  
  5. System.out.println(sb);//prints HJavaello  
  6. }  
  7. }  

                                            StringBuffer replace() method

The replace() method replaces the given string from the specified beginIndex and endIndex.

  1. class A{  
  2. public static void main(String args[]){  
  3. StringBuffer sb=new StringBuffer("Hello");  
  4. sb.delete(1,3);  
  5. System.out.println(sb);//prints Hlo  
  6. }  
  7. }  

                                          StringBuffer reverse() method

The reverse() method of StringBuilder class reverses the current string.

  1. class A{  
  2. public static void main(String args[]){  
  3. StringBuffer sb=new StringBuffer("Hello");  
  4. sb.reverse();  
  5. System.out.println(sb);//prints olleH  
  6. }  
  7. }  

                                           StringBuffer capacity() method

The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

                                            StringBuffer ensureCapacity() method

The ensureCapacity() method of StringBuffer class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.


ALL the methods are instance methods so "With object"..!!

This was all about string and string buffer class .

Comments

Popular posts from this blog

State space search / blocks world problem by heuristic approach /TIC TAC TOE

Navigation in Vaadin.

Drag and drop items from one Grid to another