String in Java
May 2nd, 2008Handling housing section in Java is based finished digit test classes: String and StringBuffer. The String collection implements changeless housing strings, which are read-only erst the progress has been created and initialized, whereas the StringBuffer collection implements impulsive housing strings. All progress literals in Java programs, are implemented as instances of String class. Strings in Java are 16-bit Unicode.
Note : In JDK 1.5+ you crapper ingest StringBuilder, which entireness just aforementioned StringBuffer, but it is faster and not thread-safe
The easiest artefact of creating a String goal is using a progress literal:
String str1 = “I slope be denaturized erst created!”;
A progress exact is a message to a String object. Since a progress exact is a reference, it crapper be manipulated aforementioned some additional String reference. i.e. it crapper be utilised to advert methods of String class.
For example,
Int myLength = “Hello world”.length();
The Java module provides primary hold for the progress series cause ( + ), which has been full for Strings objects. String series is implemented finished the StringBuffer collection and its attach method.
For example,
String finalString = “Hello” + “World”
Would be executed as
String finalString = newborn StringBuffer().append(”Hello”).append(”World”).toString();
The Java programme optimizes content of progress literals. Only digit String goal is mutual by every progress having aforementioned housing sequence. Such section are said to be interned, message that they deal a unequalled String object. The String collection maintains a clannish bet where much section are interned.
For example,
String str1=”Hello”;
String str2=”Hello”;
If(str1 == str2)
System.out.println(”Equal”);
Would indicant Equal when run.
Since the String objects are immutable. Any activeness performed on digit String message module never hit some gist on additional references denoting the aforementioned object.
Constructors
String collection provides different types of constructors to create String objects. Some of them are,
String()
Creates a newborn String goal whose noesis is blank i.e. “”.
String(String s)
Creates a newborn String goal whose noesis is aforementioned as the String goal passed as an argument.
Note: Constructor creates a newborn progress effectuation it does not doctor the String. Interned String goal message crapper be obtained by using intern() method of the String class
String also provides constructors that verify byte and burn clothing as discussion and returns String object.
String equality
String collection overrides the equals() method of the Object class. It compares the noesis of the digit progress goal and returns the boolean continuance accordingly.
For example,
String str1=”Hello”;
String str2=”Hello”;
String str3=new String(”Hello”) //Using constructor.
If(str1 == str2)
System.out.println(”Equal 1″);
Else
System.out.println(”Not Equal 1″);
If(str1 == str3)
System.out.println(”Equal 2″);
Else
System.out.println(”I am constructed using constructor, hence
not interned”);
If( str1.equals(str3) )
System.out.println(”Equal 3″);
Else
System.out.println(”Not Equal 3″);
The output would be,
Equal 1
Not Equal 2
Equal 3
Note that == compares the references not the actualised table of the String object; Where as equals method compares actualised table of digit String objects.
String collection also provides additional method equalsIgnoreCase() which ignores the housing of table patch comparing.
Apart from these methods String collection also provides compareTo methods.
int compareTo(String str2)
This method compares digit Strings and returns an int value. It returns
continuance 0, if this progress is coequal to the progress discussion
a continuance inferior than 0, if this progress is inferior than the progress
argument
a continuance greater than 0, if this progress is greater than the
progress argument
int compareTo(Object object)
This method behaves just aforementioned the prototypal method if the discussion goal is actually a String object; otherwise, it throws a ClassCastException.
String Manipulations
Reading characters from String:
char charAt(index i)
Returns burn at presented index. An finger ranges from 0 to length() -1.
Searching characters in String
String collection provides indexOf method which searches for the presented housing exclusive the progress object. This method has been overloaded. If the see is successful, then it returns the finger of the burn otherwise -1 is returned.
int indexOf(int c)
Returns the finger of prototypal event of the discussion char.
int indexOf(int c, int fromIndex)
Finds the finger of the prototypal event of the discussion housing in a string, play at the finger presented in the ordinal argument.
int indexOf(String str)
Finds the move finger of the prototypal event of the substring discussion in a String.
int indexOf(String str, int fromIndex)
Finds the move finger of the prototypal event of the substring discussion in a String, play at the finger presented in the ordinal argument.
The String collection also provides methods to see for a housing or progress in sweptback direction. These methods are presented below.
int lastIndexOf(int ch)
int lastIndexOf(int ch, int fromIndex)
int lastIndexOf(String str)
int lastIndexOf(String str, int fromIndex)
Replacing characters in String
The change method of String crapper be utilised to change every occurrences of the presented housing with presented character.
String replace(char oldChar, int newchar)
Getting substrings
String collection provides substring method to select presented assets of the presented String. This method has been overloaded.
String substring(int startIndex)
String substring(int startIndex, int endIndex)
Note: A newborn String goal containing the substring is created and returned. The example String won’t be affected.
If the finger continuance is not valid, a StringIndexOutOfBoundsException is thrown.
Conversions
String collection provides ordered of noise full valueOf method to modify primitives and goal into strings.
static String valueOf(Object obj)
static String valueOf(char[] character)
static String valueOf(boolean b)
static String valueOf(char c)
static String valueOf(int i)
static String valueOf(long l)
static String valueOf(float f)
static String valueOf(double d)
Manipulating Character Case
String collection provides mass methods to cook housing housing in String.
String toUpperCase()
String toUpperCase(Locale locale)
String toLowerCase()
String toLowerCase(Locale locale)
Note : Original String goal is returned if hour of the characters changed, otherwise newborn String goal is constructed and returned.
Miscellaneous methods
String trim()
This method removes albescent expanse from the face and the modify of a String.
int length()
Returns size of the String.
String intern()
This method returns interned String object, if already inform in the String pool. Otherwise this String is additional into the pool, and then interned message is returned.
Rahim Vindhani
Application Develper [Application Development & Webservices]
IBM Global Services, pune, India
email: rahim.vindhani@gmail.com
web: http://www.javadeveloper.co.in