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

move out cleaning service Lake Forest ..
In The News:

A third-party dental marketing agency's unsecured database exposed millions of patient profiles with personal information that could be exploited for identity theft and insurance fraud.
New York-based Aircela unveils refrigerator-size device that converts air and water into fossil-free gasoline, with initial deployments planned for 2025.
Your home address is easily accessible on people finder sites, putting you at risk for stalking and identity theft, but data removal services can help protect your personal information.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents
Robot combat evolves at Unitree's Iron Fist King event as G1 robots face off in China, featuring knockouts, precise strikes and agile machines that can perform side flips.
Take control of your digital privacy with actionable tips like Facebook privacy checkup, location tracking management and data removal services to protect your personal information.
Smart TVs and streaming devices manufactured in China are being compromised by BadBox 2.0 malware before users even power them on; infections have been detected in 222 countries.
The lightweight, 15-pound Tenniix tennis robot mimics pro playing styles like Nadal and Federer, using AI trained on 8,000 hours of professional tennis data.
Oak Ridge's uranium enrichment facility supports America's AI ambitions amid concerns that China's aggressive nuclear reactor construction could give it an edge in powering data centers.
Facebook scam ads now leverage AI and deepfakes to create convincing celebrity endorsements, targeting specific demographics with sophisticated schemes.
Apple unveils iOS 26, macOS 26 Tahoe and iPadOS 26 with translucent Liquid Glass design at WWDC 2025, featuring ChatGPT integration as competitors advance rapidly.
The Atom Touch prosthetic arm combines an AI neural interface with EMG sensors, allowing amputees to control individual fingers with precision at an affordable $25,000.
Aspen officials aim to have crews on the scene within five minutes — something they say would be nearly impossible without precise location data the AI technology gives.
Tech expert Kurt “CyberGuy" Knutsson says iPads are usually secure, but hackers can access them. Spot warning signs early to protect your data.
Tech expert Kurt Knutsson reveals how to easily move photos and videos off your iPhone or Android to securely protect your favorite moments.
The Social Security Administration is launching digital SSN access this summer. Tech expert Kurt “CyberGuy" Knutsson helps you learn how to use it and protect your identity.
Glide underwater with CudaJet and make the ocean your playground. Kurt “CyberGuy" Knutsson discusses the redesigned tech that might be your next big thrilling adventure.
Protect yourself from login alert scams with five security steps, including avoiding suspicious links, checking account activity and enabling two-factor authentication
Skip the usual Father's Day gifts with personalized ideas for tech enthusiasts, home brewers, pool owners, seniors, outdoor lovers and privacy-conscious dads.
DMV text scam alert: Fraudsters impersonating motor vehicle departments nationwide are sending threatening messages about unpaid tickets and tolls to steal your information.
Fox News' AI Newsletter brings you the latest on this rapidly evolving technology.
E-BAR, MIT's mobile robot, provides physical support for seniors with handlebars that follow from behind, helping prevent falls while maintaining dignity for aging adults.
AI is changing everything – now, we can even use it to generate video. I tried OpenAI's Sora and Google's Veo – here's how they measure up against each other.
Five simple phone setting tweaks that make your device work harder for you, from automatic text message deletion to scheduled focus modes.
Android users can save time with 10 simple automations, including automatic battery saver mode, location-based Wi-Fi settings and scheduled "Do Not Disturb" mode.

Ukraine: a Prospective Player on the World Software Outsourcing Market

The destruction of the Soviet Union about 15 years ago,... Read More

Looking for an Alternative to Microsoft Office? You Should Be!

Now is the time to look at an alternative to... Read More

Microsoft Great Plains: Customization Upgrade & Recovery ? Visual Studio VB 6.0

Microsoft Great Plains, former Great Plains Software Dynamics, eEnterprise has... Read More

Microsoft CRM Data Import FAQ

Microsoft CRM has built-in conversion tool, however you should probably... Read More

The Secret of the Layer Styles Dialogue

When you double-click a layer in the Layer Palette, you... Read More

Document Templates Give You The Perfect Framework For Your Documents

When it comes to running an office, the SOHO entrepreneur... Read More

Partitioning, Formatting and Reinstalling in Windows 98

Formatting and reinstalling windows 98 is very easy if you... Read More

Alien Intruders!

You probably didn't casually invite, or extend a formal attendance... Read More

Groove Network. Are you in it?

If you are in a business that passes documents around... Read More

IBM Lotus Domino or Microsoft Exchange?

IBM Lotus Domino or Microsoft Exchange?The severe competition continues for... Read More

Microsoft Great Plains Subcontracting ? Overview for Microsoft Business Solutions Partner

Microsoft Business Solutions Great Plains is very popular ERP/MRP applications... Read More

Microsoft Great Plains Integrations ? Retail Management Sample

Microsoft Business Solutions is emerging as very attractive vendor for... Read More

Cisco Certification: Introduction To ISDN, Part V

The major reason I recommend getting your hands on real... Read More

Microsoft Great Plains Oil & Gas ? Implementation & Customization Highlights

Microsoft Great Plains serves the wide spectrum of horizontal markets.... Read More

Razzle Dazzle Them

Once upon a time not so long ago, there was... 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

Microsoft CRM Custom Design & Development: SDK, C#, SQL, Exchange, Integration, Crystal Reports

Microsoft CRM is new player on the CRM software... Read More

Vlans

In order to implement VLANs in a network environment, you'll... Read More

Downloading Spyware Removers: Think Before, not After

Just imagine: you are walking, say, towards your car, and... 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

Microsoft Great Plains eCommerce: overview for developer

Microsoft Business Solutions Great Plains was designed back in the... Read More

Microsoft Great Plains: Offshore Customization & Development ? Overview for Consultant

When you visit department stores and see that majority of... Read More

Microsoft Navision Customization and Reporting ? Tips For Programmer/IT Specialist

C/SIDE (Client/Server Integrated Development Environment) - The core of... Read More

Great Plains Bill of Materials Setup & Customization for Process Manufacturing ? Overview

Microsoft Great Plains has full-featured Manufacturing suite of modules: Capacity... Read More

How to Evaluate Staffing Software

If you are in the market for new staffing software,... Read More

house refresh service Bannockburn ..