Wednesday, 24 December 2014

What is String class or String Handling in java

String Handling:

String Handling provides a lot of concepts that can be performed on a string such as concatinating string, comparing string, substring etc.In java, string is basically an immutable object.Immutable means unmodifiable object.

String:

Normally string is a sequence of characters. But in java, string is an object. String class is used to create string object.

In Java you can create String By two Ways:

>1. By string literal
>2. By new keyword

By string literal:

In string literal you can create string object by double quote.

For Example:

String name="vishwa";
String company="TCS";
String college="KEC";

Note:Actually JVM create string literal object in a memory area known as string constant pool which is a part of heap memory area.
each time when you create a string object by string literal first JVM check string constant pool for that string if present in the string
constant pool then JVM will not create new object it return  reference of that  old object.if it dose not present in the string constant pool
then it create new object and place in the string constant poll area.

For Example:

String name="vishwa";
String ename="vishwa";

Here no new object will be created only one object is created in string constant pool and both name and ename reference variable refer to that  vishwa(single object) in the memory.

Why java uses concept of string literal ?

To make Java more memory efficient (because no new objects are created if it exists already in string constant pool area).


By new keyword:

String name=new String("vishwa");

In such case, JVM will create a new String object in normal(nonpool) Heap memory and the literal "vishwa" will be placed in the string constant  pool.The variable name will refer to the object in Heap(nonpool).

As you know String is an immutable Object so here immutable means.....

In Java immutable means unmodifiable object.

For Exampale: 

class Test{
public static void main(String []args){
String name="vishwa";
name.concat(" roop ");
System.out.println(name);
   }
}

Output: vishwa

As you can see in the above example that two objects are created but no reference variable refers to"vishwa roop".But if we explicitely assign it to the reference variable, it will refer to "vishwa roop" object.

For example:

class Test{
public static void main(String []args){
String name="vishwa";
name=name.concat(" roop");
System.out.println(name);
  }
}

Output: vishwa roop

Que) Why string objects are immutable in java ?

Ans: Because java uses the concept of string literal.Suppose there are 10 reference variables,all referes to one object "vishwa".If one reference  variable changes the value of the object,it will be affected to all the others reference variables.That is why string objects are immutable in java
so that now can change the value once created.


String Concatenation:

In Java you can concat string objects by two ways:

>1. By + (string concatenation) operator
>2. By concat() method


>1. By + (string concatenation) operator:

String concatenation operator is used to add strings.
For Example:

class Test{
public static void main(String []args){
String name="vishwa"+" roop";
System.out.println(name);
  }
}

Output: vishwa roop

Note: String concatenation operator produces a new string by appending the second operand onto the end of the first operand.The string concatenation  operator can concat not only string but primitive values also.

For Example:

class Test{
public static void main(String args[]){

String name=10+20+"vishwa"+30+40;
System.out.println(name);
  }
}

Output: 30vishwa3040

Note:If either operand is a string, the resulting operation will be string concatenation. If both operands are numbers, the operator will perform an addition.

>2. By concat() method:

concat() method concatenates the specified string to the end of current string.

Syntax: public String concat(String another){  }

class Test{
public static void main(String []args){
String name="vishwa ";
String lname="roop";
String fname=name.concat(lname);
System.out.println(fname);
  }
}

Output: vishwa roop 


String comparison:

There are three ways to compare String objects:

>1. By equals() method
>2. By = = operator
>3. By compareTo() method

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

For Exampale no.1 :

class Test{
public static void main(String [] args){
String name="vishwa";
String name1="vishwa";
String name3=new String("vishwa");
String name4="roop";
System.out.println(name.equals(name1));
System.out.println(name1.equals(name2));
System.out.println(name3.equals(name4));
   }
}

Output: true
              true
              true
              false

For Example no.2

class Test{
public static void main(String []args){
String name="vishwa";
String cname="VISHWA";
System.out.println(name.equals(name));
System.out.println(name.equalsIgnoreCase(cname));
   }
}


Output: false
               true

>2. By == operator:

The = = operator compares references(means memory address of the object in the heap )  not values.

For Example:  

class Test{
public static void main(String []args){

String name="vishwa";
String name1="vishwa";
String name2=new String("vishwa");
System.out.println(name==name1);
System.out.println(name1=name2);
  }
}


Output: true
              false

>3. By compareTo() method:

compareTo() method compares values and returns an int  which tells the difference between ASCII value of the character value is equal,less or greater than. Suppose name and name1 are two string variables.If:

Suppose s1 and s2 are two string variables.If:

name == name1  then 0
name > name1 then positive value
name < name1 then negative value

For Exampale:

class Test{
public static void main(String args[]){
String name="vishwa";
String name1="vishwa";
String name2="roop";
System.out.println(name.compareTo(name1));
System.out.println(name.compareTo(name2));
System.out.println(name2.compareTo(name));
  }
}

Output: 0
                4
              -4


Commonaly used methods of String class:

>1.public boolean equals(Object obj)-----------------------> Compares this string to the specified object.
>2.public boolean equalsIgnoreCase(String another)--------->Compares this String to another String, ignoring case.
>3.public String concat(String str)------------------------>Concatenates the specified string to the end of this string.
>4.public int compareTo(String str)------------------------> Compares two strings and returns int
>5.public int compareToIgnoreCase(String str)-------------->Compares two strings, ignoring case differences.
>6.public String substring(int beginIndex)------------------> Returns a new string that is a substring of this string.
>7.public String substring(int beginIndex,int endIndex)----->Returns a new string that is a substring of this string.
>8.public String toUpperCase()------------------------------> Converts all of the characters in this String to upper case
>9.public String toLowerCase()------------------------------> Converts all of the characters in this String to lower case.
>10.public String trim()------------------------------------>Returns a copy of the string, with leading and trailing whitespace omitted.
>11.public boolean startsWith(String prefix)----------------> Tests if this string starts with the specified prefix.
>12.public boolean endsWith(String suffix)------------------> Tests if this string ends with the specified suffix.
>13.public char charAt(int index)---------------------------> Returns the char value at the specified index.
>14.public int length()-------------------------------------> Returns the length of this string.
>15.public String intern()----------------------------------> Returns a canonical representation for the string object.


Some  example of the above methods:

toUpperCase() and toLowerCase() method:

class Test{
public static void main(String []args){
String name="vishwa";
System.out.println(name.toLowerCase());
System.out.println(name.toUpperCase());
System.out.println(name);
  }
}


Output: vishwa
                VISHWA
                 vishwa


trim() method:

class Test{
public static void main(String []args){
String name=" vishwa ";
System.out.println(name);
System.out.println(name.trim());
   }
}

Output:  vishwa
                 vishwa


startsWith() and endsWith() method:

class Test{
public static void main(String []args){
String name="vishwa";
System.out.println(name.startsWith("vi"));
System.out.println(name.startsWith("wa"));
  }
}

Output: true
                 true


charAt() and length() method:

class Test{
public static void main(String []args){
String name="vishwa";//012345(index)
System.out.println(name.charAt(1));
System.out.println(name.charAt(5));

System.out.println("length is =="+name.length());
    }
}

Output: i
                a
 length is ==6

intern() method:

A pool of strings,initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned.  Otherwise, this String object is added to the pool and a reference to this String object is returned.

For Exampale:

class Test{
public static void main(String args[]){
String name=new String("vishwa");
String name1=name.intern();
System.out.println(name1);
  }
}

Output: vishwa



toString() method of String class:

If you want to represent any object as a string, toString() method is used. The toString() method returns the string representation of  the object. If you print any object, java compiler internally invokes the toString() method on that object.So overriding the toString()  method, returns the desired output, it can be the state of an object etc. depends on your implementation.

Advantage of the toString() method:

By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.

Problem without toString() method:

class Employee{
int eid;
String ename;
String company;
Employee(int eid, String ename, String company){
this.eid=eid;
this.ename=ename;
this.company=company;
}
public static void main(String args[]){

Employee e1=new Employee(111,"vishwa","gorakhpur");
Employee e2=new Employee(222,"Virat","delhi");
System.out.println(e1);
System.out.println(e2);
  }
}

Output: Employee@19821f
                Employee@addbf1


As you can see in the above example, printing e1 and e2 prints the hashcode values of the objects but I want to print the values of these objects. Since java compiler internally calls toString() method, overriding this method will return the specified values. Let's understand  it with the example given below:

Understanding the actual use of toString() method:

class Employee{
int eid;
String ename;
String company;
Employee(int eid, String ename, String company){
this.eid=eid;
this.ename=ename;
this.company=company;
}
public String toString()
 {
return eid+" "+ename+' "+company;
 }
public static void main(String args[]){

Employee e1=new Employee(111,"vishwa","gorakhpur");
Employee e2=new Employee(222,"Virat","delhi");
System.out.println(e1);
System.out.println(e2);
  }
}

Output: 111 vishwa gorakhpur
                222 virat delhi




substring method of String class:

You can get substring from the given String object by one of the two methods:

>1.public String substring(int startIndex):   This method returns new String object containing the
 substring of the given string from specified startIndex (inclusive).
>2.public String substring(int startIndex,int endIndex): This method returns new String object
 containing the substring of the given string from specified startIndex to endIndex.

In case of string:
startIndex: starts from index 0(inclusive).
endIndex: starts from index 1(exclusive).

For Example:

class Test{
public static void main(String args[]){
          Sachin Tendulkar
String s="vishwa roop";
System.out.println(s.substring(5));
System.out.println(s.substring(0,5));
   }
}

Output: roop
              vishwa



How to create Immutable class in Java ?


There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes  and String class is immutable. We can also create immutable class by creating final class that have final data members.

For Example:

In this example, we have created a final class named Student. It have one final datamember, a parameterized constructor and getter method.

public final class Student{
final String rollno;
public Student(String rollno){
this.rollno=rollno;
}
public String getRollno(){
return rollno;
  }
}


The above class is immutable because:

The instance variable of the class is final i.e. we cannot change the value of it after creating an object.
The class is final so we cannot create the subclass.There is no setter methods i.e. we have no option to change the value of the instance variable. These points makes this class as immutable class.










No comments:

Post a Comment