Software Information |
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
MORE RESOURCES: Unable to open RSS Feed $XMLfilename with error HTTP ERROR: 404, exiting |
RELATED ARTICLES
Fast Car Knoppix Small can be beautiful! Working with Knoppix for the past two years has been a joy. Two terms to describe this distribution, simple, elegance. Microsoft Great Plains e-Commerce - additional considerations for programmer Microsoft Great Plains, designed back in 1990th as database transferable and graphical platform independent ERP application - Great Plains Dynamics/Dynamics C/S+/eEnterprise. For eCommerce developer the most important is to understand Great Plains tables structure and business processes in Sales Order Processing, Accounts Receivables, Inventory Control (inventory items allocation, backordering, etc), posting to Bank Reconciliation and General Ledger. Removing Incoming Email in MS Exchange, C# Example The purpose of one of our projects was MS Exchange handler for processing incoming email.The basic source of knowledge was this article "Developing Managed Event Sinks/Hooks for Exchange Server Store using C#" by Logu Krishnan, published to the address http://www. Lotus Domino: Application Integration - A Programmer View There are two approaches for application integration:? Programmer's approach - for applications integration it is necessary to create some program codes;? Integrator's approach - in this case special software products are to be used and the integration process set up by those software settings.The following tools may be used for the first approach:? ODBC. Hear It in Digits Music downloads are off the charts! We're listening to digital music in the digital era.The driving force behind the phenonmena is the technonolgy called MP3. An Introduction to .NET Framework .Net Framework is a platform or development environment to seamlessly create web-applications that are accessible through client machines from across the globe. Fleet Maintenance Software Reviews Innovative Maintenance Systems (IMS) is one company that offers solutions for companies in need of fleet maintenance software. One of their most popular products is Fleet Maintenance ProŽ. Keeping Track One of the things we can be as certain of as death and taxesis that in every meeting at least one person will hand out adocument for comments and discussion.But think of the huge workload this gives rise to for theauthor. The Top 5 Wrong Reasons For Not Hiring Testers Considering whether or not your software company should hire a dedicated team of testers? Here are the Top 5 Wrong Reasons why you shouldn't.We Have a Beta ProgramSome people feel that the best way to debug a system is to ship it to your customers and wait for trouble tickets. Guide to Software Marketing IntroThis concise article will tell you in plain English how you can promote your software easily and effectively.Submit your softwareI recommend submitting your software to upload. Navision Customization: C/SIDE, C/ODBC, C/FRONT, XBRL - Development Options Microsoft bought Navision, Denmark based software development company, along with Great Plains Software. Now Microsoft Business Solutions offers following ERP applications: Navision (former Navision Attain), Microsoft Great Plains (former Great Plains Dynamics/eEnterprise), Solomon, Axapta. Is Your Computer Sick? Viruses and spyware usually show up on your computer one of two ways.Either they invade your system with a frontal assault like the Huns attacking the Romans, or they sneak in a back door like a cat burglar. Save Your Resources - Combine Your IM Clients There are so many different programs that clutter up your desktop and icon bar, every program using up your precious resources! How much faster would your PC if you could run one single program as opposed to three or more instant messenger clients?Let me give you an example of how much resources are eaten up by using a couple of instant messenger (IM) clients.On a normal day I have two instant messenger clients running at any given time, both of these programs use up hard drive storage space, memory resources and cpu processes. Editing Your Photos Using Microsoft Picture It Publishing Platinum 2002 - A Great Dinosaur I started using PIP (Picture It Publishing) Platinum 2002 right after I got it in a bundle with my HP Pavallion N5295 Notebook more than several moons ago!I don't want to be a rocket scientist to produce edited photos quickly and with quality results, again and again.I had a terrible time at first with the edited pictures. Microsoft Great Plains Upgrade - Things to Consider and FAQ If you have Microsoft Great Plains and support it for your company then you need to know some technical details about Great Plains version upgrade and what is going on behind the scenes, which options do you have in case of Dexterity, VBA, SQL customization, additional complexity comes with migration from ctree/Pervasive to MS SQL/MSDE.What is upgrade in the language of technology? Upgrade has server and client sides. Introducing GRML Creating a new markup language.Introduction. Top Questions to Ask Before Buying a Help Desk & Asset Management Software #5 All your hardware components like Printers, PCs etc come under various maintenance contracts with different maintenance vendors. Do you know which batch of PCs are under warranty & for what number of PCs is the warranty about to expire (so that you can plan for an AMC)? Can you split up & tell how much AMC charges do you pay for each hardware component & how much for each vendor? Can you re-calculate the costs if an AMC with a vendor is to be renewed?#4 Typically your company gets hardware parts and accessories from different vendors. Microsoft Great Plains implementation: Restaurants Supply Chain Management Example Microsoft Great Plains serves majority of US based horizontal and vertical markets. Being relatively flexible and customizable - it can fit your specific business requirements with light or deep customization. Linux Dual Boot-How To Format Just the thought of a duel-boot scares many people away, but over the years it's developed into an easier process. Most people are running Windows, so I'm assuming it's your choice of preference:1. Five Steps to Rapid Development with TierDeveloper 4.0 Follow the steps below to quickly design, generate, and deploy a great portion of your real-life N-Tier application.STEP 1: HAVE YOUR DATABASE READY1. |
home | site map | contact us |