Monday, February 16, 2015

Strings and String Builder

In this Section we are going to see what is Strings and String builders and different kind of operations performed on Strings. Strings are immutable that is once created it cannot be changed and the next change occurs and stored in a different object. However in string builders that is not the case Strings are mutable it can be changed. Please follow the below example for more details


package Example1;

import java.util.Arrays;

public class StringOperations {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  String name="Albert Einstein";
  
  //CharAt
  System.out.println("Character at "+name.charAt(3));
  //uppercase;
  System.out.println("Uppercase "+name.toUpperCase());
  //concat
  System.out.println(name.concat("ka"));
  System.out.println(name);
  
  //equals and equalsignorecase
  if(name.equals("Albert Einstein")){
   System.out.println("its is true");
  }
  
  if(name.equalsIgnoreCase("Albert Einstein")){
   System.out.println("ignores the case ");
  }
  //string contains
  System.out.println("Contains the string " +name.contains("ber"));
  
  //index of
  System.out.println("Index of e is  "+name.indexOf("e"));
  
  //length of the string
  System.out.println("length of String is "+name.length());
  
  //Replace
  System.out.println("Repalce string "+name.replace("A", "Dr A"));
  
  
  //creation of string builder
  StringBuilder names=new StringBuilder("Charles Darwin");
  //append operation
  System.out.println("Uppercase "+names.append("ka"));
  System.out.println(names);
  
  //capacity
  System.out.println(names.capacity());
  
 }

}


output:
Character at e
Uppercase ALBERT EINSTEIN
Albert Einsteinka
Albert Einstein
its is true
ignores the case
Contains the string true
Index of e is 3
length of String is 15
Repalce string Dr Albert Einstein
Uppercase Charles Darwinka
Charles Darwinka
30

>>>Final
------------------------------------------------------------------------------------------------------------