Friday, 16 January 2015

Strings in java


String:-
A String represents a group of characters.
ex:- name,address,credit card no,etc..,
In java, any string is object of String class. String class is used to create string object.

String class methods:-

String class belongs to java.lang package.
1.String concat(String str):-
concatenates the calling string with str.
   note:- '+' will also do the same.
ex:-  String s1="hydera"; String s2 = "bad";
String s3 = s1.concat(s2);
o/p: hyderabad
2.int length():-
Returns the length of the string.
String s1 = "Vijayawada";
int n = s1.length();  o/p: 10
3.char charAt(int i):-
It extracts only one character from given String.That      character at the same ith place.
ex: String s1 = "Vijayawada";
  s1.charAt(3)   -->  o/p:  a
4.int compareTo(String str):-    (case sensitive)
(or)
 int compareToIgnoreCase(String str):-  (case insensitive)
They are used to compare two strings.

ex: st1="HELLO",String st2 ="hello";
int n=st1.compareToIgnoreCase(st2);
if(n==0)
System.out.println("given strings are equal");
else if (n>0)
System.out.println("1st str >2nd str");
else
System.out.println("1st str < 2nd str");
o/p:  both are equal
5.boolean equals(String str):- (case sensitive)
(or)
 boolean equalsIgnoreCase(String str):-   (case insensitive)
It returns true if the calling string equals to str.

ex :   String st1 ="hello",st2="HELLO";
st1.equals(st2)    -> o/p : false
st1.equalsIgnoreCase(st2)    -> o/p : true
6.boolean startsWith(String prefix):-
It returns true if the calling string starts with prefix(begins)
prefix - sub string (or) not.
String s1="hyderabad" ;
if(s1.startsWith("hy"))  --->   o/p:  true
7.boolean endsWith(String suffix):-
It returns true if the invoking string ends with suffix.
String s1="hyderabad" ;
if(s1.endsWith("hy"))  --->   o/p:  false
Note:- The above two methods use case sensitive comparison.

8.int indexOf(String str):-
It returns the position number of substring in the main String.So we have to pass substring. It returns the first occurance of str in the string.
EX:- String str="This is a book"
int n = str.indexOf("is");
o/p :- n = 2
9.int lastIndexOf(String str):-
It returns last Occurance in the string.
String str="This is a book"
int n = str.lastIndexOf("is");
o/p :- n = 5
10.String replace(char oldchar,char newchar):-
It returns a new String that is obtained by replacing all     characters of 'oldchar' in string with 'newchar'.
String str="This is a book";
String str1= str.replace('i','l');
                  o/p: s.o.pln(str1) -->  Thls ls a book.   
11.String substring(int beginIndex):-
It ruturns a new String consisting of all characters from      beginindex until the end of the String.
String str="This is a book";
String str1= str.substring(5);
s.o.pln(str1)---> "is a book"
12.String substring(int beginIndex,int endIndex):-
It returns a new String consisting all characters from          beginindex until endindex(exclusive).
String str="This is a book";
String str1= str.substring(8,13);
s.o.pln(str1) --->  "a boo"
13.String toLowerCase():-
It converts all characters into lowercase and returns.
14.String toUpperCase():-
IT converts all characters into uppercase and returns.
15.String trim():-
It eleminates all leading and trailing spaces.
String str="  book  ";
String str1= str.trim();
s.o.pln(str.length()) ---> 8
s.o.pln(str1.length()) ---> 4


How to create String object?

1.We can declare a String type variable and initialize it directly     with a group of characters.
ex:- String st = "Hello";
2.We can create a String object using new operator and pass a group of    characters to the object.
ex:- String s1 = new String("java");
3.We can create a character array into a string by passing it to the    String object.
ex:- char arr[] = {'c','h','a','i','r','s'};
String s2 = new String(arr);
ex:- String s3 = new String(arr,1,4);
o/p: hair
There are two ways to create String object:
  1. By string literal
  2. By new keyword
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 returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.
string objects are immutable.
  1. class Simple{  
  2. public static void main(String args[]){  
  3.   String s="Good";  
  4.   s.concat(" Morning");//concat() method appends the string at the end  
  5.   System.out.println(s);//will print Sachin because strings are immutable objects  
  6. }  
  7. }  
Output:Good
two objects are created but s reference variable still refers to "Sachin" not to "Sachin Tendulkar".

if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object.
  1. class Simple{  
  2. public static void main(String args[]){  
  3.   String s="Good";  
  4.   s=s.concat(" Morning");  
  5.   System.out.println(s);  
  6. }  
  7. }  
Output:Good Morning
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not modified

String comparison in Java

authentication (by equals() method),
sorting (by compareTo() method),
reference matching (by == operator) etc.

1. By equals() method


equals() method compares the original content of the string.It compares values of string for equality.String class provides two methods:
  • public boolean equals(Object another){} compares this string to the specified object.
  • public boolean equalsIgnoreCase(String another){} compares this String to another String, ignoring case


  1. class Simple{  
  2. public static void main(String args[]){  
  3.   
  4.   String s1="Sachin";   
  5.   String s3=new String("Sachin");  
  6.   System.out.println(s1.equals(s3));//true  
  7. }  
  8. }  
Output:true


  1. class Simple{  
  2. public static void main(String args[]){  
  3.   
  4.   String s1="Sachin";  
  5.   String s2="SACHIN";  
  6.  
  7.   System.out.println(s1.equals(s2));//false  
  8.   System.out.println(s1.equalsIgnoreCase(s3));//true  
  9. }  
  10. }  
Output:false
      true

2) By == operator

The = = operator compares references not values.
  1. //<b><i>Example of == operator</i></b>  
  2.  
  3. class Simple{  
  4. public static void main(String args[]){  
  5.   
  6.   String s1="Sachin";  
  7.   String s2="Sachin";  
  8.   String s3=new String("Sachin");  
  9.  
  10.   System.out.println(s1==s2);//true (because both refer to same instance)  
  11.   System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)  
  12. }  
  13. }  
Output:true
      false

3) By compareTo() method:

compareTo() method compares values and returns an int which tells if the values compare less than, equal, or greater than.
Suppose s1 and s2 are two string variables.If:
  • s1 == s2 :0
  • s1 > s2   :positive value
  • s1 < s2   :negative value

//<b><i>Example of compareTo() method:</i></b>  
 
class Simple{  
public static void main(String args[]){  
  String s1="xxx";  
  String s2="xxx";  
  String s3="yyy";  
  System.out.println(s1.compareTo(s2));//0  
  System.out.println(s1.compareTo(s3));//1(because s1>s3)  
  System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )  
}  
}  
Output:0
      1
      -1


String Concatenation in Java


There are two ways to concat string objects:
  1. By + (string concatenation) operator
  2. By concat() method

1) By + (string concatenation) operator

String concatenation operator is used to add strings.For Example:
//Example of string concatenation operator  
 class Simple{  
public static void main(String args[]){  
 String s="Good"+" Mrng";  
 System.out.println(s);  
}  
}  
Output:Good Mrng

2) By concat() method

concat() method concatenates the specified string to the end of current string.
Syntax:public String concat(String another){}
//<b><i>Example of concat(String) method</i></b>  
 
class Simple{  
public static void main(String args[]){  
   String s1="Sachin ";  
  String s2="Tendulkar";  
  String s3=s1.concat(s2);  
  System.out.println(s3);//Sachin Tendulkar  
 }  
}  
Output:Sachin Tendulkar


Substring in Java


public String substring(int startIndex):
public String substring(int startIndex,int endIndex):

//Example of substring() method  
 
class Simple{  
public static void main(String args[]){  
  String s="Sachin Tendulkar";  
  System.out.println(s.substring(6));//Tendulkar  
  System.out.println(s.substring(0,6));//Sachin  
}  
}  
Output:Tendulkar
      Sachin


HashCode :
Hash code is a unique id number given to every object by the     JVM. #code is also called as reference number.
ex:- To compare two strings.
 String s1 =  new String("Hello");
 String s2 = "Hello";
Now JVM follow:-
if( s1 == s2 ) returns not same.
because it compares reference of Object.
if( s1.equals(s2)) returns same.

String constant pool :

It is a block of memory where string objects are stored by JVM when we are trying to create the string objects.
   Here if(s1==s2) then it gives same. when
             s1= "hello"   s2 = "hello".

Types of Objects:-
There are 2 types.
1.Mutable
2.Immutable
1.Mutable:-
A mutable object is an object where content can be modified.
2.Immutable:-
An immutable object is an object whose content can not be modified.

=>String objects are immutable.

StringBuffer class:

this class is available in java.lang package.
->this is a mutable object.
--> we can change the content of the StringBuffer objects by the methods available in that class.

Creating StringBuffer objects:-

1.StringBuffer sb = new StringBuffer("hello");
2.StringBuffer sb = new StringBuffer(50);
3.StringBuffer sb = new StringBuffer();

java.lang.StringBuffer methods:-

1)StringBuffer append(x):-
=> x may be int,float,double,char,String (or) StringBuffer.It will be appended to the calling StringBuffer.
2)StringBuffer insert(int index,x):-
=> x may be int,float,double,char,String (or) StringBuffer.It will be inserted into the StringBuffer at specified index.
3)StringBuffer delete(int start,int end):-
Removes the characters from start to end position.
4)StringBuffer reverse():-
It reverses the all characters in the StringBuffer.
5)String toString():-
Converts the StringBuffer into the String.
purpose:- converts StringBuffer to string class.
6)int length():-
returns the length of the StringBuffer.
7)int indexOf(String str):-
It returns the first position
8)int lastIndexOf(String str):-
=> It returns the last Occurance of substring 'str' in the StringBuffer object.

The StringBuffer class is used to created mutable (modifiable) string.

StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously .So it is safe and will result in an order.


Commonly used Constructors of StringBuffer class:

  1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
  2. StringBuffer(String str): creates a string buffer with the specified string.
  3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length
class A{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello ");  
sb.append("Java");//now original string is changed  
System.out.println(sb);//prints Hello Java  
}  
}  


class A{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello ");  
sb.insert(1,"Java");//now original string is changed  
System.out.println(sb);//prints HJavaello  
}  
}  


class A{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello");  
sb.replace(1,3,"Java");  
System.out.println(sb);//prints HJavalo  
}  
}  



StringBuilder class:

This class is available in java.lang package.
This class has been added in jdk1.5.0 which has same features like StringBuffer class.These objects are also mutable as are the StringBuffer objects.

Difference between StringBuffer and StringBuilder classes :

The StringBuilder class is used to create mutable (modifiable) string. The StringBuilder class is same as StringBuffer class except that it is non-synchronized.
.When the programmer wants to use several threads,he should use StringBuffer as it gives reliable results.If only one thread is used,StringBuilder is prefered,as it improves execution time.

Commonly used Constructors of StringBuilder class:

  1. StringBuilder(): creates an empty string Builder with the initial capacity of 16.
  2. StringBuilder(String str): creates a string Builder with the specified string.
  3. StringBuilder(int length): creates an empty string Builder with the specified capacity as length.\
class A{  
public static void main(String args[]){  
StringBuilder sb=new StringBuilder("Hello ");  
sb.append("Java");//now original string is changed  
System.out.println(sb);//prints Hello Java  
}  
}


The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.
class Student{  
int rollno;  
String name;  
String city;  
Student(int rollno, String name, String city){  
this.rollno=rollno;  
this.name=name;  
this.city=city;  
}  
public static void main(String args[]){  
Student s1=new Student(101,"a","x");  
Student s2=new Student(102,"b","y");  
System.out.println(s1);//compiler writes here s1.toString()  
  System.out.println(s2);//compiler writes here s2.toString()  
}  
}  
Output:Student@1fee6fc
      Student@1eed786


class Student{  
int rollno;  
String name;  
String city;  
 
Student(int rollno, String name, String city){  
this.rollno=rollno;  
this.name=name;  
this.city=city;  
}  
  
public String toString(){//overriding the toString() method  
 return rollno+" "+name+" "+city;  
}  
public static void main(String args[]){  
  Student s1=new Student(101,"Ramu","x");  
  Student s2=new Student(102,"Vijjy","y");  
    
  System.out.println(s1);//compiler writes here s1.toString()  
  System.out.println(s2);//compiler writes here s2.toString()  
}  
}  
Output:101 Ramu x
      102 Vijjy y



StringTokenizer in Java


This class is available in java.util package.
By using this class we can get the string values from a large string using some tokens( tokens may be separated by special characters called as delimiters(i.e *,.,/,:,-,....)).
This class contains SPACE as the default delimiter.

The java.util.StringTokenizer class allows you to break a string into tokens
Syntax
 1)StringTokenizer stk=new StringTokenizer(string);
  -> in the above case 'space' is treated as default delimiter.
 2)StringTokenizer stk=new StringTokenizer(string,deimiter);
ex:  StringTokenizer stk=new StringTokenizer("127.0.0.1",".");

Constructors

StringTokenizer(String str)-creates StringTokenizer with specified string.
StringTokenizer(String str, String delim)- creates StringTokenizer with specified string and delimeter.
StringTokenizer(String str, String delim, boolean returnValue)- creates StringTokenizer with specified string, delimeter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate token
methods :
1) hasMoreTokens() :
it returns boolean whether it consists of tokens or not.
2) nextToken() :
it returns a string value of the existing token.


QUESTIONS

1.   Java provides two different string classes from which string objects can be instantiated. What are they?
A - The two classes are:
String
StringBuffer
2.   StringBuffer class is used for strings that are not allowed to change. The String class is
used for strings that are modified by the program: True or False. If false, explain why.
A - False. This statement is backwards. The String class is used for strings that are not allowed to change. The StringBuffer class is used for strings that are modified by the program.
3 - While the contents of a String object cannot be modified, a reference to a String object can be caused to point to a different String object: True or False. If false, explain why.
A - True.
4 - The use of the new operator is required for instantiation of objects of type String: True or False? If false, explain your answer.
A - False. A String object can be instantiated using either of the following statements:
String str1 = new String("String named str2");
String str2 = "String named str1";
5 - The use of the new operator is required for instantiation of objects of type StringBuffer: True or False? If false, explain your answer.
A - True.
6 - Provide a code fragment consisting of a single statement showing how to use the Integer wrapper class to convert a string containing digits to an integer and store it in a variable of type int.
A - See code fragment below
int num = new Integer("3625").intValue();
7 - Explain the difference between the capacity() method and the length() methods of the StringBuffer class.
A - The capacity() method - returns the amount of space currently allocated for the StringBuffer object.
The length() - method returns the amount of space used.
To find length of a string
8 - The following is a valid code fragment: True or False? If false, explain why.
StringBuffer str6 = new StringBuffer("StringBuffer named str6".length());
A - True.
9 - Which of the following code fragments is the most efficient, first or second?
String str1 = "THIS STRING IS NAMED str1";
String str1 = new String("THIS STRING IS NAMED str1");
A - The first code fragment is the most efficient.

No comments:

Post a Comment