Handling character strings in Java is supported through two final classes: String and StringBuffer. The String class implements immutable character strings, which are read-only once the string has been created and initialized, whereas the StringBuffer class implements dynamic character strings. All string literals in Java programs, are implemented as instances of String class. Strings in Java are 16-bit Unicode.
Note : In JDK 1.5+ you can use StringBuilder, which works exactly like StringBuffer, but it is faster and not thread-safe
The easiest way of creating a String object is using a string literal:
String str1 = "I cant be changed once created!";
A string literal is a reference to a String object. Since a string literal is a reference, it can be manipulated like any other String reference. i.e. it can be used to invoke methods of String class.
For example,
Int myLength = "Hello world".length();
The Java language provides special support for the string concatenation operator ( + ), which has been overloaded for Strings objects. String concatenation is implemented through the StringBuffer class and its append method.
For example,
String finalString = "Hello" + "World"
Would be executed as
String finalString = new StringBuffer().append("Hello").append("World").toString();
The Java compiler optimizes handling of string literals. Only one String object is shared by all string having same character sequence. Such strings are said to be interned, meaning that they share a unique String object. The String class maintains a private pool where such strings are interned.
For example,
String str1="Hello";
String str2="Hello";
If(str1 == str2)
System.out.println("Equal");
Would print Equal when run.
Since the String objects are immutable. Any operation performed on one String reference will never have any effect on other references denoting the same object.
Constructors
String class provides various types of constructors to create String objects. Some of them are,
String()
Creates a new String object whose content is empty i.e. "".
String(String s)
Creates a new String object whose content is same as the String object passed as an argument.
Note: Constructor creates a new string means it does not intern the String. Interned String object reference can be obtained by using intern() method of the String class
String also provides constructors that take byte and char array as argument and returns String object.
String equality
String class overrides the equals() method of the Object class. It compares the content of the two string object and returns the boolean value 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 actual contents of the String object; Where as equals method compares actual contents of two String objects.
String class also provides another method equalsIgnoreCase() which ignores the case of contents while comparing.
Apart from these methods String class also provides compareTo methods.
int compareTo(String str2)
This method compares two Strings and returns an int value. It returns value 0, if this string is equal to the string argument a value less than 0, if this string is less than the string argument
a value greater than 0, if this string is greater than the string argument
int compareTo(Object object)
This method behaves exactly like the first method if the argument object is actually a String object; otherwise, it throws a ClassCastException.
String Manipulations
Reading characters from String:
char charAt(index i)
Returns char at specified index. An index ranges from 0 to length() -1.
Searching characters in String
String class provides indexOf method which searches for the specified character inside the string object. This method has been overloaded. If the search is successful, then it returns the index of the char otherwise -1 is returned.
int indexOf(int c)
Returns the index of first occurrence of the argument char.
int indexOf(int c, int fromIndex)
Finds the index of the first occurrence of the argument character in a string, starting at the index specified in the second argument.
int indexOf(String str)
Finds the start index of the first occurrence of the substring argument in a String.
int indexOf(String str, int fromIndex)
Finds the start index of the first occurrence of the substring argument in a String, starting at the index specified in the second argument.
The String class also provides methods to search for a character or string in backward direction. These methods are given 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 replace method of String can be used to replace all occurrences of the specified character with given character.
String replace(char oldChar, int newchar)
Getting substrings
String class provides substring method to extract specified portion of the given String. This method has been overloaded.
String substring(int startIndex)
String substring(int startIndex, int endIndex)
Note: A new String object containing the substring is created and returned. The original String won't be affected.
If the index value is not valid, a StringIndexOutOfBoundsException is thrown.
Conversions
String class provides set of static overloaded valueOf method to convert primitives and object 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 class provides following methods to manipulate character case in String.
String toUpperCase()
String toUpperCase(Locale locale)
String toLowerCase()
String toLowerCase(Locale locale)
Note : Original String object is returned if none of the characters changed, otherwise new String object is constructed and returned.
Miscellaneous methods
String trim()
This method removes white space from the front and the end of a String.
int length()
Returns length of the String.
String intern()
This method returns interned String object, if already present in the String pool. Otherwise this String is added into the pool, and then interned reference is returned.
Rahim Vindhani
Application Develper [Application Development & Webservices]
IBM Global Services, pune, India
email: rahim.vindhani@gmail.com
web: http://www.rahim.co.nr
Most people don't use Photoshop to its fullest capabilities. Here... Read More
The software giants don't do everything and don't always produce... Read More
As we could imagine, if you are reading this article... Read More
GroupwareEfforts are continually made to manage the unavoidable ad hoc... Read More
Sticky Noteshttp://www.deprice.com/stickynote.htmWith StickyNote 9.0, you can create beautiful 3D notes... Read More
Looks like Microsoft Great Plains becomes more and more popular,... Read More
Microsoft Great Plains is one of the Microsoft Business Solutions... Read More
In today's business world it's all but impossible to escape... Read More
Microsoft Business Solutions Great Plains version 8.5, 8.0, 7.5, Great... Read More
The COSMIC FP (function point) software quality metric, is no... Read More
Microsoft Business Solutions Great Plains has I'd say end user... Read More
Microsoft Great Plains and Microsoft CRM become more and more... Read More
What is 'adware'?Adware is basically software or scripts that are... Read More
If you've been using MySQL database to store your important... Read More
Microsoft Business Solutions Great Plains is marketed for mid-size companies... Read More
Microsoft CRM is CRM answer from Microsoft Business Solutions. If... Read More
What is Spyware?Spyware monitors your surfing habits and sends the... Read More
Think of this, first we had the HAM Radio, then... Read More
Viruses and spyware usually show up on your computer one... Read More
People often ask me: What image file formats will Photoshop... Read More
Microsoft Business Solutions ? Great Plains has captured the US... Read More
First we had the original Google search that evolved into... Read More
The destruction of the Soviet Union about 15 years ago,... Read More
Microsoft Business Solutions Great Plains is very popular ERP/MRP applications... Read More
Our company, Novaprof Inc., developed unique software - DB Integration.... Read More
Microsoft Business Solutions Great Plains, former Great Plains Software Dynamics... Read More
Microsoft Business Solutions CRM proved to be reliable solution in... Read More
Trying to figure out a stream in banning one email... Read More
If you look back to the history, you will see... Read More
Hey Guys! Don't raise your eyebrows or fear by hearing... Read More
The first thing that you will notice about Linux Red... Read More
We all take the computer for granted. I mean, all... Read More
Before September 1995, Microsoft Windows was an MS-DOS program. DOS... Read More
While I was in college, if you would have asked... Read More
Microsoft Word is one of the most popular office applications... Read More
Microsoft bought Navision, Denmark based software development company, along with... Read More
Our hosted solution allow you to run your own search... Read More
Which Type of Shop Can Rely On A Home Built... Read More
This article is the third of a series of articles... Read More
Customer Relationship Management, abbreviated "CRM," is the term for a... Read More
A few months back I really got sick of my... Read More
Microsoft Business Solutions offers several ERP applications: Great Plains, Navision,... Read More
In this article you will find some background information about... Read More
C++ Function templates are those functions which can handle different... Read More
In the new era of internet marketing the problem of... Read More
MSN messenger is a pretty cool invention. I mean I'm... Read More
Traditionally we were considering functionally rich systems, such as SAP,... Read More
Microsoft Great Plains is main mid-market application from Microsoft Business... Read More
Looks like Microsoft Great Plains becomes more and more... Read More
Have you noticed WordPerfect is gearing up for a comeback... Read More
Three highly respected names in Human Resources have joined forces... Read More
(1) Avoid using the same variable again and again for... Read More
Customer Relationship Management (CRM) is a strategy and processes used... Read More
Microsoft Retail Management System serves retail single store as well... Read More
The US House of Representatives has recently passed the "Spy... Read More
If you are in the market for new staffing software,... Read More
RSS (Really Simple Syndication) is a way for a site... Read More
So, you've bought a new Macintosh, and now you may... Read More
Logistics automation is often considered as barcoding extension to Sales... Read More
IBM Lotus Notes with Domino email server is traditional document... Read More
Language development computer: Computer-based method for aiding language development seems... Read More
With so many Microsoft Windows related viruses, errors, and other... Read More
Microsoft Great Plains - Microsoft Business Solutions accounting and ERP... Read More
The Internet is reshaping every form of communications medium, and... Read More
Microsoft Business Solutions Navision is main ERP application for European,... Read More
The adware and spyware definitions list is very long. But... Read More
Software |