1 /* 2 * Copyright (c) 1994, 2014, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang; 27 28 import java.io.ObjectStreamField; 29 import java.io.UnsupportedEncodingException; 30 import java.nio.charset.Charset; 31 import java.nio.ByteBuffer; 32 import java.util.ArrayList; 33 import java.util.Arrays; 34 import java.util.Comparator; 35 import java.util.Formatter; 36 import java.util.Locale; 37 import java.util.Objects; 38 import java.util.StringJoiner; 39 import java.util.regex.Matcher; 40 import java.util.regex.Pattern; 41 import java.util.regex.PatternSyntaxException; 42 43 /** 44 * The {@code String} class represents character strings. All 45 * string literals in Java programs, such as {@code "abc"}, are 46 * implemented as instances of this class. 47 * <p> 48 * Strings are constant; their values cannot be changed after they 49 * are created. String buffers support mutable strings. 50 * Because String objects are immutable they can be shared. For example: 51 * <blockquote><pre> 52 * String str = "abc"; 53 * </pre></blockquote><p> 54 * is equivalent to: 55 * <blockquote><pre> 56 * char data[] = {'a', 'b', 'c'}; 57 * String str = new String(data); 58 * </pre></blockquote><p> 59 * Here are some more examples of how strings can be used: 60 * <blockquote><pre> 61 * System.out.println("abc"); 62 * String cde = "cde"; 63 * System.out.println("abc" + cde); 64 * String c = "abc".substring(2,3); 65 * String d = cde.substring(1, 2); 66 * </pre></blockquote> 67 * <p> 68 * The class {@code String} includes methods for examining 69 * individual characters of the sequence, for comparing strings, for 70 * searching strings, for extracting substrings, and for creating a 71 * copy of a string with all characters translated to uppercase or to 72 * lowercase. Case mapping is based on the Unicode Standard version 73 * specified by the {@link java.lang.Character Character} class. 74 * <p> 75 * The Java language provides special support for the string 76 * concatenation operator ( + ), and for conversion of 77 * other objects to strings. String concatenation is implemented 78 * through the {@code StringBuilder}(or {@code StringBuffer}) 79 * class and its {@code append} method. 80 * String conversions are implemented through the method 81 * {@code toString}, defined by {@code Object} and 82 * inherited by all classes in Java. For additional information on 83 * string concatenation and conversion, see Gosling, Joy, and Steele, 84 * <i>The Java Language Specification</i>. 85 * 86 * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor 87 * or method in this class will cause a {@link NullPointerException} to be 88 * thrown. 89 * 90 * <p>A {@code String} represents a string in the UTF-16 format 91 * in which <em>supplementary characters</em> are represented by <em>surrogate 92 * pairs</em> (see the section <a href="Character.html#unicode">Unicode 93 * Character Representations</a> in the {@code Character} class for 94 * more information). 95 * Index values refer to {@code char} code units, so a supplementary 96 * character uses two positions in a {@code String}. 97 * <p>The {@code String} class provides methods for dealing with 98 * Unicode code points (i.e., characters), in addition to those for 99 * dealing with Unicode code units (i.e., {@code char} values). 100 * 101 * @author Lee Boynton 102 * @author Arthur van Hoff 103 * @author Martin Buchholz 104 * @author Ulf Zibis 105 * @see java.lang.Object#toString() 106 * @see java.lang.StringBuffer 107 * @see java.lang.StringBuilder 108 * @see java.nio.charset.Charset 109 * @since 1.0 110 */ 111 112 public final class String 113 implements java.io.Serializable, Comparable<String>, CharSequence { 114 /** The value is used for character storage. */ 115 private final char value[]; 116 117 /** Cache the hash code for the string */ 118 private int hash; // Default to 0 119 120 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 121 private static final long serialVersionUID = -6849794470754667710L; 122 123 /** 124 * Class String is special cased within the Serialization Stream Protocol. 125 * 126 * A String instance is written into an ObjectOutputStream according to 127 * <a href="{@docRoot}/../platform/serialization/spec/output.html"> 128 * Object Serialization Specification, Section 6.2, "Stream Elements"</a> 129 */ 130 private static final ObjectStreamField[] serialPersistentFields = 131 new ObjectStreamField[0]; 132 133 /** 134 * Initializes a newly created {@code String} object so that it represents 135 * an empty character sequence. Note that use of this constructor is 136 * unnecessary since Strings are immutable. 137 */ 138 public String() { 139 this.value = new char[0]; 140 } 141 142 /** 143 * Initializes a newly created {@code String} object so that it represents 144 * the same sequence of characters as the argument; in other words, the 145 * newly created string is a copy of the argument string. Unless an 146 * explicit copy of {@code original} is needed, use of this constructor is 147 * unnecessary since Strings are immutable. 148 * 149 * @param original 150 * A {@code String} 151 */ 152 public String(String original) { 153 this.value = original.value; 154 this.hash = original.hash; 155 } 156 157 /** 158 * Allocates a new {@code String} so that it represents the sequence of 159 * characters currently contained in the character array argument. The 160 * contents of the character array are copied; subsequent modification of 161 * the character array does not affect the newly created string. 162 * 163 * @param value 164 * The initial value of the string 165 */ 166 public String(char value[]) { 167 this.value = Arrays.copyOf(value, value.length); 168 } 169 170 /** 171 * Allocates a new {@code String} that contains characters from a subarray 172 * of the character array argument. The {@code offset} argument is the 173 * index of the first character of the subarray and the {@code count} 174 * argument specifies the length of the subarray. The contents of the 175 * subarray are copied; subsequent modification of the character array does 176 * not affect the newly created string. 177 * 178 * @param value 179 * Array that is the source of characters 180 * 181 * @param offset 182 * The initial offset 183 * 184 * @param count 185 * The length 186 * 187 * @throws IndexOutOfBoundsException 188 * If the {@code offset} and {@code count} arguments index 189 * characters outside the bounds of the {@code value} array 190 */ 191 public String(char value[], int offset, int count) { 192 if (offset < 0) { 193 throw new StringIndexOutOfBoundsException(offset); 194 } 195 if (count < 0) { 196 throw new StringIndexOutOfBoundsException(count); 197 } 198 // Note: offset or count might be near -1>>>1. 199 if (offset > value.length - count) { 200 throw new StringIndexOutOfBoundsException(offset + count); 201 } 202 this.value = Arrays.copyOfRange(value, offset, offset+count); 203 } 204 205 /** 206 * Allocates a new {@code String} that contains characters from a subarray 207 * of the <a href="Character.html#unicode">Unicode code point</a> array 208 * argument. The {@code offset} argument is the index of the first code 209 * point of the subarray and the {@code count} argument specifies the 210 * length of the subarray. The contents of the subarray are converted to 211 * {@code char}s; subsequent modification of the {@code int} array does not 212 * affect the newly created string. 213 * 214 * @param codePoints 215 * Array that is the source of Unicode code points 216 * 217 * @param offset 218 * The initial offset 219 * 220 * @param count 221 * The length 222 * 223 * @throws IllegalArgumentException 224 * If any invalid Unicode code point is found in {@code 225 * codePoints} 226 * 227 * @throws IndexOutOfBoundsException 228 * If the {@code offset} and {@code count} arguments index 229 * characters outside the bounds of the {@code codePoints} array 230 * 231 * @since 1.5 232 */ 233 public String(int[] codePoints, int offset, int count) { 234 if (offset < 0) { 235 throw new StringIndexOutOfBoundsException(offset); 236 } 237 if (count < 0) { 238 throw new StringIndexOutOfBoundsException(count); 239 } 240 // Note: offset or count might be near -1>>>1. 241 if (offset > codePoints.length - count) { 242 throw new StringIndexOutOfBoundsException(offset + count); 243 } 244 245 final int end = offset + count; 246 247 // Pass 1: Compute precise size of char[] 248 int n = count; 249 for (int i = offset; i < end; i++) { 250 int c = codePoints[i]; 251 if (Character.isBmpCodePoint(c)) 252 continue; 253 else if (Character.isValidCodePoint(c)) 254 n++; 255 else throw new IllegalArgumentException(Integer.toString(c)); 256 } 257 258 // Pass 2: Allocate and fill in char[] 259 final char[] v = new char[n]; 260 261 for (int i = offset, j = 0; i < end; i++, j++) { 262 int c = codePoints[i]; 263 if (Character.isBmpCodePoint(c)) 264 v[j] = (char)c; 265 else 266 Character.toSurrogates(c, v, j++); 267 } 268 269 this.value = v; 270 } 271 272 /** 273 * Allocates a new {@code String} constructed from a subarray of an array 274 * of 8-bit integer values. 275 * 276 * <p> The {@code offset} argument is the index of the first byte of the 277 * subarray, and the {@code count} argument specifies the length of the 278 * subarray. 279 * 280 * <p> Each {@code byte} in the subarray is converted to a {@code char} as 281 * specified in the method above. 282 * 283 * @deprecated This method does not properly convert bytes into characters. 284 * As of JDK 1.1, the preferred way to do this is via the 285 * {@code String} constructors that take a {@link 286 * java.nio.charset.Charset}, charset name, or that use the platform's 287 * default charset. 288 * 289 * @param ascii 290 * The bytes to be converted to characters 291 * 292 * @param hibyte 293 * The top 8 bits of each 16-bit Unicode code unit 294 * 295 * @param offset 296 * The initial offset 297 * @param count 298 * The length 299 * 300 * @throws IndexOutOfBoundsException 301 * If the {@code offset} or {@code count} argument is invalid 302 * 303 * @see #String(byte[], int) 304 * @see #String(byte[], int, int, java.lang.String) 305 * @see #String(byte[], int, int, java.nio.charset.Charset) 306 * @see #String(byte[], int, int) 307 * @see #String(byte[], java.lang.String) 308 * @see #String(byte[], java.nio.charset.Charset) 309 * @see #String(byte[]) 310 */ 311 @Deprecated 312 public String(byte ascii[], int hibyte, int offset, int count) { 313 checkBounds(ascii, offset, count); 314 char value[] = new char[count]; 315 316 if (hibyte == 0) { 317 for (int i = count; i-- > 0;) { 318 value[i] = (char)(ascii[i + offset] & 0xff); 319 } 320 } else { 321 hibyte <<= 8; 322 for (int i = count; i-- > 0;) { 323 value[i] = (char)(hibyte | (ascii[i + offset] & 0xff)); 324 } 325 } 326 this.value = value; 327 } 328 329 /** 330 * Allocates a new {@code String} containing characters constructed from 331 * an array of 8-bit integer values. Each character <i>c</i>in the 332 * resulting string is constructed from the corresponding component 333 * <i>b</i> in the byte array such that: 334 * 335 * <blockquote><pre> 336 * <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8) 337 * | (<b><i>b</i></b> & 0xff)) 338 * </pre></blockquote> 339 * 340 * @deprecated This method does not properly convert bytes into 341 * characters. As of JDK 1.1, the preferred way to do this is via the 342 * {@code String} constructors that take a {@link 343 * java.nio.charset.Charset}, charset name, or that use the platform's 344 * default charset. 345 * 346 * @param ascii 347 * The bytes to be converted to characters 348 * 349 * @param hibyte 350 * The top 8 bits of each 16-bit Unicode code unit 351 * 352 * @see #String(byte[], int, int, java.lang.String) 353 * @see #String(byte[], int, int, java.nio.charset.Charset) 354 * @see #String(byte[], int, int) 355 * @see #String(byte[], java.lang.String) 356 * @see #String(byte[], java.nio.charset.Charset) 357 * @see #String(byte[]) 358 */ 359 @Deprecated 360 public String(byte ascii[], int hibyte) { 361 this(ascii, hibyte, 0, ascii.length); 362 } 363 364 /* Common private utility method used to bounds check the byte array 365 * and requested offset & length values used by the String(byte[],..) 366 * constructors. 367 */ 368 private static void checkBounds(byte[] bytes, int offset, int length) { 369 if (length < 0) 370 throw new StringIndexOutOfBoundsException(length); 371 if (offset < 0) 372 throw new StringIndexOutOfBoundsException(offset); 373 if (offset > bytes.length - length) 374 throw new StringIndexOutOfBoundsException(offset + length); 375 } 376 377 /** 378 * Constructs a new {@code String} by decoding the specified subarray of 379 * bytes using the specified charset. The length of the new {@code String} 380 * is a function of the charset, and hence may not be equal to the length 381 * of the subarray. 382 * 383 * <p> The behavior of this constructor when the given bytes are not valid 384 * in the given charset is unspecified. The {@link 385 * java.nio.charset.CharsetDecoder} class should be used when more control 386 * over the decoding process is required. 387 * 388 * @param bytes 389 * The bytes to be decoded into characters 390 * 391 * @param offset 392 * The index of the first byte to decode 393 * 394 * @param length 395 * The number of bytes to decode 396 397 * @param charsetName 398 * The name of a supported {@linkplain java.nio.charset.Charset 399 * charset} 400 * 401 * @throws UnsupportedEncodingException 402 * If the named charset is not supported 403 * 404 * @throws IndexOutOfBoundsException 405 * If the {@code offset} and {@code length} arguments index 406 * characters outside the bounds of the {@code bytes} array 407 * 408 * @since 1.1 409 */ 410 public String(byte bytes[], int offset, int length, String charsetName) 411 throws UnsupportedEncodingException { 412 if (charsetName == null) 413 throw new NullPointerException("charsetName"); 414 checkBounds(bytes, offset, length); 415 this.value = StringCoding.decode(charsetName, bytes, offset, length); 416 } 417 418 /** 419 * Constructs a new {@code String} by decoding the specified subarray of 420 * bytes using the specified {@linkplain java.nio.charset.Charset charset}. 421 * The length of the new {@code String} is a function of the charset, and 422 * hence may not be equal to the length of the subarray. 423 * 424 * <p> This method always replaces malformed-input and unmappable-character 425 * sequences with this charset's default replacement string. The {@link 426 * java.nio.charset.CharsetDecoder} class should be used when more control 427 * over the decoding process is required. 428 * 429 * @param bytes 430 * The bytes to be decoded into characters 431 * 432 * @param offset 433 * The index of the first byte to decode 434 * 435 * @param length 436 * The number of bytes to decode 437 * 438 * @param charset 439 * The {@linkplain java.nio.charset.Charset charset} to be used to 440 * decode the {@code bytes} 441 * 442 * @throws IndexOutOfBoundsException 443 * If the {@code offset} and {@code length} arguments index 444 * characters outside the bounds of the {@code bytes} array 445 * 446 * @since 1.6 447 */ 448 public String(byte bytes[], int offset, int length, Charset charset) { 449 if (charset == null) 450 throw new NullPointerException("charset"); 451 checkBounds(bytes, offset, length); 452 this.value = StringCoding.decode(charset, bytes, offset, length); 453 } 454 455 /** 456 * Constructs a new {@code String} by decoding the remaining bytes in the specified 457 * {@linkplain java.nio.ByteBuffer byte buffer} using the specified 458 * {@linkplain java.nio.charset.Charset charset}. 459 * The length of the new {@code String} is a function of the charset, and 460 * hence may not be equal to the remaining number of bytes in the 461 * {@linkplain java.nio.ByteBuffer byte buffer}. 462 * 463 * <p> This method always replaces malformed-input and unmappable-character 464 * sequences with this charset's default replacement string. The {@link 465 * java.nio.charset.CharsetDecoder} class should be used when more control 466 * over the decoding process is required. 467 * 468 * <p> 469 * Bytes are read between <code>position()</code> and <code>limit()</code> 470 * of the {@link java.nio.ByteBuffer}. 471 * After the bytes have been read the <code>position()</code> will be 472 * advanced to its <code>limit()</code>. 473 * 474 * @param bytes 475 * The bytes to be decoded into characters 476 * 477 * @param charset 478 * The {@linkplain java.nio.charset.Charset charset} to be used to 479 * decode the {@code bytes} 480 * 481 * @since 1.9 482 */ 483 public String(ByteBuffer bytes, Charset charset) { 484 Objects.requireNonNull(bytes); 485 Objects.requireNonNull(charset); 486 this.value = StringCoding.decode(charset, bytes); 487 } 488 489 /** 490 * Constructs a new {@code String} by decoding the remaining bytes in the specified 491 * {@linkplain java.nio.ByteBuffer byte buffer} using the specified 492 * charset. 493 * The length of the new {@code String} is a function of the charset, and 494 * hence may not be equal to the remaining number of bytes in the 495 * {@linkplain java.nio.ByteBuffer byte buffer}. 496 * 497 * <p> This method always replaces malformed-input and unmappable-character 498 * sequences with this charset's default replacement string. The {@link 499 * java.nio.charset.CharsetDecoder} class should be used when more control 500 * over the decoding process is required. 501 * 502 * <p> 503 * Bytes are read between <code>position()</code> and <code>limit()</code> 504 * of the {@link java.nio.ByteBuffer}. 505 * After the bytes have been read the <code>position()</code> will be 506 * advanced to its <code>limit()</code>. 507 * 508 * @param bytes 509 * The bytes to be decoded into characters 510 * 511 * @param charsetName 512 * The name of a supported {@linkplain java.nio.charset.Charset 513 * charset} 514 * 515 * @throws UnsupportedEncodingException 516 * If the named charset is not supported 517 * 518 * 519 * @since 1.9 520 */ 521 public String(ByteBuffer bytes, String charsetName) 522 throws UnsupportedEncodingException { 523 Objects.requireNonNull(bytes); 524 Objects.requireNonNull(charsetName); 525 this.value = StringCoding.decode(charsetName, bytes); 526 } 527 528 /** 529 * Constructs a new {@code String} by decoding the specified array of bytes 530 * using the specified {@linkplain java.nio.charset.Charset charset}. The 531 * length of the new {@code String} is a function of the charset, and hence 532 * may not be equal to the length of the byte array. 533 * 534 * <p> The behavior of this constructor when the given bytes are not valid 535 * in the given charset is unspecified. The {@link 536 * java.nio.charset.CharsetDecoder} class should be used when more control 537 * over the decoding process is required. 538 * 539 * @param bytes 540 * The bytes to be decoded into characters 541 * 542 * @param charsetName 543 * The name of a supported {@linkplain java.nio.charset.Charset 544 * charset} 545 * 546 * @throws UnsupportedEncodingException 547 * If the named charset is not supported 548 * 549 * @since 1.1 550 */ 551 public String(byte bytes[], String charsetName) 552 throws UnsupportedEncodingException { 553 this(bytes, 0, bytes.length, charsetName); 554 } 555 556 /** 557 * Constructs a new {@code String} by decoding the specified array of 558 * bytes using the specified {@linkplain java.nio.charset.Charset charset}. 559 * The length of the new {@code String} is a function of the charset, and 560 * hence may not be equal to the length of the byte array. 561 * 562 * <p> This method always replaces malformed-input and unmappable-character 563 * sequences with this charset's default replacement string. The {@link 564 * java.nio.charset.CharsetDecoder} class should be used when more control 565 * over the decoding process is required. 566 * 567 * @param bytes 568 * The bytes to be decoded into characters 569 * 570 * @param charset 571 * The {@linkplain java.nio.charset.Charset charset} to be used to 572 * decode the {@code bytes} 573 * 574 * @since 1.6 575 */ 576 public String(byte bytes[], Charset charset) { 577 this(bytes, 0, bytes.length, charset); 578 } 579 580 /** 581 * Constructs a new {@code String} by decoding the specified subarray of 582 * bytes using the platform's default charset. The length of the new 583 * {@code String} is a function of the charset, and hence may not be equal 584 * to the length of the subarray. 585 * 586 * <p> The behavior of this constructor when the given bytes are not valid 587 * in the default charset is unspecified. The {@link 588 * java.nio.charset.CharsetDecoder} class should be used when more control 589 * over the decoding process is required. 590 * 591 * @param bytes 592 * The bytes to be decoded into characters 593 * 594 * @param offset 595 * The index of the first byte to decode 596 * 597 * @param length 598 * The number of bytes to decode 599 * 600 * @throws IndexOutOfBoundsException 601 * If the {@code offset} and the {@code length} arguments index 602 * characters outside the bounds of the {@code bytes} array 603 * 604 * @since 1.1 605 */ 606 public String(byte bytes[], int offset, int length) { 607 checkBounds(bytes, offset, length); 608 this.value = StringCoding.decode(bytes, offset, length); 609 } 610 611 /** 612 * Constructs a new {@code String} by decoding the specified array of bytes 613 * using the platform's default charset. The length of the new {@code 614 * String} is a function of the charset, and hence may not be equal to the 615 * length of the byte array. 616 * 617 * <p> The behavior of this constructor when the given bytes are not valid 618 * in the default charset is unspecified. The {@link 619 * java.nio.charset.CharsetDecoder} class should be used when more control 620 * over the decoding process is required. 621 * 622 * @param bytes 623 * The bytes to be decoded into characters 624 * 625 * @since 1.1 626 */ 627 public String(byte bytes[]) { 628 this(bytes, 0, bytes.length); 629 } 630 631 /** 632 * Allocates a new string that contains the sequence of characters 633 * currently contained in the string buffer argument. The contents of the 634 * string buffer are copied; subsequent modification of the string buffer 635 * does not affect the newly created string. 636 * 637 * @param buffer 638 * A {@code StringBuffer} 639 */ 640 public String(StringBuffer buffer) { 641 synchronized(buffer) { 642 this.value = Arrays.copyOf(buffer.getValue(), buffer.length()); 643 } 644 } 645 646 /** 647 * Allocates a new string that contains the sequence of characters 648 * currently contained in the string builder argument. The contents of the 649 * string builder are copied; subsequent modification of the string builder 650 * does not affect the newly created string. 651 * 652 * <p> This constructor is provided to ease migration to {@code 653 * StringBuilder}. Obtaining a string from a string builder via the {@code 654 * toString} method is likely to run faster and is generally preferred. 655 * 656 * @param builder 657 * A {@code StringBuilder} 658 * 659 * @since 1.5 660 */ 661 public String(StringBuilder builder) { 662 this.value = Arrays.copyOf(builder.getValue(), builder.length()); 663 } 664 665 /* 666 * Package private constructor which shares value array for speed. 667 * this constructor is always expected to be called with share==true. 668 * a separate constructor is needed because we already have a public 669 * String(char[]) constructor that makes a copy of the given char[]. 670 */ 671 String(char[] value, boolean share) { 672 // assert share : "unshared not supported"; 673 this.value = value; 674 } 675 676 /** 677 * Returns the length of this string. 678 * The length is equal to the number of <a href="Character.html#unicode">Unicode 679 * code units</a> in the string. 680 * 681 * @return the length of the sequence of characters represented by this 682 * object. 683 */ 684 public int length() { 685 return value.length; 686 } 687 688 /** 689 * Returns {@code true} if, and only if, {@link #length()} is {@code 0}. 690 * 691 * @return {@code true} if {@link #length()} is {@code 0}, otherwise 692 * {@code false} 693 * 694 * @since 1.6 695 */ 696 public boolean isEmpty() { 697 return value.length == 0; 698 } 699 700 /** 701 * Returns the {@code char} value at the 702 * specified index. An index ranges from {@code 0} to 703 * {@code length() - 1}. The first {@code char} value of the sequence 704 * is at index {@code 0}, the next at index {@code 1}, 705 * and so on, as for array indexing. 706 * 707 * <p>If the {@code char} value specified by the index is a 708 * <a href="Character.html#unicode">surrogate</a>, the surrogate 709 * value is returned. 710 * 711 * @param index the index of the {@code char} value. 712 * @return the {@code char} value at the specified index of this string. 713 * The first {@code char} value is at index {@code 0}. 714 * @exception IndexOutOfBoundsException if the {@code index} 715 * argument is negative or not less than the length of this 716 * string. 717 */ 718 public char charAt(int index) { 719 if ((index < 0) || (index >= value.length)) { 720 throw new StringIndexOutOfBoundsException(index); 721 } 722 return value[index]; 723 } 724 725 /** 726 * Returns the character (Unicode code point) at the specified 727 * index. The index refers to {@code char} values 728 * (Unicode code units) and ranges from {@code 0} to 729 * {@link #length()}{@code - 1}. 730 * 731 * <p> If the {@code char} value specified at the given index 732 * is in the high-surrogate range, the following index is less 733 * than the length of this {@code String}, and the 734 * {@code char} value at the following index is in the 735 * low-surrogate range, then the supplementary code point 736 * corresponding to this surrogate pair is returned. Otherwise, 737 * the {@code char} value at the given index is returned. 738 * 739 * @param index the index to the {@code char} values 740 * @return the code point value of the character at the 741 * {@code index} 742 * @exception IndexOutOfBoundsException if the {@code index} 743 * argument is negative or not less than the length of this 744 * string. 745 * @since 1.5 746 */ 747 public int codePointAt(int index) { 748 if ((index < 0) || (index >= value.length)) { 749 throw new StringIndexOutOfBoundsException(index); 750 } 751 return Character.codePointAtImpl(value, index, value.length); 752 } 753 754 /** 755 * Returns the character (Unicode code point) before the specified 756 * index. The index refers to {@code char} values 757 * (Unicode code units) and ranges from {@code 1} to {@link 758 * CharSequence#length() length}. 759 * 760 * <p> If the {@code char} value at {@code (index - 1)} 761 * is in the low-surrogate range, {@code (index - 2)} is not 762 * negative, and the {@code char} value at {@code (index - 763 * 2)} is in the high-surrogate range, then the 764 * supplementary code point value of the surrogate pair is 765 * returned. If the {@code char} value at {@code index - 766 * 1} is an unpaired low-surrogate or a high-surrogate, the 767 * surrogate value is returned. 768 * 769 * @param index the index following the code point that should be returned 770 * @return the Unicode code point value before the given index. 771 * @exception IndexOutOfBoundsException if the {@code index} 772 * argument is less than 1 or greater than the length 773 * of this string. 774 * @since 1.5 775 */ 776 public int codePointBefore(int index) { 777 int i = index - 1; 778 if ((i < 0) || (i >= value.length)) { 779 throw new StringIndexOutOfBoundsException(index); 780 } 781 return Character.codePointBeforeImpl(value, index, 0); 782 } 783 784 /** 785 * Returns the number of Unicode code points in the specified text 786 * range of this {@code String}. The text range begins at the 787 * specified {@code beginIndex} and extends to the 788 * {@code char} at index {@code endIndex - 1}. Thus the 789 * length (in {@code char}s) of the text range is 790 * {@code endIndex-beginIndex}. Unpaired surrogates within 791 * the text range count as one code point each. 792 * 793 * @param beginIndex the index to the first {@code char} of 794 * the text range. 795 * @param endIndex the index after the last {@code char} of 796 * the text range. 797 * @return the number of Unicode code points in the specified text 798 * range 799 * @exception IndexOutOfBoundsException if the 800 * {@code beginIndex} is negative, or {@code endIndex} 801 * is larger than the length of this {@code String}, or 802 * {@code beginIndex} is larger than {@code endIndex}. 803 * @since 1.5 804 */ 805 public int codePointCount(int beginIndex, int endIndex) { 806 if (beginIndex < 0 || endIndex > value.length || beginIndex > endIndex) { 807 throw new IndexOutOfBoundsException(); 808 } 809 return Character.codePointCountImpl(value, beginIndex, endIndex - beginIndex); 810 } 811 812 /** 813 * Returns the index within this {@code String} that is 814 * offset from the given {@code index} by 815 * {@code codePointOffset} code points. Unpaired surrogates 816 * within the text range given by {@code index} and 817 * {@code codePointOffset} count as one code point each. 818 * 819 * @param index the index to be offset 820 * @param codePointOffset the offset in code points 821 * @return the index within this {@code String} 822 * @exception IndexOutOfBoundsException if {@code index} 823 * is negative or larger then the length of this 824 * {@code String}, or if {@code codePointOffset} is positive 825 * and the substring starting with {@code index} has fewer 826 * than {@code codePointOffset} code points, 827 * or if {@code codePointOffset} is negative and the substring 828 * before {@code index} has fewer than the absolute value 829 * of {@code codePointOffset} code points. 830 * @since 1.5 831 */ 832 public int offsetByCodePoints(int index, int codePointOffset) { 833 if (index < 0 || index > value.length) { 834 throw new IndexOutOfBoundsException(); 835 } 836 return Character.offsetByCodePointsImpl(value, 0, value.length, 837 index, codePointOffset); 838 } 839 840 /** 841 * Copy characters from this string into dst starting at dstBegin. 842 * This method doesn't perform any range checking. 843 */ 844 void getChars(char dst[], int dstBegin) { 845 System.arraycopy(value, 0, dst, dstBegin, value.length); 846 } 847 848 /** 849 * Copies characters from this string into the destination character 850 * array. 851 * <p> 852 * The first character to be copied is at index {@code srcBegin}; 853 * the last character to be copied is at index {@code srcEnd-1} 854 * (thus the total number of characters to be copied is 855 * {@code srcEnd-srcBegin}). The characters are copied into the 856 * subarray of {@code dst} starting at index {@code dstBegin} 857 * and ending at index: 858 * <blockquote><pre> 859 * dstbegin + (srcEnd-srcBegin) - 1 860 * </pre></blockquote> 861 * 862 * @param srcBegin index of the first character in the string 863 * to copy. 864 * @param srcEnd index after the last character in the string 865 * to copy. 866 * @param dst the destination array. 867 * @param dstBegin the start offset in the destination array. 868 * @exception IndexOutOfBoundsException If any of the following 869 * is true: 870 * <ul><li>{@code srcBegin} is negative. 871 * <li>{@code srcBegin} is greater than {@code srcEnd} 872 * <li>{@code srcEnd} is greater than the length of this 873 * string 874 * <li>{@code dstBegin} is negative 875 * <li>{@code dstBegin+(srcEnd-srcBegin)} is larger than 876 * {@code dst.length}</ul> 877 */ 878 public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) { 879 if (srcBegin < 0) { 880 throw new StringIndexOutOfBoundsException(srcBegin); 881 } 882 if (srcEnd > value.length) { 883 throw new StringIndexOutOfBoundsException(srcEnd); 884 } 885 if (srcBegin > srcEnd) { 886 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin); 887 } 888 System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin); 889 } 890 891 /** 892 * Copies characters from this string into the destination byte array. Each 893 * byte receives the 8 low-order bits of the corresponding character. The 894 * eight high-order bits of each character are not copied and do not 895 * participate in the transfer in any way. 896 * 897 * <p> The first character to be copied is at index {@code srcBegin}; the 898 * last character to be copied is at index {@code srcEnd-1}. The total 899 * number of characters to be copied is {@code srcEnd-srcBegin}. The 900 * characters, converted to bytes, are copied into the subarray of {@code 901 * dst} starting at index {@code dstBegin} and ending at index: 902 * 903 * <blockquote><pre> 904 * dstbegin + (srcEnd-srcBegin) - 1 905 * </pre></blockquote> 906 * 907 * @deprecated This method does not properly convert characters into 908 * bytes. As of JDK 1.1, the preferred way to do this is via the 909 * {@link #getBytes()} method, which uses the platform's default charset. 910 * 911 * @param srcBegin 912 * Index of the first character in the string to copy 913 * 914 * @param srcEnd 915 * Index after the last character in the string to copy 916 * 917 * @param dst 918 * The destination array 919 * 920 * @param dstBegin 921 * The start offset in the destination array 922 * 923 * @throws IndexOutOfBoundsException 924 * If any of the following is true: 925 * <ul> 926 * <li> {@code srcBegin} is negative 927 * <li> {@code srcBegin} is greater than {@code srcEnd} 928 * <li> {@code srcEnd} is greater than the length of this String 929 * <li> {@code dstBegin} is negative 930 * <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code 931 * dst.length} 932 * </ul> 933 */ 934 @Deprecated 935 public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) { 936 if (srcBegin < 0) { 937 throw new StringIndexOutOfBoundsException(srcBegin); 938 } 939 if (srcEnd > value.length) { 940 throw new StringIndexOutOfBoundsException(srcEnd); 941 } 942 if (srcBegin > srcEnd) { 943 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin); 944 } 945 Objects.requireNonNull(dst); 946 947 int j = dstBegin; 948 int n = srcEnd; 949 int i = srcBegin; 950 char[] val = value; /* avoid getfield opcode */ 951 952 while (i < n) { 953 dst[j++] = (byte)val[i++]; 954 } 955 } 956 957 /** 958 * Encodes this {@code String} into a sequence of bytes using the named 959 * charset, storing the result into a new byte array. 960 * 961 * <p> The behavior of this method when this string cannot be encoded in 962 * the given charset is unspecified. The {@link 963 * java.nio.charset.CharsetEncoder} class should be used when more control 964 * over the encoding process is required. 965 * 966 * @param charsetName 967 * The name of a supported {@linkplain java.nio.charset.Charset 968 * charset} 969 * 970 * @return The resultant byte array 971 * 972 * @throws UnsupportedEncodingException 973 * If the named charset is not supported 974 * 975 * @since 1.1 976 */ 977 public byte[] getBytes(String charsetName) 978 throws UnsupportedEncodingException { 979 if (charsetName == null) throw new NullPointerException(); 980 return StringCoding.encode(charsetName, value, 0, value.length); 981 } 982 983 /** 984 * Encodes this {@code String} into a sequence of bytes using the given 985 * {@linkplain java.nio.charset.Charset charset}, storing the result into a 986 * new byte array. 987 * 988 * <p> This method always replaces malformed-input and unmappable-character 989 * sequences with this charset's default replacement byte array. The 990 * {@link java.nio.charset.CharsetEncoder} class should be used when more 991 * control over the encoding process is required. 992 * 993 * @param charset 994 * The {@linkplain java.nio.charset.Charset} to be used to encode 995 * the {@code String} 996 * 997 * @return The resultant byte array 998 * 999 * @since 1.6 1000 */ 1001 public byte[] getBytes(Charset charset) { 1002 Objects.requireNonNull(charset); 1003 return StringCoding.encode(charset, value, 0, value.length); 1004 } 1005 1006 /** 1007 * Encodes this {@code String} into a sequence of bytes using the given 1008 * {@linkplain java.nio.charset.Charset charset}, storing the result into a 1009 * byte array that has been passed as an argument. 1010 * 1011 * <p> This method always replaces malformed-input and unmappable-character 1012 * sequences with this charset's default replacement byte array. The {@link 1013 * java.nio.charset.CharsetDecoder} class should be used when more control 1014 * over the decoding process is required. 1015 * 1016 * <p> The number of bytes written during encoding is a function of the charset 1017 * used to perform the encoding and is returned from this method. It may not 1018 * be equal to the length of this 1019 * String. At most <code>destBuffer.length - destOffset</code> bytes will be written. 1020 * 1021 * @param destBuffer 1022 * The destination array 1023 * 1024 * @param destOffset 1025 * The start offset in the destination array 1026 * 1027 * @param charset 1028 * The {@linkplain java.nio.charset.Charset} to be used to encode 1029 * the {@code String} 1030 * 1031 * @return the number of bytes written 1032 * 1033 * @since 1.9 1034 */ 1035 public int getBytes(byte[] destBuffer, int destOffset, Charset charset) { 1036 Objects.requireNonNull(destBuffer); 1037 Objects.requireNonNull(charset); 1038 return StringCoding.encode(charset, value, 0, value.length, destBuffer, destOffset); 1039 } 1040 1041 /** 1042 * Encodes as many characters as possible from this {@code String} into a 1043 * sequence of bytes using the given 1044 * {@linkplain java.nio.charset.Charset charset}, storing the result into a 1045 * {@linkplain java.nio.ByteBuffer byte buffer} that has been passed as an argument. 1046 * 1047 * <p> The number of bytes written during encoding is a function of the charset 1048 * used to perform the encoding and is returned from this method. It may not 1049 * be equal to the length of this 1050 * String. At most <code>destBuffer.remaining()</code> bytes will be written. 1051 * 1052 * <p> This method always replaces malformed-input and unmappable-character 1053 * sequences with this charset's default replacement byte array. The {@link 1054 * java.nio.charset.CharsetDecoder} class should be used when more control 1055 * over the decoding process is required. 1056 * 1057 * <p> The buffer's position will be advanced to reflect the number of 1058 * the bytes written, but its mark and limit will not be modified. 1059 * 1060 * @param destBuffer 1061 * The destination {@linkplain java.nio.ByteBuffer} 1062 * 1063 * @param charset 1064 * The {@linkplain java.nio.charset.Charset} to be used to encode 1065 * the {@code String} 1066 * 1067 * @return the number of bytes written 1068 * 1069 * @since 1.9 1070 */ 1071 public int getBytes(ByteBuffer destBuffer, Charset charset) { 1072 Objects.requireNonNull(destBuffer); 1073 Objects.requireNonNull(charset); 1074 return StringCoding.encode(charset, value, 0, value.length, destBuffer); 1075 } 1076 1077 /** 1078 * Encodes as many characters as possible from this {@code String} into a 1079 * sequence of bytes using the specified charset, storing the result into a 1080 * {@linkplain java.nio.ByteBuffer byte buffer} that has been passed as an argument. 1081 * 1082 * <p> The number of bytes written during encoding is a function of the charset 1083 * used to perform the encoding and is returned from this method. It may not 1084 * be equal to the length of this 1085 * String. At most <code>destBuffer.remaining()</code> bytes will be written. 1086 * 1087 * <p> This method always replaces malformed-input and unmappable-character 1088 * sequences with this charset's default replacement byte array. The {@link 1089 * java.nio.charset.CharsetDecoder} class should be used when more control 1090 * over the decoding process is required. 1091 * 1092 * <p> The buffer's position will be advanced to reflect the number of 1093 * the bytes written, but its mark and limit will not be modified. 1094 * 1095 * @param destBuffer 1096 * The destination {@linkplain java.nio.ByteBuffer} 1097 * 1098 * @param charsetName 1099 * The name of a supported {@linkplain java.nio.charset.Charset 1100 * charset} 1101 * 1102 * @return the number of bytes written 1103 * 1104 * @throws UnsupportedEncodingException 1105 * If the named charset is not supported 1106 * 1107 * @since 1.9 1108 */ 1109 public int getBytes(ByteBuffer destBuffer, String charsetName) throws UnsupportedEncodingException { 1110 Objects.requireNonNull(destBuffer); 1111 Objects.requireNonNull(charsetName); 1112 return StringCoding.encode(charsetName, value, 0, value.length, destBuffer); 1113 } 1114 1115 /** 1116 * Encodes as many characters as possible from this {@code String} into a 1117 * sequence of bytes using the specified charset, storing the result into a 1118 * byte array that has been passed as an argument. 1119 * 1120 * <p> The number of bytes written during encoding is a function of the charset 1121 * used to perform the encoding and is returned from this method. It may not 1122 * be equal to the length of this 1123 * String. At most <code>destBuffer.length - destOffset</code> bytes will be written. 1124 * 1125 * <p> This method always replaces malformed-input and unmappable-character 1126 * sequences with this charset's default replacement byte array. The {@link 1127 * java.nio.charset.CharsetDecoder} class should be used when more control 1128 * over the decoding process is required. 1129 * 1130 * @param destBuffer 1131 * The destination array 1132 * 1133 * @param destOffset 1134 * The start offset in the destination array 1135 * 1136 * @param charsetName 1137 * The name of a supported {@linkplain java.nio.charset.Charset 1138 * charset} 1139 * 1140 * @return the number of bytes written 1141 * 1142 * @throws UnsupportedEncodingException 1143 * If the named charset is not supported 1144 * 1145 * @since 1.9 1146 */ 1147 public int getBytes(byte[] destBuffer, int destOffset, String charsetName) throws UnsupportedEncodingException { 1148 Objects.requireNonNull(destBuffer); 1149 Objects.requireNonNull(charsetName); 1150 return StringCoding.encode(charsetName, value, 0, value.length, destBuffer, destOffset); 1151 } 1152 1153 /** 1154 * Encodes this {@code String} into a sequence of bytes using the 1155 * platform's default charset, storing the result into a new byte array. 1156 * 1157 * <p> The behavior of this method when this string cannot be encoded in 1158 * the default charset is unspecified. The {@link 1159 * java.nio.charset.CharsetEncoder} class should be used when more control 1160 * over the encoding process is required. 1161 * 1162 * @return The resultant byte array 1163 * 1164 * @since 1.1 1165 */ 1166 public byte[] getBytes() { 1167 return StringCoding.encode(value, 0, value.length); 1168 } 1169 1170 /** 1171 * Compares this string to the specified object. The result is {@code 1172 * true} if and only if the argument is not {@code null} and is a {@code 1173 * String} object that represents the same sequence of characters as this 1174 * object. 1175 * 1176 * @param anObject 1177 * The object to compare this {@code String} against 1178 * 1179 * @return {@code true} if the given object represents a {@code String} 1180 * equivalent to this string, {@code false} otherwise 1181 * 1182 * @see #compareTo(String) 1183 * @see #equalsIgnoreCase(String) 1184 */ 1185 public boolean equals(Object anObject) { 1186 if (this == anObject) { 1187 return true; 1188 } 1189 if (anObject instanceof String) { 1190 String anotherString = (String)anObject; 1191 int n = value.length; 1192 if (n == anotherString.value.length) { 1193 char v1[] = value; 1194 char v2[] = anotherString.value; 1195 int i = 0; 1196 while (n-- != 0) { 1197 if (v1[i] != v2[i]) 1198 return false; 1199 i++; 1200 } 1201 return true; 1202 } 1203 } 1204 return false; 1205 } 1206 1207 /** 1208 * Compares this string to the specified {@code StringBuffer}. The result 1209 * is {@code true} if and only if this {@code String} represents the same 1210 * sequence of characters as the specified {@code StringBuffer}. This method 1211 * synchronizes on the {@code StringBuffer}. 1212 * 1213 * @param sb 1214 * The {@code StringBuffer} to compare this {@code String} against 1215 * 1216 * @return {@code true} if this {@code String} represents the same 1217 * sequence of characters as the specified {@code StringBuffer}, 1218 * {@code false} otherwise 1219 * 1220 * @since 1.4 1221 */ 1222 public boolean contentEquals(StringBuffer sb) { 1223 return contentEquals((CharSequence)sb); 1224 } 1225 1226 private boolean nonSyncContentEquals(AbstractStringBuilder sb) { 1227 char v1[] = value; 1228 char v2[] = sb.getValue(); 1229 int n = v1.length; 1230 if (n != sb.length()) { 1231 return false; 1232 } 1233 for (int i = 0; i < n; i++) { 1234 if (v1[i] != v2[i]) { 1235 return false; 1236 } 1237 } 1238 return true; 1239 } 1240 1241 /** 1242 * Compares this string to the specified {@code CharSequence}. The 1243 * result is {@code true} if and only if this {@code String} represents the 1244 * same sequence of char values as the specified sequence. Note that if the 1245 * {@code CharSequence} is a {@code StringBuffer} then the method 1246 * synchronizes on it. 1247 * 1248 * @param cs 1249 * The sequence to compare this {@code String} against 1250 * 1251 * @return {@code true} if this {@code String} represents the same 1252 * sequence of char values as the specified sequence, {@code 1253 * false} otherwise 1254 * 1255 * @since 1.5 1256 */ 1257 public boolean contentEquals(CharSequence cs) { 1258 // Argument is a StringBuffer, StringBuilder 1259 if (cs instanceof AbstractStringBuilder) { 1260 if (cs instanceof StringBuffer) { 1261 synchronized(cs) { 1262 return nonSyncContentEquals((AbstractStringBuilder)cs); 1263 } 1264 } else { 1265 return nonSyncContentEquals((AbstractStringBuilder)cs); 1266 } 1267 } 1268 // Argument is a String 1269 if (cs instanceof String) { 1270 return equals(cs); 1271 } 1272 // Argument is a generic CharSequence 1273 char v1[] = value; 1274 int n = v1.length; 1275 if (n != cs.length()) { 1276 return false; 1277 } 1278 for (int i = 0; i < n; i++) { 1279 if (v1[i] != cs.charAt(i)) { 1280 return false; 1281 } 1282 } 1283 return true; 1284 } 1285 1286 /** 1287 * Compares this {@code String} to another {@code String}, ignoring case 1288 * considerations. Two strings are considered equal ignoring case if they 1289 * are of the same length and corresponding characters in the two strings 1290 * are equal ignoring case. 1291 * 1292 * <p> Two characters {@code c1} and {@code c2} are considered the same 1293 * ignoring case if at least one of the following is true: 1294 * <ul> 1295 * <li> The two characters are the same (as compared by the 1296 * {@code ==} operator) 1297 * <li> Applying the method {@link 1298 * java.lang.Character#toUpperCase(char)} to each character 1299 * produces the same result 1300 * <li> Applying the method {@link 1301 * java.lang.Character#toLowerCase(char)} to each character 1302 * produces the same result 1303 * </ul> 1304 * 1305 * @param anotherString 1306 * The {@code String} to compare this {@code String} against 1307 * 1308 * @return {@code true} if the argument is not {@code null} and it 1309 * represents an equivalent {@code String} ignoring case; {@code 1310 * false} otherwise 1311 * 1312 * @see #equals(Object) 1313 */ 1314 public boolean equalsIgnoreCase(String anotherString) { 1315 return (this == anotherString) ? true 1316 : (anotherString != null) 1317 && (anotherString.value.length == value.length) 1318 && regionMatches(true, 0, anotherString, 0, value.length); 1319 } 1320 1321 /** 1322 * Compares two strings lexicographically. 1323 * The comparison is based on the Unicode value of each character in 1324 * the strings. The character sequence represented by this 1325 * {@code String} object is compared lexicographically to the 1326 * character sequence represented by the argument string. The result is 1327 * a negative integer if this {@code String} object 1328 * lexicographically precedes the argument string. The result is a 1329 * positive integer if this {@code String} object lexicographically 1330 * follows the argument string. The result is zero if the strings 1331 * are equal; {@code compareTo} returns {@code 0} exactly when 1332 * the {@link #equals(Object)} method would return {@code true}. 1333 * <p> 1334 * This is the definition of lexicographic ordering. If two strings are 1335 * different, then either they have different characters at some index 1336 * that is a valid index for both strings, or their lengths are different, 1337 * or both. If they have different characters at one or more index 1338 * positions, let <i>k</i> be the smallest such index; then the string 1339 * whose character at position <i>k</i> has the smaller value, as 1340 * determined by using the < operator, lexicographically precedes the 1341 * other string. In this case, {@code compareTo} returns the 1342 * difference of the two character values at position {@code k} in 1343 * the two string -- that is, the value: 1344 * <blockquote><pre> 1345 * this.charAt(k)-anotherString.charAt(k) 1346 * </pre></blockquote> 1347 * If there is no index position at which they differ, then the shorter 1348 * string lexicographically precedes the longer string. In this case, 1349 * {@code compareTo} returns the difference of the lengths of the 1350 * strings -- that is, the value: 1351 * <blockquote><pre> 1352 * this.length()-anotherString.length() 1353 * </pre></blockquote> 1354 * 1355 * @param anotherString the {@code String} to be compared. 1356 * @return the value {@code 0} if the argument string is equal to 1357 * this string; a value less than {@code 0} if this string 1358 * is lexicographically less than the string argument; and a 1359 * value greater than {@code 0} if this string is 1360 * lexicographically greater than the string argument. 1361 */ 1362 public int compareTo(String anotherString) { 1363 int len1 = value.length; 1364 int len2 = anotherString.value.length; 1365 int lim = Math.min(len1, len2); 1366 char v1[] = value; 1367 char v2[] = anotherString.value; 1368 1369 int k = 0; 1370 while (k < lim) { 1371 char c1 = v1[k]; 1372 char c2 = v2[k]; 1373 if (c1 != c2) { 1374 return c1 - c2; 1375 } 1376 k++; 1377 } 1378 return len1 - len2; 1379 } 1380 1381 /** 1382 * A Comparator that orders {@code String} objects as by 1383 * {@code compareToIgnoreCase}. This comparator is serializable. 1384 * <p> 1385 * Note that this Comparator does <em>not</em> take locale into account, 1386 * and will result in an unsatisfactory ordering for certain locales. 1387 * The java.text package provides <em>Collators</em> to allow 1388 * locale-sensitive ordering. 1389 * 1390 * @see java.text.Collator#compare(String, String) 1391 * @since 1.2 1392 */ 1393 public static final Comparator<String> CASE_INSENSITIVE_ORDER 1394 = new CaseInsensitiveComparator(); 1395 private static class CaseInsensitiveComparator 1396 implements Comparator<String>, java.io.Serializable { 1397 // use serialVersionUID from JDK 1.2.2 for interoperability 1398 private static final long serialVersionUID = 8575799808933029326L; 1399 1400 public int compare(String s1, String s2) { 1401 int n1 = s1.length(); 1402 int n2 = s2.length(); 1403 int min = Math.min(n1, n2); 1404 for (int i = 0; i < min; i++) { 1405 char c1 = s1.charAt(i); 1406 char c2 = s2.charAt(i); 1407 if (c1 != c2) { 1408 c1 = Character.toUpperCase(c1); 1409 c2 = Character.toUpperCase(c2); 1410 if (c1 != c2) { 1411 c1 = Character.toLowerCase(c1); 1412 c2 = Character.toLowerCase(c2); 1413 if (c1 != c2) { 1414 // No overflow because of numeric promotion 1415 return c1 - c2; 1416 } 1417 } 1418 } 1419 } 1420 return n1 - n2; 1421 } 1422 1423 /** Replaces the de-serialized object. */ 1424 private Object readResolve() { return CASE_INSENSITIVE_ORDER; } 1425 } 1426 1427 /** 1428 * Compares two strings lexicographically, ignoring case 1429 * differences. This method returns an integer whose sign is that of 1430 * calling {@code compareTo} with normalized versions of the strings 1431 * where case differences have been eliminated by calling 1432 * {@code Character.toLowerCase(Character.toUpperCase(character))} on 1433 * each character. 1434 * <p> 1435 * Note that this method does <em>not</em> take locale into account, 1436 * and will result in an unsatisfactory ordering for certain locales. 1437 * The java.text package provides <em>collators</em> to allow 1438 * locale-sensitive ordering. 1439 * 1440 * @param str the {@code String} to be compared. 1441 * @return a negative integer, zero, or a positive integer as the 1442 * specified String is greater than, equal to, or less 1443 * than this String, ignoring case considerations. 1444 * @see java.text.Collator#compare(String, String) 1445 * @since 1.2 1446 */ 1447 public int compareToIgnoreCase(String str) { 1448 return CASE_INSENSITIVE_ORDER.compare(this, str); 1449 } 1450 1451 /** 1452 * Tests if two string regions are equal. 1453 * <p> 1454 * A substring of this {@code String} object is compared to a substring 1455 * of the argument other. The result is true if these substrings 1456 * represent identical character sequences. The substring of this 1457 * {@code String} object to be compared begins at index {@code toffset} 1458 * and has length {@code len}. The substring of other to be compared 1459 * begins at index {@code ooffset} and has length {@code len}. The 1460 * result is {@code false} if and only if at least one of the following 1461 * is true: 1462 * <ul><li>{@code toffset} is negative. 1463 * <li>{@code ooffset} is negative. 1464 * <li>{@code toffset+len} is greater than the length of this 1465 * {@code String} object. 1466 * <li>{@code ooffset+len} is greater than the length of the other 1467 * argument. 1468 * <li>There is some nonnegative integer <i>k</i> less than {@code len} 1469 * such that: 1470 * {@code this.charAt(toffset + }<i>k</i>{@code ) != other.charAt(ooffset + } 1471 * <i>k</i>{@code )} 1472 * </ul> 1473 * 1474 * @param toffset the starting offset of the subregion in this string. 1475 * @param other the string argument. 1476 * @param ooffset the starting offset of the subregion in the string 1477 * argument. 1478 * @param len the number of characters to compare. 1479 * @return {@code true} if the specified subregion of this string 1480 * exactly matches the specified subregion of the string argument; 1481 * {@code false} otherwise. 1482 */ 1483 public boolean regionMatches(int toffset, String other, int ooffset, 1484 int len) { 1485 char ta[] = value; 1486 int to = toffset; 1487 char pa[] = other.value; 1488 int po = ooffset; 1489 // Note: toffset, ooffset, or len might be near -1>>>1. 1490 if ((ooffset < 0) || (toffset < 0) 1491 || (toffset > (long)value.length - len) 1492 || (ooffset > (long)other.value.length - len)) { 1493 return false; 1494 } 1495 while (len-- > 0) { 1496 if (ta[to++] != pa[po++]) { 1497 return false; 1498 } 1499 } 1500 return true; 1501 } 1502 1503 /** 1504 * Tests if two string regions are equal. 1505 * <p> 1506 * A substring of this {@code String} object is compared to a substring 1507 * of the argument {@code other}. The result is {@code true} if these 1508 * substrings represent character sequences that are the same, ignoring 1509 * case if and only if {@code ignoreCase} is true. The substring of 1510 * this {@code String} object to be compared begins at index 1511 * {@code toffset} and has length {@code len}. The substring of 1512 * {@code other} to be compared begins at index {@code ooffset} and 1513 * has length {@code len}. The result is {@code false} if and only if 1514 * at least one of the following is true: 1515 * <ul><li>{@code toffset} is negative. 1516 * <li>{@code ooffset} is negative. 1517 * <li>{@code toffset+len} is greater than the length of this 1518 * {@code String} object. 1519 * <li>{@code ooffset+len} is greater than the length of the other 1520 * argument. 1521 * <li>{@code ignoreCase} is {@code false} and there is some nonnegative 1522 * integer <i>k</i> less than {@code len} such that: 1523 * <blockquote><pre> 1524 * this.charAt(toffset+k) != other.charAt(ooffset+k) 1525 * </pre></blockquote> 1526 * <li>{@code ignoreCase} is {@code true} and there is some nonnegative 1527 * integer <i>k</i> less than {@code len} such that: 1528 * <blockquote><pre> 1529 * Character.toLowerCase(this.charAt(toffset+k)) != 1530 Character.toLowerCase(other.charAt(ooffset+k)) 1531 * </pre></blockquote> 1532 * and: 1533 * <blockquote><pre> 1534 * Character.toUpperCase(this.charAt(toffset+k)) != 1535 * Character.toUpperCase(other.charAt(ooffset+k)) 1536 * </pre></blockquote> 1537 * </ul> 1538 * 1539 * @param ignoreCase if {@code true}, ignore case when comparing 1540 * characters. 1541 * @param toffset the starting offset of the subregion in this 1542 * string. 1543 * @param other the string argument. 1544 * @param ooffset the starting offset of the subregion in the string 1545 * argument. 1546 * @param len the number of characters to compare. 1547 * @return {@code true} if the specified subregion of this string 1548 * matches the specified subregion of the string argument; 1549 * {@code false} otherwise. Whether the matching is exact 1550 * or case insensitive depends on the {@code ignoreCase} 1551 * argument. 1552 */ 1553 public boolean regionMatches(boolean ignoreCase, int toffset, 1554 String other, int ooffset, int len) { 1555 char ta[] = value; 1556 int to = toffset; 1557 char pa[] = other.value; 1558 int po = ooffset; 1559 // Note: toffset, ooffset, or len might be near -1>>>1. 1560 if ((ooffset < 0) || (toffset < 0) 1561 || (toffset > (long)value.length - len) 1562 || (ooffset > (long)other.value.length - len)) { 1563 return false; 1564 } 1565 while (len-- > 0) { 1566 char c1 = ta[to++]; 1567 char c2 = pa[po++]; 1568 if (c1 == c2) { 1569 continue; 1570 } 1571 if (ignoreCase) { 1572 // If characters don't match but case may be ignored, 1573 // try converting both characters to uppercase. 1574 // If the results match, then the comparison scan should 1575 // continue. 1576 char u1 = Character.toUpperCase(c1); 1577 char u2 = Character.toUpperCase(c2); 1578 if (u1 == u2) { 1579 continue; 1580 } 1581 // Unfortunately, conversion to uppercase does not work properly 1582 // for the Georgian alphabet, which has strange rules about case 1583 // conversion. So we need to make one last check before 1584 // exiting. 1585 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) { 1586 continue; 1587 } 1588 } 1589 return false; 1590 } 1591 return true; 1592 } 1593 1594 /** 1595 * Tests if the substring of this string beginning at the 1596 * specified index starts with the specified prefix. 1597 * 1598 * @param prefix the prefix. 1599 * @param toffset where to begin looking in this string. 1600 * @return {@code true} if the character sequence represented by the 1601 * argument is a prefix of the substring of this object starting 1602 * at index {@code toffset}; {@code false} otherwise. 1603 * The result is {@code false} if {@code toffset} is 1604 * negative or greater than the length of this 1605 * {@code String} object; otherwise the result is the same 1606 * as the result of the expression 1607 * <pre> 1608 * this.substring(toffset).startsWith(prefix) 1609 * </pre> 1610 */ 1611 public boolean startsWith(String prefix, int toffset) { 1612 char ta[] = value; 1613 int to = toffset; 1614 char pa[] = prefix.value; 1615 int po = 0; 1616 int pc = prefix.value.length; 1617 // Note: toffset might be near -1>>>1. 1618 if ((toffset < 0) || (toffset > value.length - pc)) { 1619 return false; 1620 } 1621 while (--pc >= 0) { 1622 if (ta[to++] != pa[po++]) { 1623 return false; 1624 } 1625 } 1626 return true; 1627 } 1628 1629 /** 1630 * Tests if this string starts with the specified prefix. 1631 * 1632 * @param prefix the prefix. 1633 * @return {@code true} if the character sequence represented by the 1634 * argument is a prefix of the character sequence represented by 1635 * this string; {@code false} otherwise. 1636 * Note also that {@code true} will be returned if the 1637 * argument is an empty string or is equal to this 1638 * {@code String} object as determined by the 1639 * {@link #equals(Object)} method. 1640 * @since 1.0 1641 */ 1642 public boolean startsWith(String prefix) { 1643 return startsWith(prefix, 0); 1644 } 1645 1646 /** 1647 * Tests if this string ends with the specified suffix. 1648 * 1649 * @param suffix the suffix. 1650 * @return {@code true} if the character sequence represented by the 1651 * argument is a suffix of the character sequence represented by 1652 * this object; {@code false} otherwise. Note that the 1653 * result will be {@code true} if the argument is the 1654 * empty string or is equal to this {@code String} object 1655 * as determined by the {@link #equals(Object)} method. 1656 */ 1657 public boolean endsWith(String suffix) { 1658 return startsWith(suffix, value.length - suffix.value.length); 1659 } 1660 1661 /** 1662 * Returns a hash code for this string. The hash code for a 1663 * {@code String} object is computed as 1664 * <blockquote><pre> 1665 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 1666 * </pre></blockquote> 1667 * using {@code int} arithmetic, where {@code s[i]} is the 1668 * <i>i</i>th character of the string, {@code n} is the length of 1669 * the string, and {@code ^} indicates exponentiation. 1670 * (The hash value of the empty string is zero.) 1671 * 1672 * @return a hash code value for this object. 1673 */ 1674 public int hashCode() { 1675 int h = hash; 1676 if (h == 0) { 1677 for (char v : value) { 1678 h = 31 * h + v; 1679 } 1680 hash = h; 1681 } 1682 return h; 1683 } 1684 1685 /** 1686 * Returns the index within this string of the first occurrence of 1687 * the specified character. If a character with value 1688 * {@code ch} occurs in the character sequence represented by 1689 * this {@code String} object, then the index (in Unicode 1690 * code units) of the first such occurrence is returned. For 1691 * values of {@code ch} in the range from 0 to 0xFFFF 1692 * (inclusive), this is the smallest value <i>k</i> such that: 1693 * <blockquote><pre> 1694 * this.charAt(<i>k</i>) == ch 1695 * </pre></blockquote> 1696 * is true. For other values of {@code ch}, it is the 1697 * smallest value <i>k</i> such that: 1698 * <blockquote><pre> 1699 * this.codePointAt(<i>k</i>) == ch 1700 * </pre></blockquote> 1701 * is true. In either case, if no such character occurs in this 1702 * string, then {@code -1} is returned. 1703 * 1704 * @param ch a character (Unicode code point). 1705 * @return the index of the first occurrence of the character in the 1706 * character sequence represented by this object, or 1707 * {@code -1} if the character does not occur. 1708 */ 1709 public int indexOf(int ch) { 1710 return indexOf(ch, 0); 1711 } 1712 1713 /** 1714 * Returns the index within this string of the first occurrence of the 1715 * specified character, starting the search at the specified index. 1716 * <p> 1717 * If a character with value {@code ch} occurs in the 1718 * character sequence represented by this {@code String} 1719 * object at an index no smaller than {@code fromIndex}, then 1720 * the index of the first such occurrence is returned. For values 1721 * of {@code ch} in the range from 0 to 0xFFFF (inclusive), 1722 * this is the smallest value <i>k</i> such that: 1723 * <blockquote><pre> 1724 * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> >= fromIndex) 1725 * </pre></blockquote> 1726 * is true. For other values of {@code ch}, it is the 1727 * smallest value <i>k</i> such that: 1728 * <blockquote><pre> 1729 * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> >= fromIndex) 1730 * </pre></blockquote> 1731 * is true. In either case, if no such character occurs in this 1732 * string at or after position {@code fromIndex}, then 1733 * {@code -1} is returned. 1734 * 1735 * <p> 1736 * There is no restriction on the value of {@code fromIndex}. If it 1737 * is negative, it has the same effect as if it were zero: this entire 1738 * string may be searched. If it is greater than the length of this 1739 * string, it has the same effect as if it were equal to the length of 1740 * this string: {@code -1} is returned. 1741 * 1742 * <p>All indices are specified in {@code char} values 1743 * (Unicode code units). 1744 * 1745 * @param ch a character (Unicode code point). 1746 * @param fromIndex the index to start the search from. 1747 * @return the index of the first occurrence of the character in the 1748 * character sequence represented by this object that is greater 1749 * than or equal to {@code fromIndex}, or {@code -1} 1750 * if the character does not occur. 1751 */ 1752 public int indexOf(int ch, int fromIndex) { 1753 final int max = value.length; 1754 if (fromIndex < 0) { 1755 fromIndex = 0; 1756 } else if (fromIndex >= max) { 1757 // Note: fromIndex might be near -1>>>1. 1758 return -1; 1759 } 1760 1761 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { 1762 // handle most cases here (ch is a BMP code point or a 1763 // negative value (invalid code point)) 1764 final char[] value = this.value; 1765 for (int i = fromIndex; i < max; i++) { 1766 if (value[i] == ch) { 1767 return i; 1768 } 1769 } 1770 return -1; 1771 } else { 1772 return indexOfSupplementary(ch, fromIndex); 1773 } 1774 } 1775 1776 /** 1777 * Handles (rare) calls of indexOf with a supplementary character. 1778 */ 1779 private int indexOfSupplementary(int ch, int fromIndex) { 1780 if (Character.isValidCodePoint(ch)) { 1781 final char[] value = this.value; 1782 final char hi = Character.highSurrogate(ch); 1783 final char lo = Character.lowSurrogate(ch); 1784 final int max = value.length - 1; 1785 for (int i = fromIndex; i < max; i++) { 1786 if (value[i] == hi && value[i + 1] == lo) { 1787 return i; 1788 } 1789 } 1790 } 1791 return -1; 1792 } 1793 1794 /** 1795 * Returns the index within this string of the last occurrence of 1796 * the specified character. For values of {@code ch} in the 1797 * range from 0 to 0xFFFF (inclusive), the index (in Unicode code 1798 * units) returned is the largest value <i>k</i> such that: 1799 * <blockquote><pre> 1800 * this.charAt(<i>k</i>) == ch 1801 * </pre></blockquote> 1802 * is true. For other values of {@code ch}, it is the 1803 * largest value <i>k</i> such that: 1804 * <blockquote><pre> 1805 * this.codePointAt(<i>k</i>) == ch 1806 * </pre></blockquote> 1807 * is true. In either case, if no such character occurs in this 1808 * string, then {@code -1} is returned. The 1809 * {@code String} is searched backwards starting at the last 1810 * character. 1811 * 1812 * @param ch a character (Unicode code point). 1813 * @return the index of the last occurrence of the character in the 1814 * character sequence represented by this object, or 1815 * {@code -1} if the character does not occur. 1816 */ 1817 public int lastIndexOf(int ch) { 1818 return lastIndexOf(ch, value.length - 1); 1819 } 1820 1821 /** 1822 * Returns the index within this string of the last occurrence of 1823 * the specified character, searching backward starting at the 1824 * specified index. For values of {@code ch} in the range 1825 * from 0 to 0xFFFF (inclusive), the index returned is the largest 1826 * value <i>k</i> such that: 1827 * <blockquote><pre> 1828 * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> <= fromIndex) 1829 * </pre></blockquote> 1830 * is true. For other values of {@code ch}, it is the 1831 * largest value <i>k</i> such that: 1832 * <blockquote><pre> 1833 * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> <= fromIndex) 1834 * </pre></blockquote> 1835 * is true. In either case, if no such character occurs in this 1836 * string at or before position {@code fromIndex}, then 1837 * {@code -1} is returned. 1838 * 1839 * <p>All indices are specified in {@code char} values 1840 * (Unicode code units). 1841 * 1842 * @param ch a character (Unicode code point). 1843 * @param fromIndex the index to start the search from. There is no 1844 * restriction on the value of {@code fromIndex}. If it is 1845 * greater than or equal to the length of this string, it has 1846 * the same effect as if it were equal to one less than the 1847 * length of this string: this entire string may be searched. 1848 * If it is negative, it has the same effect as if it were -1: 1849 * -1 is returned. 1850 * @return the index of the last occurrence of the character in the 1851 * character sequence represented by this object that is less 1852 * than or equal to {@code fromIndex}, or {@code -1} 1853 * if the character does not occur before that point. 1854 */ 1855 public int lastIndexOf(int ch, int fromIndex) { 1856 if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { 1857 // handle most cases here (ch is a BMP code point or a 1858 // negative value (invalid code point)) 1859 final char[] value = this.value; 1860 int i = Math.min(fromIndex, value.length - 1); 1861 for (; i >= 0; i--) { 1862 if (value[i] == ch) { 1863 return i; 1864 } 1865 } 1866 return -1; 1867 } else { 1868 return lastIndexOfSupplementary(ch, fromIndex); 1869 } 1870 } 1871 1872 /** 1873 * Handles (rare) calls of lastIndexOf with a supplementary character. 1874 */ 1875 private int lastIndexOfSupplementary(int ch, int fromIndex) { 1876 if (Character.isValidCodePoint(ch)) { 1877 final char[] value = this.value; 1878 char hi = Character.highSurrogate(ch); 1879 char lo = Character.lowSurrogate(ch); 1880 int i = Math.min(fromIndex, value.length - 2); 1881 for (; i >= 0; i--) { 1882 if (value[i] == hi && value[i + 1] == lo) { 1883 return i; 1884 } 1885 } 1886 } 1887 return -1; 1888 } 1889 1890 /** 1891 * Returns the index within this string of the first occurrence of the 1892 * specified substring. 1893 * 1894 * <p>The returned index is the smallest value {@code k} for which: 1895 * <pre>{@code 1896 * this.startsWith(str, k) 1897 * }</pre> 1898 * If no such value of {@code k} exists, then {@code -1} is returned. 1899 * 1900 * @param str the substring to search for. 1901 * @return the index of the first occurrence of the specified substring, 1902 * or {@code -1} if there is no such occurrence. 1903 */ 1904 public int indexOf(String str) { 1905 return indexOf(str, 0); 1906 } 1907 1908 /** 1909 * Returns the index within this string of the first occurrence of the 1910 * specified substring, starting at the specified index. 1911 * 1912 * <p>The returned index is the smallest value {@code k} for which: 1913 * <pre>{@code 1914 * k >= Math.min(fromIndex, this.length()) && 1915 * this.startsWith(str, k) 1916 * }</pre> 1917 * If no such value of {@code k} exists, then {@code -1} is returned. 1918 * 1919 * @param str the substring to search for. 1920 * @param fromIndex the index from which to start the search. 1921 * @return the index of the first occurrence of the specified substring, 1922 * starting at the specified index, 1923 * or {@code -1} if there is no such occurrence. 1924 */ 1925 public int indexOf(String str, int fromIndex) { 1926 return indexOf(value, 0, value.length, 1927 str.value, 0, str.value.length, fromIndex); 1928 } 1929 1930 /** 1931 * Code shared by String and AbstractStringBuilder to do searches. The 1932 * source is the character array being searched, and the target 1933 * is the string being searched for. 1934 * 1935 * @param source the characters being searched. 1936 * @param sourceOffset offset of the source string. 1937 * @param sourceCount count of the source string. 1938 * @param target the characters being searched for. 1939 * @param fromIndex the index to begin searching from. 1940 */ 1941 static int indexOf(char[] source, int sourceOffset, int sourceCount, 1942 String target, int fromIndex) { 1943 return indexOf(source, sourceOffset, sourceCount, 1944 target.value, 0, target.value.length, 1945 fromIndex); 1946 } 1947 1948 /** 1949 * Code shared by String and StringBuffer to do searches. The 1950 * source is the character array being searched, and the target 1951 * is the string being searched for. 1952 * 1953 * @param source the characters being searched. 1954 * @param sourceOffset offset of the source string. 1955 * @param sourceCount count of the source string. 1956 * @param target the characters being searched for. 1957 * @param targetOffset offset of the target string. 1958 * @param targetCount count of the target string. 1959 * @param fromIndex the index to begin searching from. 1960 */ 1961 static int indexOf(char[] source, int sourceOffset, int sourceCount, 1962 char[] target, int targetOffset, int targetCount, 1963 int fromIndex) { 1964 if (fromIndex >= sourceCount) { 1965 return (targetCount == 0 ? sourceCount : -1); 1966 } 1967 if (fromIndex < 0) { 1968 fromIndex = 0; 1969 } 1970 if (targetCount == 0) { 1971 return fromIndex; 1972 } 1973 1974 char first = target[targetOffset]; 1975 int max = sourceOffset + (sourceCount - targetCount); 1976 1977 for (int i = sourceOffset + fromIndex; i <= max; i++) { 1978 /* Look for first character. */ 1979 if (source[i] != first) { 1980 while (++i <= max && source[i] != first); 1981 } 1982 1983 /* Found first character, now look at the rest of v2 */ 1984 if (i <= max) { 1985 int j = i + 1; 1986 int end = j + targetCount - 1; 1987 for (int k = targetOffset + 1; j < end && source[j] 1988 == target[k]; j++, k++); 1989 1990 if (j == end) { 1991 /* Found whole string. */ 1992 return i - sourceOffset; 1993 } 1994 } 1995 } 1996 return -1; 1997 } 1998 1999 /** 2000 * Returns the index within this string of the last occurrence of the 2001 * specified substring. The last occurrence of the empty string "" 2002 * is considered to occur at the index value {@code this.length()}. 2003 * 2004 * <p>The returned index is the largest value {@code k} for which: 2005 * <pre>{@code 2006 * this.startsWith(str, k) 2007 * }</pre> 2008 * If no such value of {@code k} exists, then {@code -1} is returned. 2009 * 2010 * @param str the substring to search for. 2011 * @return the index of the last occurrence of the specified substring, 2012 * or {@code -1} if there is no such occurrence. 2013 */ 2014 public int lastIndexOf(String str) { 2015 return lastIndexOf(str, value.length); 2016 } 2017 2018 /** 2019 * Returns the index within this string of the last occurrence of the 2020 * specified substring, searching backward starting at the specified index. 2021 * 2022 * <p>The returned index is the largest value {@code k} for which: 2023 * <pre>{@code 2024 * k <= Math.min(fromIndex, this.length()) && 2025 * this.startsWith(str, k) 2026 * }</pre> 2027 * If no such value of {@code k} exists, then {@code -1} is returned. 2028 * 2029 * @param str the substring to search for. 2030 * @param fromIndex the index to start the search from. 2031 * @return the index of the last occurrence of the specified substring, 2032 * searching backward from the specified index, 2033 * or {@code -1} if there is no such occurrence. 2034 */ 2035 public int lastIndexOf(String str, int fromIndex) { 2036 return lastIndexOf(value, 0, value.length, 2037 str.value, 0, str.value.length, fromIndex); 2038 } 2039 2040 /** 2041 * Code shared by String and AbstractStringBuilder to do searches. The 2042 * source is the character array being searched, and the target 2043 * is the string being searched for. 2044 * 2045 * @param source the characters being searched. 2046 * @param sourceOffset offset of the source string. 2047 * @param sourceCount count of the source string. 2048 * @param target the characters being searched for. 2049 * @param fromIndex the index to begin searching from. 2050 */ 2051 static int lastIndexOf(char[] source, int sourceOffset, int sourceCount, 2052 String target, int fromIndex) { 2053 return lastIndexOf(source, sourceOffset, sourceCount, 2054 target.value, 0, target.value.length, 2055 fromIndex); 2056 } 2057 2058 /** 2059 * Code shared by String and StringBuffer to do searches. The 2060 * source is the character array being searched, and the target 2061 * is the string being searched for. 2062 * 2063 * @param source the characters being searched. 2064 * @param sourceOffset offset of the source string. 2065 * @param sourceCount count of the source string. 2066 * @param target the characters being searched for. 2067 * @param targetOffset offset of the target string. 2068 * @param targetCount count of the target string. 2069 * @param fromIndex the index to begin searching from. 2070 */ 2071 static int lastIndexOf(char[] source, int sourceOffset, int sourceCount, 2072 char[] target, int targetOffset, int targetCount, 2073 int fromIndex) { 2074 /* 2075 * Check arguments; return immediately where possible. For 2076 * consistency, don't check for null str. 2077 */ 2078 int rightIndex = sourceCount - targetCount; 2079 if (fromIndex < 0) { 2080 return -1; 2081 } 2082 if (fromIndex > rightIndex) { 2083 fromIndex = rightIndex; 2084 } 2085 /* Empty string always matches. */ 2086 if (targetCount == 0) { 2087 return fromIndex; 2088 } 2089 2090 int strLastIndex = targetOffset + targetCount - 1; 2091 char strLastChar = target[strLastIndex]; 2092 int min = sourceOffset + targetCount - 1; 2093 int i = min + fromIndex; 2094 2095 startSearchForLastChar: 2096 while (true) { 2097 while (i >= min && source[i] != strLastChar) { 2098 i--; 2099 } 2100 if (i < min) { 2101 return -1; 2102 } 2103 int j = i - 1; 2104 int start = j - (targetCount - 1); 2105 int k = strLastIndex - 1; 2106 2107 while (j > start) { 2108 if (source[j--] != target[k--]) { 2109 i--; 2110 continue startSearchForLastChar; 2111 } 2112 } 2113 return start - sourceOffset + 1; 2114 } 2115 } 2116 2117 /** 2118 * Returns a string that is a substring of this string. The 2119 * substring begins with the character at the specified index and 2120 * extends to the end of this string. <p> 2121 * Examples: 2122 * <blockquote><pre> 2123 * "unhappy".substring(2) returns "happy" 2124 * "Harbison".substring(3) returns "bison" 2125 * "emptiness".substring(9) returns "" (an empty string) 2126 * </pre></blockquote> 2127 * 2128 * @param beginIndex the beginning index, inclusive. 2129 * @return the specified substring. 2130 * @exception IndexOutOfBoundsException if 2131 * {@code beginIndex} is negative or larger than the 2132 * length of this {@code String} object. 2133 */ 2134 public String substring(int beginIndex) { 2135 if (beginIndex < 0) { 2136 throw new StringIndexOutOfBoundsException(beginIndex); 2137 } 2138 int subLen = value.length - beginIndex; 2139 if (subLen < 0) { 2140 throw new StringIndexOutOfBoundsException(subLen); 2141 } 2142 return (beginIndex == 0) ? this : new String(value, beginIndex, subLen); 2143 } 2144 2145 /** 2146 * Returns a string that is a substring of this string. The 2147 * substring begins at the specified {@code beginIndex} and 2148 * extends to the character at index {@code endIndex - 1}. 2149 * Thus the length of the substring is {@code endIndex-beginIndex}. 2150 * <p> 2151 * Examples: 2152 * <blockquote><pre> 2153 * "hamburger".substring(4, 8) returns "urge" 2154 * "smiles".substring(1, 5) returns "mile" 2155 * </pre></blockquote> 2156 * 2157 * @param beginIndex the beginning index, inclusive. 2158 * @param endIndex the ending index, exclusive. 2159 * @return the specified substring. 2160 * @exception IndexOutOfBoundsException if the 2161 * {@code beginIndex} is negative, or 2162 * {@code endIndex} is larger than the length of 2163 * this {@code String} object, or 2164 * {@code beginIndex} is larger than 2165 * {@code endIndex}. 2166 */ 2167 public String substring(int beginIndex, int endIndex) { 2168 if (beginIndex < 0) { 2169 throw new StringIndexOutOfBoundsException(beginIndex); 2170 } 2171 if (endIndex > value.length) { 2172 throw new StringIndexOutOfBoundsException(endIndex); 2173 } 2174 int subLen = endIndex - beginIndex; 2175 if (subLen < 0) { 2176 throw new StringIndexOutOfBoundsException(subLen); 2177 } 2178 return ((beginIndex == 0) && (endIndex == value.length)) ? this 2179 : new String(value, beginIndex, subLen); 2180 } 2181 2182 /** 2183 * Returns a character sequence that is a subsequence of this sequence. 2184 * 2185 * <p> An invocation of this method of the form 2186 * 2187 * <blockquote><pre> 2188 * str.subSequence(begin, end)</pre></blockquote> 2189 * 2190 * behaves in exactly the same way as the invocation 2191 * 2192 * <blockquote><pre> 2193 * str.substring(begin, end)</pre></blockquote> 2194 * 2195 * @apiNote 2196 * This method is defined so that the {@code String} class can implement 2197 * the {@link CharSequence} interface. 2198 * 2199 * @param beginIndex the begin index, inclusive. 2200 * @param endIndex the end index, exclusive. 2201 * @return the specified subsequence. 2202 * 2203 * @throws IndexOutOfBoundsException 2204 * if {@code beginIndex} or {@code endIndex} is negative, 2205 * if {@code endIndex} is greater than {@code length()}, 2206 * or if {@code beginIndex} is greater than {@code endIndex} 2207 * 2208 * @since 1.4 2209 * @spec JSR-51 2210 */ 2211 public CharSequence subSequence(int beginIndex, int endIndex) { 2212 return this.substring(beginIndex, endIndex); 2213 } 2214 2215 /** 2216 * Concatenates the specified string to the end of this string. 2217 * <p> 2218 * If the length of the argument string is {@code 0}, then this 2219 * {@code String} object is returned. Otherwise, a 2220 * {@code String} object is returned that represents a character 2221 * sequence that is the concatenation of the character sequence 2222 * represented by this {@code String} object and the character 2223 * sequence represented by the argument string.<p> 2224 * Examples: 2225 * <blockquote><pre> 2226 * "cares".concat("s") returns "caress" 2227 * "to".concat("get").concat("her") returns "together" 2228 * </pre></blockquote> 2229 * 2230 * @param str the {@code String} that is concatenated to the end 2231 * of this {@code String}. 2232 * @return a string that represents the concatenation of this object's 2233 * characters followed by the string argument's characters. 2234 */ 2235 public String concat(String str) { 2236 int otherLen = str.length(); 2237 if (otherLen == 0) { 2238 return this; 2239 } 2240 int len = value.length; 2241 char buf[] = Arrays.copyOf(value, len + otherLen); 2242 str.getChars(buf, len); 2243 return new String(buf, true); 2244 } 2245 2246 /** 2247 * Returns a string resulting from replacing all occurrences of 2248 * {@code oldChar} in this string with {@code newChar}. 2249 * <p> 2250 * If the character {@code oldChar} does not occur in the 2251 * character sequence represented by this {@code String} object, 2252 * then a reference to this {@code String} object is returned. 2253 * Otherwise, a {@code String} object is returned that 2254 * represents a character sequence identical to the character sequence 2255 * represented by this {@code String} object, except that every 2256 * occurrence of {@code oldChar} is replaced by an occurrence 2257 * of {@code newChar}. 2258 * <p> 2259 * Examples: 2260 * <blockquote><pre> 2261 * "mesquite in your cellar".replace('e', 'o') 2262 * returns "mosquito in your collar" 2263 * "the war of baronets".replace('r', 'y') 2264 * returns "the way of bayonets" 2265 * "sparring with a purple porpoise".replace('p', 't') 2266 * returns "starring with a turtle tortoise" 2267 * "JonL".replace('q', 'x') returns "JonL" (no change) 2268 * </pre></blockquote> 2269 * 2270 * @param oldChar the old character. 2271 * @param newChar the new character. 2272 * @return a string derived from this string by replacing every 2273 * occurrence of {@code oldChar} with {@code newChar}. 2274 */ 2275 public String replace(char oldChar, char newChar) { 2276 if (oldChar != newChar) { 2277 int len = value.length; 2278 int i = -1; 2279 char[] val = value; /* avoid getfield opcode */ 2280 2281 while (++i < len) { 2282 if (val[i] == oldChar) { 2283 break; 2284 } 2285 } 2286 if (i < len) { 2287 char buf[] = new char[len]; 2288 for (int j = 0; j < i; j++) { 2289 buf[j] = val[j]; 2290 } 2291 while (i < len) { 2292 char c = val[i]; 2293 buf[i] = (c == oldChar) ? newChar : c; 2294 i++; 2295 } 2296 return new String(buf, true); 2297 } 2298 } 2299 return this; 2300 } 2301 2302 /** 2303 * Tells whether or not this string matches the given <a 2304 * href="../util/regex/Pattern.html#sum">regular expression</a>. 2305 * 2306 * <p> An invocation of this method of the form 2307 * <i>str</i>{@code .matches(}<i>regex</i>{@code )} yields exactly the 2308 * same result as the expression 2309 * 2310 * <blockquote> 2311 * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#matches(String,CharSequence) 2312 * matches(<i>regex</i>, <i>str</i>)} 2313 * </blockquote> 2314 * 2315 * @param regex 2316 * the regular expression to which this string is to be matched 2317 * 2318 * @return {@code true} if, and only if, this string matches the 2319 * given regular expression 2320 * 2321 * @throws PatternSyntaxException 2322 * if the regular expression's syntax is invalid 2323 * 2324 * @see java.util.regex.Pattern 2325 * 2326 * @since 1.4 2327 * @spec JSR-51 2328 */ 2329 public boolean matches(String regex) { 2330 return Pattern.matches(regex, this); 2331 } 2332 2333 /** 2334 * Returns true if and only if this string contains the specified 2335 * sequence of char values. 2336 * 2337 * @param s the sequence to search for 2338 * @return true if this string contains {@code s}, false otherwise 2339 * @since 1.5 2340 */ 2341 public boolean contains(CharSequence s) { 2342 return indexOf(s.toString()) >= 0; 2343 } 2344 2345 /** 2346 * Replaces the first substring of this string that matches the given <a 2347 * href="../util/regex/Pattern.html#sum">regular expression</a> with the 2348 * given replacement. 2349 * 2350 * <p> An invocation of this method of the form 2351 * <i>str</i>{@code .replaceFirst(}<i>regex</i>{@code ,} <i>repl</i>{@code )} 2352 * yields exactly the same result as the expression 2353 * 2354 * <blockquote> 2355 * <code> 2356 * {@link java.util.regex.Pattern}.{@link 2357 * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link 2358 * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link 2359 * java.util.regex.Matcher#replaceFirst replaceFirst}(<i>repl</i>) 2360 * </code> 2361 * </blockquote> 2362 * 2363 *<p> 2364 * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the 2365 * replacement string may cause the results to be different than if it were 2366 * being treated as a literal replacement string; see 2367 * {@link java.util.regex.Matcher#replaceFirst}. 2368 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special 2369 * meaning of these characters, if desired. 2370 * 2371 * @param regex 2372 * the regular expression to which this string is to be matched 2373 * @param replacement 2374 * the string to be substituted for the first match 2375 * 2376 * @return The resulting {@code String} 2377 * 2378 * @throws PatternSyntaxException 2379 * if the regular expression's syntax is invalid 2380 * 2381 * @see java.util.regex.Pattern 2382 * 2383 * @since 1.4 2384 * @spec JSR-51 2385 */ 2386 public String replaceFirst(String regex, String replacement) { 2387 return Pattern.compile(regex).matcher(this).replaceFirst(replacement); 2388 } 2389 2390 /** 2391 * Replaces each substring of this string that matches the given <a 2392 * href="../util/regex/Pattern.html#sum">regular expression</a> with the 2393 * given replacement. 2394 * 2395 * <p> An invocation of this method of the form 2396 * <i>str</i>{@code .replaceAll(}<i>regex</i>{@code ,} <i>repl</i>{@code )} 2397 * yields exactly the same result as the expression 2398 * 2399 * <blockquote> 2400 * <code> 2401 * {@link java.util.regex.Pattern}.{@link 2402 * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link 2403 * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link 2404 * java.util.regex.Matcher#replaceAll replaceAll}(<i>repl</i>) 2405 * </code> 2406 * </blockquote> 2407 * 2408 *<p> 2409 * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the 2410 * replacement string may cause the results to be different than if it were 2411 * being treated as a literal replacement string; see 2412 * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}. 2413 * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special 2414 * meaning of these characters, if desired. 2415 * 2416 * @param regex 2417 * the regular expression to which this string is to be matched 2418 * @param replacement 2419 * the string to be substituted for each match 2420 * 2421 * @return The resulting {@code String} 2422 * 2423 * @throws PatternSyntaxException 2424 * if the regular expression's syntax is invalid 2425 * 2426 * @see java.util.regex.Pattern 2427 * 2428 * @since 1.4 2429 * @spec JSR-51 2430 */ 2431 public String replaceAll(String regex, String replacement) { 2432 return Pattern.compile(regex).matcher(this).replaceAll(replacement); 2433 } 2434 2435 /** 2436 * Replaces each substring of this string that matches the literal target 2437 * sequence with the specified literal replacement sequence. The 2438 * replacement proceeds from the beginning of the string to the end, for 2439 * example, replacing "aa" with "b" in the string "aaa" will result in 2440 * "ba" rather than "ab". 2441 * 2442 * @param target The sequence of char values to be replaced 2443 * @param replacement The replacement sequence of char values 2444 * @return The resulting string 2445 * @since 1.5 2446 */ 2447 public String replace(CharSequence target, CharSequence replacement) { 2448 return Pattern.compile(target.toString(), Pattern.LITERAL).matcher( 2449 this).replaceAll(Matcher.quoteReplacement(replacement.toString())); 2450 } 2451 2452 /** 2453 * Splits this string around matches of the given 2454 * <a href="../util/regex/Pattern.html#sum">regular expression</a>. 2455 * 2456 * <p> The array returned by this method contains each substring of this 2457 * string that is terminated by another substring that matches the given 2458 * expression or is terminated by the end of the string. The substrings in 2459 * the array are in the order in which they occur in this string. If the 2460 * expression does not match any part of the input then the resulting array 2461 * has just one element, namely this string. 2462 * 2463 * <p> When there is a positive-width match at the beginning of this 2464 * string then an empty leading substring is included at the beginning 2465 * of the resulting array. A zero-width match at the beginning however 2466 * never produces such empty leading substring. 2467 * 2468 * <p> The {@code limit} parameter controls the number of times the 2469 * pattern is applied and therefore affects the length of the resulting 2470 * array. If the limit <i>n</i> is greater than zero then the pattern 2471 * will be applied at most <i>n</i> - 1 times, the array's 2472 * length will be no greater than <i>n</i>, and the array's last entry 2473 * will contain all input beyond the last matched delimiter. If <i>n</i> 2474 * is non-positive then the pattern will be applied as many times as 2475 * possible and the array can have any length. If <i>n</i> is zero then 2476 * the pattern will be applied as many times as possible, the array can 2477 * have any length, and trailing empty strings will be discarded. 2478 * 2479 * <p> The string {@code "boo:and:foo"}, for example, yields the 2480 * following results with these parameters: 2481 * 2482 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result"> 2483 * <tr> 2484 * <th>Regex</th> 2485 * <th>Limit</th> 2486 * <th>Result</th> 2487 * </tr> 2488 * <tr><td align=center>:</td> 2489 * <td align=center>2</td> 2490 * <td>{@code { "boo", "and:foo" }}</td></tr> 2491 * <tr><td align=center>:</td> 2492 * <td align=center>5</td> 2493 * <td>{@code { "boo", "and", "foo" }}</td></tr> 2494 * <tr><td align=center>:</td> 2495 * <td align=center>-2</td> 2496 * <td>{@code { "boo", "and", "foo" }}</td></tr> 2497 * <tr><td align=center>o</td> 2498 * <td align=center>5</td> 2499 * <td>{@code { "b", "", ":and:f", "", "" }}</td></tr> 2500 * <tr><td align=center>o</td> 2501 * <td align=center>-2</td> 2502 * <td>{@code { "b", "", ":and:f", "", "" }}</td></tr> 2503 * <tr><td align=center>o</td> 2504 * <td align=center>0</td> 2505 * <td>{@code { "b", "", ":and:f" }}</td></tr> 2506 * </table></blockquote> 2507 * 2508 * <p> An invocation of this method of the form 2509 * <i>str.</i>{@code split(}<i>regex</i>{@code ,} <i>n</i>{@code )} 2510 * yields the same result as the expression 2511 * 2512 * <blockquote> 2513 * <code> 2514 * {@link java.util.regex.Pattern}.{@link 2515 * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link 2516 * java.util.regex.Pattern#split(java.lang.CharSequence,int) split}(<i>str</i>, <i>n</i>) 2517 * </code> 2518 * </blockquote> 2519 * 2520 * 2521 * @param regex 2522 * the delimiting regular expression 2523 * 2524 * @param limit 2525 * the result threshold, as described above 2526 * 2527 * @return the array of strings computed by splitting this string 2528 * around matches of the given regular expression 2529 * 2530 * @throws PatternSyntaxException 2531 * if the regular expression's syntax is invalid 2532 * 2533 * @see java.util.regex.Pattern 2534 * 2535 * @since 1.4 2536 * @spec JSR-51 2537 */ 2538 public String[] split(String regex, int limit) { 2539 /* fastpath if the regex is a 2540 (1)one-char String and this character is not one of the 2541 RegEx's meta characters ".$|()[{^?*+\\", or 2542 (2)two-char String and the first char is the backslash and 2543 the second is not the ascii digit or ascii letter. 2544 */ 2545 char ch = 0; 2546 if (((regex.value.length == 1 && 2547 ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) || 2548 (regex.length() == 2 && 2549 regex.charAt(0) == '\\' && 2550 (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 && 2551 ((ch-'a')|('z'-ch)) < 0 && 2552 ((ch-'A')|('Z'-ch)) < 0)) && 2553 (ch < Character.MIN_HIGH_SURROGATE || 2554 ch > Character.MAX_LOW_SURROGATE)) 2555 { 2556 int off = 0; 2557 int next = 0; 2558 boolean limited = limit > 0; 2559 ArrayList<String> list = new ArrayList<>(); 2560 while ((next = indexOf(ch, off)) != -1) { 2561 if (!limited || list.size() < limit - 1) { 2562 list.add(substring(off, next)); 2563 off = next + 1; 2564 } else { // last one 2565 //assert (list.size() == limit - 1); 2566 list.add(substring(off, value.length)); 2567 off = value.length; 2568 break; 2569 } 2570 } 2571 // If no match was found, return this 2572 if (off == 0) 2573 return new String[]{this}; 2574 2575 // Add remaining segment 2576 if (!limited || list.size() < limit) 2577 list.add(substring(off, value.length)); 2578 2579 // Construct result 2580 int resultSize = list.size(); 2581 if (limit == 0) { 2582 while (resultSize > 0 && list.get(resultSize - 1).length() == 0) { 2583 resultSize--; 2584 } 2585 } 2586 String[] result = new String[resultSize]; 2587 return list.subList(0, resultSize).toArray(result); 2588 } 2589 return Pattern.compile(regex).split(this, limit); 2590 } 2591 2592 /** 2593 * Splits this string around matches of the given <a 2594 * href="../util/regex/Pattern.html#sum">regular expression</a>. 2595 * 2596 * <p> This method works as if by invoking the two-argument {@link 2597 * #split(String, int) split} method with the given expression and a limit 2598 * argument of zero. Trailing empty strings are therefore not included in 2599 * the resulting array. 2600 * 2601 * <p> The string {@code "boo:and:foo"}, for example, yields the following 2602 * results with these expressions: 2603 * 2604 * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result"> 2605 * <tr> 2606 * <th>Regex</th> 2607 * <th>Result</th> 2608 * </tr> 2609 * <tr><td align=center>:</td> 2610 * <td>{@code { "boo", "and", "foo" }}</td></tr> 2611 * <tr><td align=center>o</td> 2612 * <td>{@code { "b", "", ":and:f" }}</td></tr> 2613 * </table></blockquote> 2614 * 2615 * 2616 * @param regex 2617 * the delimiting regular expression 2618 * 2619 * @return the array of strings computed by splitting this string 2620 * around matches of the given regular expression 2621 * 2622 * @throws PatternSyntaxException 2623 * if the regular expression's syntax is invalid 2624 * 2625 * @see java.util.regex.Pattern 2626 * 2627 * @since 1.4 2628 * @spec JSR-51 2629 */ 2630 public String[] split(String regex) { 2631 return split(regex, 0); 2632 } 2633 2634 /** 2635 * Returns a new String composed of copies of the 2636 * {@code CharSequence elements} joined together with a copy of 2637 * the specified {@code delimiter}. 2638 * 2639 * <blockquote>For example, 2640 * <pre>{@code 2641 * String message = String.join("-", "Java", "is", "cool"); 2642 * // message returned is: "Java-is-cool" 2643 * }</pre></blockquote> 2644 * 2645 * Note that if an element is null, then {@code "null"} is added. 2646 * 2647 * @param delimiter the delimiter that separates each element 2648 * @param elements the elements to join together. 2649 * 2650 * @return a new {@code String} that is composed of the {@code elements} 2651 * separated by the {@code delimiter} 2652 * 2653 * @throws NullPointerException If {@code delimiter} or {@code elements} 2654 * is {@code null} 2655 * 2656 * @see java.util.StringJoiner 2657 * @since 1.8 2658 */ 2659 public static String join(CharSequence delimiter, CharSequence... elements) { 2660 Objects.requireNonNull(delimiter); 2661 Objects.requireNonNull(elements); 2662 // Number of elements not likely worth Arrays.stream overhead. 2663 StringJoiner joiner = new StringJoiner(delimiter); 2664 for (CharSequence cs: elements) { 2665 joiner.add(cs); 2666 } 2667 return joiner.toString(); 2668 } 2669 2670 /** 2671 * Returns a new {@code String} composed of copies of the 2672 * {@code CharSequence elements} joined together with a copy of the 2673 * specified {@code delimiter}. 2674 * 2675 * <blockquote>For example, 2676 * <pre>{@code 2677 * List<String> strings = new LinkedList<>(); 2678 * strings.add("Java");strings.add("is"); 2679 * strings.add("cool"); 2680 * String message = String.join(" ", strings); 2681 * //message returned is: "Java is cool" 2682 * 2683 * Set<String> strings = new LinkedHashSet<>(); 2684 * strings.add("Java"); strings.add("is"); 2685 * strings.add("very"); strings.add("cool"); 2686 * String message = String.join("-", strings); 2687 * //message returned is: "Java-is-very-cool" 2688 * }</pre></blockquote> 2689 * 2690 * Note that if an individual element is {@code null}, then {@code "null"} is added. 2691 * 2692 * @param delimiter a sequence of characters that is used to separate each 2693 * of the {@code elements} in the resulting {@code String} 2694 * @param elements an {@code Iterable} that will have its {@code elements} 2695 * joined together. 2696 * 2697 * @return a new {@code String} that is composed from the {@code elements} 2698 * argument 2699 * 2700 * @throws NullPointerException If {@code delimiter} or {@code elements} 2701 * is {@code null} 2702 * 2703 * @see #join(CharSequence,CharSequence...) 2704 * @see java.util.StringJoiner 2705 * @since 1.8 2706 */ 2707 public static String join(CharSequence delimiter, 2708 Iterable<? extends CharSequence> elements) { 2709 Objects.requireNonNull(delimiter); 2710 Objects.requireNonNull(elements); 2711 StringJoiner joiner = new StringJoiner(delimiter); 2712 for (CharSequence cs: elements) { 2713 joiner.add(cs); 2714 } 2715 return joiner.toString(); 2716 } 2717 2718 /** 2719 * Converts all of the characters in this {@code String} to lower 2720 * case using the rules of the given {@code Locale}. Case mapping is based 2721 * on the Unicode Standard version specified by the {@link java.lang.Character Character} 2722 * class. Since case mappings are not always 1:1 char mappings, the resulting 2723 * {@code String} may be a different length than the original {@code String}. 2724 * <p> 2725 * Examples of lowercase mappings are in the following table: 2726 * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description"> 2727 * <tr> 2728 * <th>Language Code of Locale</th> 2729 * <th>Upper Case</th> 2730 * <th>Lower Case</th> 2731 * <th>Description</th> 2732 * </tr> 2733 * <tr> 2734 * <td>tr (Turkish)</td> 2735 * <td>\u0130</td> 2736 * <td>\u0069</td> 2737 * <td>capital letter I with dot above -> small letter i</td> 2738 * </tr> 2739 * <tr> 2740 * <td>tr (Turkish)</td> 2741 * <td>\u0049</td> 2742 * <td>\u0131</td> 2743 * <td>capital letter I -> small letter dotless i </td> 2744 * </tr> 2745 * <tr> 2746 * <td>(all)</td> 2747 * <td>French Fries</td> 2748 * <td>french fries</td> 2749 * <td>lowercased all chars in String</td> 2750 * </tr> 2751 * <tr> 2752 * <td>(all)</td> 2753 * <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi"> 2754 * <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil"> 2755 * <img src="doc-files/capsigma.gif" alt="capsigma"></td> 2756 * <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi"> 2757 * <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon"> 2758 * <img src="doc-files/sigma1.gif" alt="sigma"></td> 2759 * <td>lowercased all chars in String</td> 2760 * </tr> 2761 * </table> 2762 * 2763 * @param locale use the case transformation rules for this locale 2764 * @return the {@code String}, converted to lowercase. 2765 * @see java.lang.String#toLowerCase() 2766 * @see java.lang.String#toUpperCase() 2767 * @see java.lang.String#toUpperCase(Locale) 2768 * @since 1.1 2769 */ 2770 public String toLowerCase(Locale locale) { 2771 if (locale == null) { 2772 throw new NullPointerException(); 2773 } 2774 int first; 2775 boolean hasSurr = false; 2776 final int len = value.length; 2777 2778 // Now check if there are any characters that need to be changed, or are surrogate 2779 for (first = 0 ; first < len; first++) { 2780 int cp = (int)value[first]; 2781 if (Character.isSurrogate((char)cp)) { 2782 hasSurr = true; 2783 break; 2784 } 2785 if (cp != Character.toLowerCase(cp)) { // no need to check Character.ERROR 2786 break; 2787 } 2788 } 2789 if (first == len) 2790 return this; 2791 char[] result = new char[len]; 2792 System.arraycopy(value, 0, result, 0, first); // Just copy the first few 2793 // lowerCase characters. 2794 String lang = locale.getLanguage(); 2795 if (lang == "tr" || lang == "az" || lang == "lt") { 2796 return toLowerCaseEx(result, first, locale, true); 2797 } 2798 if (hasSurr) { 2799 return toLowerCaseEx(result, first, locale, false); 2800 } 2801 for (int i = first; i < len; i++) { 2802 int cp = (int)value[i]; 2803 if (cp == '\u03A3' || // GREEK CAPITAL LETTER SIGMA 2804 Character.isSurrogate((char)cp)) { 2805 return toLowerCaseEx(result, i, locale, false); 2806 } 2807 if (cp == '\u0130') { // LATIN CAPITAL LETTER I WITH DOT ABOVE 2808 return toLowerCaseEx(result, i, locale, true); 2809 } 2810 cp = Character.toLowerCase(cp); 2811 if (!Character.isBmpCodePoint(cp)) { 2812 return toLowerCaseEx(result, i, locale, false); 2813 } 2814 result[i] = (char)cp; 2815 } 2816 return new String(result, true); 2817 } 2818 2819 private String toLowerCaseEx(char[] result, int first, Locale locale, boolean localeDependent) { 2820 int resultOffset = first; 2821 int srcCount; 2822 for (int i = first; i < value.length; i += srcCount) { 2823 int srcChar = (int)value[i]; 2824 int lowerChar; 2825 char[] lowerCharArray; 2826 srcCount = 1; 2827 if (Character.isSurrogate((char)srcChar)) { 2828 srcChar = codePointAt(i); 2829 srcCount = Character.charCount(srcChar); 2830 } 2831 if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA 2832 lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale); 2833 } else { 2834 lowerChar = Character.toLowerCase(srcChar); 2835 } 2836 if (Character.isBmpCodePoint(lowerChar)) { // Character.ERROR is not a bmp 2837 result[resultOffset++] = (char)lowerChar; 2838 } else { 2839 if (lowerChar == Character.ERROR) { 2840 lowerCharArray = ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale); 2841 } else if (srcCount == 2) { 2842 resultOffset += Character.toChars(lowerChar, result, resultOffset); 2843 continue; 2844 } else { 2845 lowerCharArray = Character.toChars(lowerChar); 2846 } 2847 /* Grow result if needed */ 2848 int mapLen = lowerCharArray.length; 2849 if (mapLen > srcCount) { 2850 char[] result2 = new char[result.length + mapLen - srcCount]; 2851 System.arraycopy(result, 0, result2, 0, resultOffset); 2852 result = result2; 2853 } 2854 for (int x = 0; x < mapLen; ++x) { 2855 result[resultOffset++] = lowerCharArray[x]; 2856 } 2857 } 2858 } 2859 return new String(result, 0, resultOffset); 2860 } 2861 2862 /** 2863 * Converts all of the characters in this {@code String} to lower 2864 * case using the rules of the default locale. This is equivalent to calling 2865 * {@code toLowerCase(Locale.getDefault())}. 2866 * <p> 2867 * <b>Note:</b> This method is locale sensitive, and may produce unexpected 2868 * results if used for strings that are intended to be interpreted locale 2869 * independently. 2870 * Examples are programming language identifiers, protocol keys, and HTML 2871 * tags. 2872 * For instance, {@code "TITLE".toLowerCase()} in a Turkish locale 2873 * returns {@code "t\u005Cu0131tle"}, where '\u005Cu0131' is the 2874 * LATIN SMALL LETTER DOTLESS I character. 2875 * To obtain correct results for locale insensitive strings, use 2876 * {@code toLowerCase(Locale.ROOT)}. 2877 * 2878 * @return the {@code String}, converted to lowercase. 2879 * @see java.lang.String#toLowerCase(Locale) 2880 */ 2881 public String toLowerCase() { 2882 return toLowerCase(Locale.getDefault()); 2883 } 2884 2885 /** 2886 * Converts all of the characters in this {@code String} to upper 2887 * case using the rules of the given {@code Locale}. Case mapping is based 2888 * on the Unicode Standard version specified by the {@link java.lang.Character Character} 2889 * class. Since case mappings are not always 1:1 char mappings, the resulting 2890 * {@code String} may be a different length than the original {@code String}. 2891 * <p> 2892 * Examples of locale-sensitive and 1:M case mappings are in the following table. 2893 * 2894 * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description."> 2895 * <tr> 2896 * <th>Language Code of Locale</th> 2897 * <th>Lower Case</th> 2898 * <th>Upper Case</th> 2899 * <th>Description</th> 2900 * </tr> 2901 * <tr> 2902 * <td>tr (Turkish)</td> 2903 * <td>\u0069</td> 2904 * <td>\u0130</td> 2905 * <td>small letter i -> capital letter I with dot above</td> 2906 * </tr> 2907 * <tr> 2908 * <td>tr (Turkish)</td> 2909 * <td>\u0131</td> 2910 * <td>\u0049</td> 2911 * <td>small letter dotless i -> capital letter I</td> 2912 * </tr> 2913 * <tr> 2914 * <td>(all)</td> 2915 * <td>\u00df</td> 2916 * <td>\u0053 \u0053</td> 2917 * <td>small letter sharp s -> two letters: SS</td> 2918 * </tr> 2919 * <tr> 2920 * <td>(all)</td> 2921 * <td>Fahrvergnügen</td> 2922 * <td>FAHRVERGNÜGEN</td> 2923 * <td></td> 2924 * </tr> 2925 * </table> 2926 * @param locale use the case transformation rules for this locale 2927 * @return the {@code String}, converted to uppercase. 2928 * @see java.lang.String#toUpperCase() 2929 * @see java.lang.String#toLowerCase() 2930 * @see java.lang.String#toLowerCase(Locale) 2931 * @since 1.1 2932 */ 2933 public String toUpperCase(Locale locale) { 2934 if (locale == null) { 2935 throw new NullPointerException(); 2936 } 2937 int first; 2938 boolean hasSurr = false; 2939 final int len = value.length; 2940 2941 // Now check if there are any characters that need to be changed, or are surrogate 2942 for (first = 0 ; first < len; first++ ) { 2943 int cp = (int)value[first]; 2944 if (Character.isSurrogate((char)cp)) { 2945 hasSurr = true; 2946 break; 2947 } 2948 if (cp != Character.toUpperCaseEx(cp)) { // no need to check Character.ERROR 2949 break; 2950 } 2951 } 2952 if (first == len) { 2953 return this; 2954 } 2955 char[] result = new char[len]; 2956 System.arraycopy(value, 0, result, 0, first); // Just copy the first few 2957 // upperCase characters. 2958 String lang = locale.getLanguage(); 2959 if (lang == "tr" || lang == "az" || lang == "lt") { 2960 return toUpperCaseEx(result, first, locale, true); 2961 } 2962 if (hasSurr) { 2963 return toUpperCaseEx(result, first, locale, false); 2964 } 2965 for (int i = first; i < len; i++) { 2966 int cp = (int)value[i]; 2967 if (Character.isSurrogate((char)cp)) { 2968 return toUpperCaseEx(result, i, locale, false); 2969 } 2970 cp = Character.toUpperCaseEx(cp); 2971 if (!Character.isBmpCodePoint(cp)) { // Character.ERROR is not bmp 2972 return toUpperCaseEx(result, i, locale, false); 2973 } 2974 result[i] = (char)cp; 2975 } 2976 return new String(result, true); 2977 } 2978 2979 private String toUpperCaseEx(char[] result, int first, Locale locale, 2980 boolean localeDependent) { 2981 int resultOffset = first; 2982 int srcCount; 2983 for (int i = first; i < value.length; i += srcCount) { 2984 int srcChar = (int)value[i]; 2985 int upperChar; 2986 char[] upperCharArray; 2987 srcCount = 1; 2988 if (Character.isSurrogate((char)srcChar)) { 2989 srcChar = codePointAt(i); 2990 srcCount = Character.charCount(srcChar); 2991 } 2992 if (localeDependent) { 2993 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale); 2994 } else { 2995 upperChar = Character.toUpperCaseEx(srcChar); 2996 } 2997 if (Character.isBmpCodePoint(upperChar)) { 2998 result[resultOffset++] = (char)upperChar; 2999 } else { 3000 if (upperChar == Character.ERROR) { 3001 if (localeDependent) { 3002 upperCharArray = 3003 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale); 3004 } else { 3005 upperCharArray = Character.toUpperCaseCharArray(srcChar); 3006 } 3007 } else if (srcCount == 2) { 3008 resultOffset += Character.toChars(upperChar, result, resultOffset); 3009 continue; 3010 } else { 3011 upperCharArray = Character.toChars(upperChar); 3012 } 3013 /* Grow result if needed */ 3014 int mapLen = upperCharArray.length; 3015 if (mapLen > srcCount) { 3016 char[] result2 = new char[result.length + mapLen - srcCount]; 3017 System.arraycopy(result, 0, result2, 0, resultOffset); 3018 result = result2; 3019 } 3020 for (int x = 0; x < mapLen; ++x) { 3021 result[resultOffset++] = upperCharArray[x]; 3022 } 3023 } 3024 } 3025 return new String(result, 0, resultOffset); 3026 } 3027 3028 /** 3029 * Converts all of the characters in this {@code String} to upper 3030 * case using the rules of the default locale. This method is equivalent to 3031 * {@code toUpperCase(Locale.getDefault())}. 3032 * <p> 3033 * <b>Note:</b> This method is locale sensitive, and may produce unexpected 3034 * results if used for strings that are intended to be interpreted locale 3035 * independently. 3036 * Examples are programming language identifiers, protocol keys, and HTML 3037 * tags. 3038 * For instance, {@code "title".toUpperCase()} in a Turkish locale 3039 * returns {@code "T\u005Cu0130TLE"}, where '\u005Cu0130' is the 3040 * LATIN CAPITAL LETTER I WITH DOT ABOVE character. 3041 * To obtain correct results for locale insensitive strings, use 3042 * {@code toUpperCase(Locale.ROOT)}. 3043 * 3044 * @return the {@code String}, converted to uppercase. 3045 * @see java.lang.String#toUpperCase(Locale) 3046 */ 3047 public String toUpperCase() { 3048 return toUpperCase(Locale.getDefault()); 3049 } 3050 3051 /** 3052 * Returns a string whose value is this string, with any leading and trailing 3053 * whitespace removed. 3054 * <p> 3055 * If this {@code String} object represents an empty character 3056 * sequence, or the first and last characters of character sequence 3057 * represented by this {@code String} object both have codes 3058 * greater than {@code '\u005Cu0020'} (the space character), then a 3059 * reference to this {@code String} object is returned. 3060 * <p> 3061 * Otherwise, if there is no character with a code greater than 3062 * {@code '\u005Cu0020'} in the string, then a 3063 * {@code String} object representing an empty string is 3064 * returned. 3065 * <p> 3066 * Otherwise, let <i>k</i> be the index of the first character in the 3067 * string whose code is greater than {@code '\u005Cu0020'}, and let 3068 * <i>m</i> be the index of the last character in the string whose code 3069 * is greater than {@code '\u005Cu0020'}. A {@code String} 3070 * object is returned, representing the substring of this string that 3071 * begins with the character at index <i>k</i> and ends with the 3072 * character at index <i>m</i>-that is, the result of 3073 * {@code this.substring(k, m + 1)}. 3074 * <p> 3075 * This method may be used to trim whitespace (as defined above) from 3076 * the beginning and end of a string. 3077 * 3078 * @return A string whose value is this string, with any leading and trailing white 3079 * space removed, or this string if it has no leading or 3080 * trailing white space. 3081 */ 3082 public String trim() { 3083 int len = value.length; 3084 int st = 0; 3085 char[] val = value; /* avoid getfield opcode */ 3086 3087 while ((st < len) && (val[st] <= ' ')) { 3088 st++; 3089 } 3090 while ((st < len) && (val[len - 1] <= ' ')) { 3091 len--; 3092 } 3093 return ((st > 0) || (len < value.length)) ? substring(st, len) : this; 3094 } 3095 3096 /** 3097 * This object (which is already a string!) is itself returned. 3098 * 3099 * @return the string itself. 3100 */ 3101 public String toString() { 3102 return this; 3103 } 3104 3105 /** 3106 * Converts this string to a new character array. 3107 * 3108 * @return a newly allocated character array whose length is the length 3109 * of this string and whose contents are initialized to contain 3110 * the character sequence represented by this string. 3111 */ 3112 public char[] toCharArray() { 3113 // Cannot use Arrays.copyOf because of class initialization order issues 3114 char result[] = new char[value.length]; 3115 System.arraycopy(value, 0, result, 0, value.length); 3116 return result; 3117 } 3118 3119 /** 3120 * Returns a formatted string using the specified format string and 3121 * arguments. 3122 * 3123 * <p> The locale always used is the one returned by {@link 3124 * java.util.Locale#getDefault() Locale.getDefault()}. 3125 * 3126 * @param format 3127 * A <a href="../util/Formatter.html#syntax">format string</a> 3128 * 3129 * @param args 3130 * Arguments referenced by the format specifiers in the format 3131 * string. If there are more arguments than format specifiers, the 3132 * extra arguments are ignored. The number of arguments is 3133 * variable and may be zero. The maximum number of arguments is 3134 * limited by the maximum dimension of a Java array as defined by 3135 * <cite>The Java™ Virtual Machine Specification</cite>. 3136 * The behaviour on a 3137 * {@code null} argument depends on the <a 3138 * href="../util/Formatter.html#syntax">conversion</a>. 3139 * 3140 * @throws java.util.IllegalFormatException 3141 * If a format string contains an illegal syntax, a format 3142 * specifier that is incompatible with the given arguments, 3143 * insufficient arguments given the format string, or other 3144 * illegal conditions. For specification of all possible 3145 * formatting errors, see the <a 3146 * href="../util/Formatter.html#detail">Details</a> section of the 3147 * formatter class specification. 3148 * 3149 * @return A formatted string 3150 * 3151 * @see java.util.Formatter 3152 * @since 1.5 3153 */ 3154 public static String format(String format, Object... args) { 3155 return new Formatter().format(format, args).toString(); 3156 } 3157 3158 /** 3159 * Returns a formatted string using the specified locale, format string, 3160 * and arguments. 3161 * 3162 * @param l 3163 * The {@linkplain java.util.Locale locale} to apply during 3164 * formatting. If {@code l} is {@code null} then no localization 3165 * is applied. 3166 * 3167 * @param format 3168 * A <a href="../util/Formatter.html#syntax">format string</a> 3169 * 3170 * @param args 3171 * Arguments referenced by the format specifiers in the format 3172 * string. If there are more arguments than format specifiers, the 3173 * extra arguments are ignored. The number of arguments is 3174 * variable and may be zero. The maximum number of arguments is 3175 * limited by the maximum dimension of a Java array as defined by 3176 * <cite>The Java™ Virtual Machine Specification</cite>. 3177 * The behaviour on a 3178 * {@code null} argument depends on the 3179 * <a href="../util/Formatter.html#syntax">conversion</a>. 3180 * 3181 * @throws java.util.IllegalFormatException 3182 * If a format string contains an illegal syntax, a format 3183 * specifier that is incompatible with the given arguments, 3184 * insufficient arguments given the format string, or other 3185 * illegal conditions. For specification of all possible 3186 * formatting errors, see the <a 3187 * href="../util/Formatter.html#detail">Details</a> section of the 3188 * formatter class specification 3189 * 3190 * @return A formatted string 3191 * 3192 * @see java.util.Formatter 3193 * @since 1.5 3194 */ 3195 public static String format(Locale l, String format, Object... args) { 3196 return new Formatter(l).format(format, args).toString(); 3197 } 3198 3199 /** 3200 * Returns the string representation of the {@code Object} argument. 3201 * 3202 * @param obj an {@code Object}. 3203 * @return if the argument is {@code null}, then a string equal to 3204 * {@code "null"}; otherwise, the value of 3205 * {@code obj.toString()} is returned. 3206 * @see java.lang.Object#toString() 3207 */ 3208 public static String valueOf(Object obj) { 3209 return (obj == null) ? "null" : obj.toString(); 3210 } 3211 3212 /** 3213 * Returns the string representation of the {@code char} array 3214 * argument. The contents of the character array are copied; subsequent 3215 * modification of the character array does not affect the returned 3216 * string. 3217 * 3218 * @param data the character array. 3219 * @return a {@code String} that contains the characters of the 3220 * character array. 3221 */ 3222 public static String valueOf(char data[]) { 3223 return new String(data); 3224 } 3225 3226 /** 3227 * Returns the string representation of a specific subarray of the 3228 * {@code char} array argument. 3229 * <p> 3230 * The {@code offset} argument is the index of the first 3231 * character of the subarray. The {@code count} argument 3232 * specifies the length of the subarray. The contents of the subarray 3233 * are copied; subsequent modification of the character array does not 3234 * affect the returned string. 3235 * 3236 * @param data the character array. 3237 * @param offset initial offset of the subarray. 3238 * @param count length of the subarray. 3239 * @return a {@code String} that contains the characters of the 3240 * specified subarray of the character array. 3241 * @exception IndexOutOfBoundsException if {@code offset} is 3242 * negative, or {@code count} is negative, or 3243 * {@code offset+count} is larger than 3244 * {@code data.length}. 3245 */ 3246 public static String valueOf(char data[], int offset, int count) { 3247 return new String(data, offset, count); 3248 } 3249 3250 /** 3251 * Equivalent to {@link #valueOf(char[], int, int)}. 3252 * 3253 * @param data the character array. 3254 * @param offset initial offset of the subarray. 3255 * @param count length of the subarray. 3256 * @return a {@code String} that contains the characters of the 3257 * specified subarray of the character array. 3258 * @exception IndexOutOfBoundsException if {@code offset} is 3259 * negative, or {@code count} is negative, or 3260 * {@code offset+count} is larger than 3261 * {@code data.length}. 3262 */ 3263 public static String copyValueOf(char data[], int offset, int count) { 3264 return new String(data, offset, count); 3265 } 3266 3267 /** 3268 * Equivalent to {@link #valueOf(char[])}. 3269 * 3270 * @param data the character array. 3271 * @return a {@code String} that contains the characters of the 3272 * character array. 3273 */ 3274 public static String copyValueOf(char data[]) { 3275 return new String(data); 3276 } 3277 3278 /** 3279 * Returns the string representation of the {@code boolean} argument. 3280 * 3281 * @param b a {@code boolean}. 3282 * @return if the argument is {@code true}, a string equal to 3283 * {@code "true"} is returned; otherwise, a string equal to 3284 * {@code "false"} is returned. 3285 */ 3286 public static String valueOf(boolean b) { 3287 return b ? "true" : "false"; 3288 } 3289 3290 /** 3291 * Returns the string representation of the {@code char} 3292 * argument. 3293 * 3294 * @param c a {@code char}. 3295 * @return a string of length {@code 1} containing 3296 * as its single character the argument {@code c}. 3297 */ 3298 public static String valueOf(char c) { 3299 char data[] = {c}; 3300 return new String(data, true); 3301 } 3302 3303 /** 3304 * Returns the string representation of the {@code int} argument. 3305 * <p> 3306 * The representation is exactly the one returned by the 3307 * {@code Integer.toString} method of one argument. 3308 * 3309 * @param i an {@code int}. 3310 * @return a string representation of the {@code int} argument. 3311 * @see java.lang.Integer#toString(int, int) 3312 */ 3313 public static String valueOf(int i) { 3314 return Integer.toString(i); 3315 } 3316 3317 /** 3318 * Returns the string representation of the {@code long} argument. 3319 * <p> 3320 * The representation is exactly the one returned by the 3321 * {@code Long.toString} method of one argument. 3322 * 3323 * @param l a {@code long}. 3324 * @return a string representation of the {@code long} argument. 3325 * @see java.lang.Long#toString(long) 3326 */ 3327 public static String valueOf(long l) { 3328 return Long.toString(l); 3329 } 3330 3331 /** 3332 * Returns the string representation of the {@code float} argument. 3333 * <p> 3334 * The representation is exactly the one returned by the 3335 * {@code Float.toString} method of one argument. 3336 * 3337 * @param f a {@code float}. 3338 * @return a string representation of the {@code float} argument. 3339 * @see java.lang.Float#toString(float) 3340 */ 3341 public static String valueOf(float f) { 3342 return Float.toString(f); 3343 } 3344 3345 /** 3346 * Returns the string representation of the {@code double} argument. 3347 * <p> 3348 * The representation is exactly the one returned by the 3349 * {@code Double.toString} method of one argument. 3350 * 3351 * @param d a {@code double}. 3352 * @return a string representation of the {@code double} argument. 3353 * @see java.lang.Double#toString(double) 3354 */ 3355 public static String valueOf(double d) { 3356 return Double.toString(d); 3357 } 3358 3359 /** 3360 * Returns a canonical representation for the string object. 3361 * <p> 3362 * A pool of strings, initially empty, is maintained privately by the 3363 * class {@code String}. 3364 * <p> 3365 * When the intern method is invoked, if the pool already contains a 3366 * string equal to this {@code String} object as determined by 3367 * the {@link #equals(Object)} method, then the string from the pool is 3368 * returned. Otherwise, this {@code String} object is added to the 3369 * pool and a reference to this {@code String} object is returned. 3370 * <p> 3371 * It follows that for any two strings {@code s} and {@code t}, 3372 * {@code s.intern() == t.intern()} is {@code true} 3373 * if and only if {@code s.equals(t)} is {@code true}. 3374 * <p> 3375 * All literal strings and string-valued constant expressions are 3376 * interned. String literals are defined in section 3.10.5 of the 3377 * <cite>The Java™ Language Specification</cite>. 3378 * 3379 * @return a string that has the same contents as this string, but is 3380 * guaranteed to be from a pool of unique strings. 3381 */ 3382 public native String intern(); 3383 }