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

Wood Dale Chicago prom limo .. Lockport Chicago limo O’Hare
In The News:

Fueled by artificial intelligence, CyberDog the robotic dog is designed specifically locate fire ant nests, which are endangering ecosystems.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents
Internet browsers are useful, but they can be dangerous. Clicking on malicious links can direct you to dangerous websites that steal information or infect your device.
Apple's latest iOS update introduces advanced artificial intelligence capabilities, which may be capturing and analyzing sensitive information.
Breach site confirmed 56,904,909 Hot Topic users' data leaked online. Tech expert Kurt “CyberGuy" Knutsson says the company's silence makes matters even worse.
Tech expert Kurt “CyberGuy" Knutsson discusses how an innovative Easy-Way kit turns standard strollers electric, simplifying navigation for parents.
Tech expert Kurt “CyberGuy" Knutsson talks about T-Mobile being hacked in broad cyberattack on global phone and internet companies.
Tech expert Kurt “CyberGuy" Knutsson shows you how to add, customize and manage widgets for quick access to apps and info from your iPhone home screen.
Wrong Google searches can not only compromise your device and personal data. They can also bring law enforcement to your doorstep. Hackers are targeting Google searches.
China's Shanghai Kepler Robotics has developed a new humanoid robot that can carry up to 35 pounds per hand for commercial applications across various industries
Checking your hearing has gotten easier with the new hearing test feature in AirPods Pro 2. You can take reliable hearing tests using your iPhone or iPad.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Kurt "CyberGuy" Knutsson explains how a VPN — virtual private network — works and how running it can slow down the operation of your device.
The WalkON Suit F1, an exoskeleton developed to help people with disabilities, can actually walk over to a person in a wheelchair, solving a major problem.
ClickFix, a new scam targeting computer users, is on the rise in the U.S. The scam prompts its targets to click on a link to fix a problem.
Skydweller is the world's largest unmanned solar-powered aircraft that can stay airborne for weeks, and even months, without refueling.
The U.S. government said it is investigating after People's Republic of China hackers targeted commercial telecommunications service providers in the U.S.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Scammers are using increasingly sophisticated ways to lure unsuspecting victims, and some are impersonating an email help desk or support team.
You can unsend or edit your iMessages with the latest iOS updates. Kurt the CyberGuy explains how you can save yourself some potential embarrassment.
Kurt “CyberGuy" Knutsson says there’s been a rise in cybercriminal services using hacked police and government emails to send subpoenas and data requests to U.S. companies.
Kurt “CyberGuy" Knutsson discusses how Axiom Space and luxury designer Prada are collaborating on NASA's Artemis III spacesuit design.
Voice assistants may cause confusion across devices. Tech expert Kurt “CyberGuy" Knutsson offers some solutions to fix it.
Shameless scammers trick veterans into giving personal info or cash. Tech expert Kurt “CyberGuy" Knutsson explores five common scams.

How To Create A Data Capture Procedure Checklist For Your Small Business CRM Software

Fortunately one of the most common reasons cited for the... Read More

Great Plains Dynamics on Pervasive/Ctree support ? overview for consultant

All of us know that Microsoft bought former Great Plains... Read More

Microsoft Great Plains Partner Selection: Overview

Microsoft Great Plains, Navision, Solomon and Axapta are Microsoft Business... Read More

Who?s Watching What You Type?

If someone entered your home, uninvited and installed numerous cameras... Read More

How To Identify, Cure and Prevent Spyware/Adware Infections

Just when you thought you were Web savvy, one more... Read More

Is Software Tester a Most Infamous Person in a Software Project Team?

The fact that a software tester is a most infamous... Read More

Lowering The Risks In Developing Do-It-Yourself Software Projects

Mike Dunville* had a decision to make. As the new... Read More

Change Your Word Docs in Record Time!

Anyone who has ever used Microsoft Word knows that it... Read More

Four Desktop Tools To Drastically Increase Your Productivity

Sticky Noteshttp://www.deprice.com/stickynote.htmWith StickyNote 9.0, you can create beautiful 3D notes... Read More

Perfectly New Database Query Tool - Foxy SQL Pro Released

Are you a database professional? Do you work with a... Read More

Microsoft CRM USA Nationwide Remote Support

Remember old good days when your company probably had Great... Read More

Great Plains Dexterity Customization Options ? Overview For Developers

Looks like Microsoft Great Plains becomes more and more popular,... Read More

The Hidden Power of Online Manual

Writing software manuals is boring, isn't it? We often think:... Read More

Free Preventive Maintenance Software

While several preventive maintenance software manufacturers offer free trials for... Read More

Navision Customization: C/SIDE, C/ODBC, C/FRONT, XBRL ? Development Options

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

Business Plan Software Review: Ultimate Business Planner?

One of the main reasons business owners and entrepreneurs use... Read More

SpyBot - Search and Destroy versus Microsoft AntiSpyware (Beta).... My personal experiences...

Ok... Where to start?Well, I guess I will start at... Read More

Windows Screensavers Explained

In this article you will find some background information about... Read More

Microsoft CRM Conversation Gateway: VoIP - Implementation & Customization

Microsoft CRM is winning market share step-by-step from such the... Read More

Corporate Accounting System: Microsoft Great Plains ? Overview

Corporate ERP/MRP selection might be tough one, especially considering very... Read More

Microsoft CRM Implementation for Large Corporation ? overview

Microsoft Business Solutions CRM is now approaching the phase of... Read More

Separate Anti-Keylogging Protection: Who Needs it Most?

If there still are few unprotected computers left, I haven't... Read More

Software Companies: Generate New Revenue Streams and Decrease Costs with Custom e-Learning Content

It's no secret that software companies operate in a very... Read More

Integrating Microsoft Great Plains Accounting/ERP: RMS, CRM, eCommerce, Lotus Domino ? overview

Microsoft Business Solutions Great Plains has substantial market share among... Read More

Imagine if Everyone Working In Your Office Was In Synch?

Microsoft-Outlook is a pretty amazing program. So much more than... Read More

Antigo wedding limo ..