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

Mercedes Benz s500 rentals Salem ..
In The News:

The International Olympic Committee on Friday announced plans to use AI in various Olympic aspects, including athlete identification, training and judging.
Tech guru Kurt "CyberGuy" Knutsson explains an easy trick to avoid squinting while working or surfing the web by zooming in on your personal computer.
Streaming giant Roku has recently been targeted by a pair of cyberattacks, and the company confirmed over a half million Roku accounts were compromised.
The Land Aircraft Carrier combines an all-terrain, six-wheeled vehicle with a two-seat aircraft, which features electric vertical takeoff and landing.
The European Union has sent TikTok a "request for information" on the video sharing platform's newest app, TikTok Lite, under the Digital Services Act, with the aim to clean up social media.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
The FBI is warning the public about a recent phishing scam via text that claims its targets owe money in Pennsylvania for unpaid road toll charges.
Your Apple Music settings may be revealing to your contacts what you're listening to. Kurt "CyberGuy" Knutsson explains the process to change those settings.
Learn how to secure social media accounts, implement legacy contacts, and create a digital estate plan to protect your online assets from 'ghost hackers' after your death.
A ported phone number scam is leading to more people having their identities stolen by sophisticated scammers. Kurt “CyberGuy" Knutsson tells you what you need to know.
The Great Pacific Garbage Patch, a vast marine debris vortex, is being tackled by The Ocean Cleanup’s innovative technologies. Kurt “CyberGuy" Knutsson explains.
Discover easy solutions to tame autocorrect frustration on iOS and Android devices. Turn off, customize and add personal touches to your typing experience.
Kurt “CyberGuy" Knutsson reveals the six top things to do right now before it’s too late: Tech and life choices that can keep your safer on and offline.
Kurt “CyberGuy" Knutsson shows you some simple steps to discreetly hide apps or an entire app page on your iPhone for decluttering or confidentiality.
The ambient light sensors on smartphones may be turned into cameras, according to researches at MIT. This could pose a threat to people's privacy.
The Autonomous Road Repair System from tech firm Robotiz3d uses artificial intelligence technology to locate potholes and promptly seal them.
Scammers have stooped to using artificial intelligence to scan obituary websites to create fake obituary websites to target the grieving.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
A Mercedes-Benz Manufacturing factory in Hungary is using humanoid robots to help with human staffing shortages on the factory floor.
Some video games act like unregulated banks, according to CFPB, which has begun monitoring the situation. The agency says children may be most at risk.
Ascender the robot is capable of climbing stairs with heights up to 8.7 inches, and it can give every corner of your home a deep cleaning.
Tax-return scams are on the rise, and one tax expert from a cybersecurity firm says filing your taxes on time is one way to avoid tax scams.
The innovative XPENG Robot Unicorn is inspired by the mythical unicorn, and you may forget the robot is not actually a living creature.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
The Federal Trade Commission, the federal agency to report scams to, is being impersonated as part of a new sophisticated phone scam.

What is Fleet Maintenance Management?

Fleet Maintenance Management is a critical position in any company... Read More

Linux Dual Boot-How To Format

Just the thought of a duel-boot scares many people away,... Read More

Microsoft Moves to Small Business Accounting/Retail Market ? Stakes and Thoughts

In this small article we will be looking at the... Read More

New Web-Based HR Tool is Max From NAS, Hannibal, and InfoLink

Three highly respected names in Human Resources have joined forces... Read More

Microsoft Great Plains on Ctree or Pervasive SQL ? What to Do ? Tips for IT Manager

As you probably know, when Microsoft purchased Great Plains Software... Read More

An Easy Way to Deal with Email Viruses and Worms

If you feel intimidated when someone tries to teach you... Read More

Microsoft Great Plains version 8.5: Upgrade, Customization, VBA, Crystal Reports - Highlights

Microsoft Great Plains is one of the Microsoft Business Solutions... Read More

Best Spyware Removers

Finding the best spyware removers to detect and remove spyware... Read More

Microsoft Great Plains eCommerce ? Stored Procedures Approach

Since Version 8.0 Microsoft Business Solutions Great Plains & Great... Read More

Begun, The Browser Wars Have

As Mozilla Firefox nears 10% market share, with well over... Read More

Microsoft Great Plains Food Processing ? Implementation & Customization Highlights

Microsoft Great Plains might be considered as ERP platform to... Read More

Microsoft Business Solutions - Navision Customization: C/SIDE, C/ODBC, C/FRONT, XBRL

Microsoft bought Navision, Denmark based software development company, along with... Read More

ERP Remote Support: Microsoft Great Plains Analysis ? Pluses & Minuses

Former Great Plains Software Dynamics/eEnterprise and currently Microsoft Business Solutions... Read More

Seven Reasons Why a Hosted Inventory Management Solution Might Be Right For Your Organization

Upgrading. Downtime. Maintenance. Hardware obsolescence. Implementation issues. The litany of... Read More

How to Choose the Right Accounting Software for Your Business

With any good luck and a good amount of hard... Read More

5 Mac Security Tips You Can?t Live Without

So, you've bought a new Macintosh, and now you may... Read More

What is a Document Manager without Version History?

Document Manager and Version HistoryIn previous articles I have discussed... Read More

Software Process Improvement -A Successful Journey

Background: For many organizations like ours, the interim target of... Read More

Microsoft CRM Messaging through Lotus Domino eMail Server - Balanced Solution

Microsoft CRM and IBM Lotus Notes Domino seem to be... Read More

Software Review: Xsitepro Total Site Management Software

It's not very often I get excited about a software... Read More

Off The Record - Tips For Picking Recording Software

Need software to record your voice, streaming audio or musical... Read More

Know-how in Microsoft Publisher

For those who still don't know, Microsoft Publisher helps computer... Read More

An Introduction to .NET Framework

.Net Framework is a platform or development environment to seamlessly... Read More

7 Things to Consider Before Buying Small Business Accounting Software

The world of small business accounting software can be a... Read More

eStore Advantage ? Extending Microsoft eConnect for MBS Great Plains

eStore Advantage allows front-office applications to communicate with back-office business... Read More

Dowagiac cheap limo service ..