String In Java
|
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
|
|
|
Great Plains Dexterity History And Programming Overview
As of now - Great Plains Dynamics/eEnterprise is transformed/renamed into Microsoft Great Plains and Microsoft Business Solutions is in process of merging all its accounting applications: Great Plains, Solomon, Navision and Axapta into somewhat granular: Microsoft Financials, Microsoft HR, Microsoft Distributions, Microsoft Project Accounting, etc. So the original design of Great Plains should be deemphasized. But even now - Great Plains is written on the programming language and technology, created in early 1990-th, named Great Plains Dexterity. And the graphical interface looks very user friendly and nice - these are all Dexterity forms and screens.The original architect of Dexterity, Tim Brookins, pursued several goals, the main are these:1. Engine, supporting graphical ...(related: Software)
Five Tips For A Great Software Demo
Whether you need to close a sale, gather end-user feedback, show progress to your customer, or simply explain how your product works, sooner or later, you will need to demo your software product.
Hsphere Control Panel Tips And Tricks - Power At Your Fingertips: Part 1
The first topic we are going to discuss is email. HSPHERE (the software running the control panel) offers many useful functions including mail forwarding, auto responders and a mail list manager. You can add new emails at anytime you wish. To add a new e-mail mailbox, do the following:
Microsoft Crm: Data Conversion ? Import From Act!
Best Software Act! is very popular CRM for small and mid-size organization. This system attracts business owner by its low price, plus system is very easy to use. However if your business is growing you should reach the moment to implement more advanced CRM solution. Natural question is ? how do we convert the data from Act! to new CRM solution and the mapping of your objects for conversion. You would probably like to avoid operator data entry with potential numerous errors and mistypes. Assuming that you are IT specialist, we'll give you technical side of Act to MS CRM data migration:? First you need to download Act! SDK from Best Software website? Install Act! SDK on the computer, where you plan to do programming? We'll use asynchronou...(related: Software)
How To Avoid Getting Hooked By Pfishing
"Pfishing", sometimes spelled "Phishing", is a word that's used to describe amethod of identity theft where con men use fake e-mail that looks like it comesfrom legitimate sources. This e-mail is designed to hoodwink you into givingout personal and financial information. Once the scammers receive yourinformation they...(related: Software)
7 Things To Consider Before Buying Small Business Accounting Software
The world of small business accounting software can be a minefield for any business owner. However choosing the right package is one of the most critical business decisions you will make.Here are the seven things you must consider before making a purchase that will help you achieve your businesses goals.1. ScalabilityBusinesses change over time so it's critical that the small business accounting software you choose can change too. Some things that often change are the number of products and services offered and the number of employees. When you choose your package try and imaging the business in 5 years or 10 years time and how different it will be. Use this information to guide your purchase decision. It may well be bet...(related: Software)
Microsoft Crm Or Siebel
Siebel is traditional CRM market leader, however and mostly due to recession 200-2003, Siebel lost sizable portion of CRM market to new tiger, such as Microsoft CRM. Microsoft CRM s recent (2001) CRM answer from Microsoft and attempt top get market share from traditional vendors: Siebel, Oracle, Onyx. Now it is targeted to the whole spectrum of horizontal and vertical market clientele. It is tightly integrated with other Microsoft Business Solutions products such as Microsoft Great Plains, Solomon, Navision (the last two in progress).We would like to give you Microsoft CRM selection advise, based on our MS CRM consulting practice, going back to its inception in 1999. This article ...(related: Software)
Microsoft Great Plains - Payroll & Hr Inexpensive Solution? Not Any More
Microsoft Great Plains is main Microsoft Business Solutions accounting package for the US market. You should probably expect some issues when you have software development company to be b...(related: Software)
Microsoft Crm Custom Design & Development: Sdk, C#, Sql, Exchange, Integration, Crystal Reports
Microsoft CRM is new player on the CRM software market. The whole conception behind CRM seems to be different. In case of traditional CRM software (Siebel, Oracle) - the application was designed with platform independence in mind. Microsoft CRM is dedicated to Microsoft technology and so deploys all the Microsoft tools: Win...(related: Software)
Microsoft Crm And Great Plains Implementation: Freight Forwarding Business Automation Example
Microsoft Business Solutions offers several ERP applications: Great Plains, Navision, Solomon and its own CRM solution ? Microsoft CRM. Targeting to automate all business operations, Microsoft CRM is now integrated with Microsoft Great Plains and in the close future it should have integration with Microsoft Navision. In this small article we'll show you business automation example, where Microsoft CRM and Great Plains are integrated and customized to fit Freight Forwarding business processes.
Make Or Break Factors - When Considering Estimating Software
Make-or-Break Factors in Success and ProfitabilityFor quick printers, estimating can prove to be a major factor in the success or failure of their business.When a customer re...(related: Software)
site-map - Copyright © 2008 | Contact Webmaster | All Rights Reserved. | Software