Wednesday 10 October 2012


String Handling in JAVA

String Handling is an important part of any programming language.
String
Strings are widely used in JAVA Programming, are a sequence of characters. String Class is defined in java.lang package so it is implicitly available for all programs

String class has following features:-
  • It is Final class
  • Due to Final, String class can not be inherited.
  • It Extends object class.
  • It implements Serializable, Comparable and CharSequence interfaces.
  • It is immutable.
  • It is also a datatype in java

String Example 1:Creating new String
String a=”Ashish”; 
String b=new String(); 
String c=new String(“Ashish”);

String Example 2:Comparing String
String a=”Ashish”;
String b=”Ashish”;
String c=new String(“Ashish”);
if(a==b) System.out.println(“Same reference “); 
if(a==c) System.out.println(“Same Reference of A and C “); 
else System.out.println(“Not Same Reference “);

There are two ways to create a String object in Java- 
1.Using the new operator. For example, 
String str1 = new String("Ashish");. 
2.Using a string literal. For example, 
String str2="Ashish"; (string literal) 

But these both "Ashish" have different reference. So if we compare str1 & str2, this is not equal. because str1 is created using new operator.

This diagram show the difference-


String Class Methods & Example
Click here

StringBuffer Class in JAVA
The java.lang.StringBuffer classes should be used when you have to make a lot of modifications to strings of characters. As,String objects are immutable , so if you choose to do a lot of manipulations with String Objects, you will end up with a lot of abandoned String objects in the String pool.

StringBuffer Example
StringBuffer sb=new StringBuffer(“Hiiii”);
sb.append(“Javacup”);
System.out.println(sb); //HiiiiJavacup

No comments:

Post a Comment