Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.The Java platform provides the
Stringclass to create and manipulate strings.Creating Strings
The most direct way to create a string is to write:In this case, "Hello world!" is a string literala series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates aString greeting = "Hello world!";Stringobject with its value—in this case,Hello world!.As with any other object, you can create
Stringobjects by using thenewkeyword and a constructor. TheStringclass has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:The last line of this code snippet displayschar[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'}; String helloString = new String(helloArray); System.out.println(helloString);hello.
Note: TheStringclass is immutable, so that once it is created aStringobject cannot be changed. TheStringclass has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.String Length
Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is thelength()method, which returns the number of characters contained in the string object. After the following two lines of code have been executed,lenequals 17:A palindrome is a word or sentence that is symmetric—it is spelled the same forward and backward, ignoring case and punctuation. Here is a short and inefficient program to reverse a palindrome string. It invokes theString palindrome = "Dot saw I was Tod"; int len = palindrome.length();StringmethodcharAt(i), which returns the ith character in the string, counting from 0.Running the program produces this output:/* * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class StringDemo { public static void main(String[] args) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); char[] tempCharArray = new char[len]; char[] charArray = new char[len]; // put original string in an array of chars for (int i = 0; i < len; i++) { tempCharArray[i] = palindrome.charAt(i); } // reverse array of chars for (int j = 0; j < len; j++) { charArray[j] = tempCharArray[len - 1 - j]; } String reversePalindrome = new String(charArray); System.out.println(reversePalindrome); } }To accomplish the string reversal, the program had to convert the string to an array of characters (firstdoT saw I was toDforloop), reverse the array into a second array (secondforloop), and then convert back to a string. TheStringclass includes a method,getChars(), to convert a string, or a portion of a string, into an array of characters so we could replace the firstforloop in the program above withpalindrome.getChars(0, len - 1, tempCharArray, 0);Concatenating Strings
TheStringclass includes a method for concatenating two strings:This returns a new string that is string1 with string2 added to it at the end.string1.concat(string2);You can also use the
concat()method with string literals, as in:Strings are more commonly concatenated with the"My name is ".concat("Rumplestiltskin");+operator, as inwhich results in"Hello," + " world" + "!"The"Hello, world!"+operator is widely used inwhich printsString string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod");Such a concatenation can be a mixture of any objects. For each object that is not aDot saw I was TodString, itstoString()method is called to convert it to aString.
Note: The Java programming language does not permit literal strings to span lines in source files, so you must use the+concatenation operator at the end of each line in a multi-line string. For example,Breaking strings between lines using theString quote = "Now is the time for all good " + "men to come to the aid of their country.";+concatenation operator is, once again, very common inCreating Format Strings
You have seen the use of theprintf()andformat()methods to print output with formatted numbers. TheStringclass has an equivalent class method,format(), that returns aStringobject rather than aPrintStreamobject.Using
String'sstaticformat()method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead ofyou can writeSystem.out.printf("The value of the float variable is %f, while the value of the " + "integer variable is %d, and the string is %s", floatVar, intVar, stringVar);String fs; fs = String.format("The value of the float variable is %f, while the value of the " + "integer variable is %d, and the string is %s", floatVar, intVar, stringVar); System.out.println(fs);
ATENCIÓN: La traducción de esta documentación es un esfuerzo personal y voluntario. NO es un documento oficial del propietario de la tecnología Java, Oracle, ni está patrocinado por esta empresa.
Los documentos originales y actualizados (en inglés) están disponibles en: http://docs.oracle.com/javase/tutorial/. La versión disponible en este sitio es la publicada en Marzo de 2008 (más información en: "What's new and What's Old? The History of the Tutorial").
Dirige cualquier comentario, petición, felicitación, etc. a tutorialesjava@codexion.com.
Si quieres ayudar a mantener en funcionamiento esta web, colaborar con la traducción de estos documentos o necesitas que se traduzca algún capítulo en concreto puedes invitarme a un café: