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

housekeepers near Park Ridge ..
In The News:

The A.I. industry seems set for growing pains as Big Tech companies scramble for solutions to the medium's unprecedented strain on the power grid.
Fourth of July fireworks cause a 60% spike in lost pets, but GPS trackers and AI photo-matching services like Love Lost can help reunite missing dogs with their families.
Protect yourself from jugging, the rising crime by which thieves monitor ATM users and follow them to steal cash, with six practical safety tips to stay alert and secure.
U.S. airlines like Delta, American and United are selling your domestic flight records to government agencies through the little-known Travel Intelligence Program.
Autonomous robots from Uber Eats are rolling out across U.S. cities, featuring LIDAR sensors, secure compartments and all-weather operation for food and grocery delivery.
Costco has expanded into EV infrastructure with new ultra-fast charging stations that can charge most electric vehicles to 80% in 20-60 minutes while shoppers browse the warehouse.
The new Gemini Robotics On-Device AI allows robots to perform complex tasks without internet, offering enhanced privacy, reliability and adaptability for real-world use.
Protect yourself from Amazon phishing scams by spotting red flags like suspicious sender addresses and spelling errors while using Amazon's Message Center to verify communications.
GAC Group's new Govy AirCab flying car combines lightweight design with advanced safety systems and smart cabin technology to revolutionize city travel with an 18.6-mile range.
The Berkeley Humanoid Light (BHL) is a lightweight, open source humanoid robot that anyone can build using 3D-printed parts and off-the-shelf components.
Meta’s new AI chatbot is getting personal, and it might be sharing more than you realize.
A new threat targets both Android and iPhone users: SparkKitty, a powerful mobile malware strain that scans private photos to steal cryptocurrency recovery phrases and other sensitive data.
Thanks to a team at the University of California, Davis, there's a new brain-computer interface (BCI) system that's opening up real-time, natural conversation for people who can't speak.
Privacy risks are hiding in plain sight, as your personal data is likely being collected, tracked, and sold without your knowledge.
VenHub, a fully autonomous, AI-powered smart store just opened at the LAX/Metro Transit Center in Los Angeles.
A woman's Facebook account takeover reveals dangerous social engineering tactics and provides lessons on recovery, avoiding scams and enacting stronger security measures.
Shanghai engineers are using 432 walking robots to relocate a complex, preserving Shikumen architecture while creating space for a modern underground hub and cultural center.
Major healthcare data analytics firm Episource had a cybersecurity incident exposing 5 million patients' medical records and personal information in recent breach.
A new sophisticated PayPal scam sends legitimate-looking emails from official PayPal addresses, using phone numbers instead of links to convince victims to download remote access tools.
Fox News' AI Newsletter brings you the latest on this rapidly evolving technology.
The innovative Kara Pod device extracts moisture from air to create mineral-rich water and brew coffee, featuring UV sterilization and compatibility with Nespresso pods.
Gov. Hochul unveiled New York's nuclear power plant project to power a million homes, which faces permit challenges while promising jobs and a cleaner energy future.
SAFE introduces Aerie, an underground luxury bunker combining high-end living with advanced security, wellness amenities and interactive walls simulating panoramic views.
A Facebook scammer posing as Elon Musk tricked a victim with promises of a Tesla and $250,000, requesting gift cards that become untraceable once the codes are shared.
Experience hands-free golfing with the Robera Neo smart caddie that uses AI to follow you, navigate obstacles and carry your clubs with GPS course mapping.

15 Questions to Ask Your Software Vendor

When making a decision to buy any piece of software... Read More

Microsoft Great Plains Reporting ? Overview for Developer

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

Crystal Reports For Microsoft RMS ? Overview For Developer/Report Designer

If you are software developer or database administrator - we... Read More

Dashboard Widgets for Windows

For a windows user like me, just can watch with... Read More

Preventive Maintenance Software Companies

Several software companies design programs for preventive maintenance. Most of... Read More

An Easy Way to Deal with Email Viruses and Worms

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

Snort for Network IDS

What is Snort?Snort is an open source network intrusion detection... Read More

The Dreaded Paper Label - Should it be Used?

While paper labeling CDs and DVDs may appear to be... Read More

Microsoft Retail Management System (RMS) SQL Customization ? Overview for Programmer

Microsoft Retail Management System serves retail single store as well... Read More

IT Department Skills to Support Microsoft Great Plains and Microsoft CRM

Microsoft Great Plains as ERP and Microsoft CRM as... Read More

Groupware: Avoid the Ad Hoc Shuffle

GroupwareEfforts are continually made to manage the unavoidable ad hoc... Read More

How the Firefox: How to... Manual Helped Me

A few months back I really got sick of my... Read More

Free Software: How Not To Get More Than You Bargained For!

I completed an experiment recently. I wanted to find out... Read More

Microsoft Great Plains: Manufacturing or Bill of Materials - Overview for IT Specialist

Microsoft Great Plains is main Microsoft Business Solutions product, targeted... Read More

Hear It in Digits

Music downloads are off the charts! We're listening to digital... 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

Information Products: A Business Owners Best Friend

We live in a post-industrial age where information is the... Read More

How To Avoid Getting Hooked By Pfishing

"Pfishing", sometimes spelled "Phishing", is a word that's used to... Read More

Linux vs Windows Operating Systems

With so many Microsoft Windows related viruses, errors, and other... Read More

Microsoft CRM Customization: Integration with Third Party SQL Application/Database

Microsoft CRM ? Client Relationship Management package from Microsoft Business... Read More

Great Plains Sales Order Processing and Invoicing Modules ? Tips For Consultants

We'll give you non formal view, based on our consulting... Read More

The Importance of Timely Timesheets

Whether you are a small consultancy firm, a medium sized... Read More

Understanding XML Server

XML Server can be a Web Server that stores the... Read More

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

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

Microsoft RMS Customization ? PO Items Receiving in Great Plains

Microsoft Retail Management (RMS) and Microsoft Great Plains are retail... Read More

scheduled cleaning services Mundelein ..