World class Hard Drive Recovery and renowned raid recovery services

WestNIC provides reliable web hosting services

Site navigation below

This FAQ is part of the Code Style Help and FAQ section. Use the help request form below if your question is not answered here, but make sure you are asking the right question first.

Subscribe to this FAQ: RSS news feed

FAQ search

The String class

Q: Why is the String class declared final?

A: The short answer is that any class may be declared final if it is not considered suitable for extension, particularly if it is a highly specialised class. When an API class is very specialised, its internal behaviour may be quite complex and pose un-seen problems for anyone who would create a sub-class.

Premium Content: Follow this link for subscription information More details available to subscribers:
Why is the String class declared final?

Q: How many objects are created for identical strings?

A: Two string declaration statements would create two separate String object references. As strings they would have the same hash code and their equals(Object) method would return true, but they are separate object references.

String string1 = "test";
String string2 = "test";

if (string1.hashCode() == string2.hashCode()) {} // true

if (string1.equals(string2)) {} // true
      
Q: What's the use of the String constructor?

A: The explicit String constructor has the same result as using double quotes to implicitly create a string reference, in both cases the given string is assigned to the reference variable. However, passing a double quoted string argument to the String constructor actually makes two strings; the argument string is implicitly created inline and then its contents are copied to the new String instance. For this reason this constructor is largely redundant and not recommended for general purposes. The String constructor with String argument is rarely used except to create an independent copy of an existing string variable.

// Creates one string implicitly
String s = "This is test string";

// Creates two string instances
String s = new String("This is a test string");
      

String methods and operators

Q: One case prints a Java code, another a literal string!

A: Your sample code shows some confusion between reference values and literal strings. Whenever an object reference is passed to the System.out.println(Object) method, its toString() method is used to provide the output.

a a1 = new a();

out.println("a");
      

In this case, the instantiation of the class a, referenced by the variable a1 is legitimate, but the second line completely disregards it and will print the string literal "a". Whenever you put characters in double quote marks like this, the Java interpreter will treat it as a String object, not a reference to the class a or instance a1.

try{
  ...
}
catch(Exception e) {

  out.println(e);
}
      

In the second case the reference to the exception e will be printed by calling its toString() method. The default implementation of toString() inherited from the Object class will output a coded reference to the object in the Java Virtual Machine. If the toString() method has been overridden by the exception class, it may provide human readable diagnostic information.

Q: The == operator doesn't match strings correctly!

A: Java strings are represented as immutable object references, so standard logical comparison operators will not give the result one might expect. If you use the simple comparison operator on two string objects that represent the same string, it will return false. Always use the equals(Object) method to compare the contents of two strings, as below.

Premium Content: Follow this link for subscription information More details available to subscribers:
The == operator doesn't match strings correctly!

Q: Is the + operator overloaded?

A: Java does not have operator overloading, but string concatenation is a special case. When the + operator is applied to a String, the two values are appended as a new String. The Java interpreter converts primitive values, such as int and long, to their string values and then concatenates the strings.

Q: How can I reverse the characters in a string?

A: This example code gets a char array from the input string and loops through it to populate a second char array. The for loop uses two variables, i is incremented and j is decremented at each pass. The output array could be used to create a new string or output directly, as in this case.

Premium Content: Follow this link for subscription information More details available to subscribers:
How can I reverse the characters in a string?

String buffers and tokenizers

Q: How can I pad a StringBuffer?

A: The StringBuffer insert(int, String) method can be used to pad the buffer at specific locations. The method inserts the given string at the offset position indicated by the int value and shifts the original buffer contents right. The original string contents are preserved and the buffer length is increased by the length of the inserted string.

Premium Content: Follow this link for subscription information More details available to subscribers:
How can I pad a StringBuffer?

Q: Why don't two StringBuffers match?

A: The String class overrides the default implementation of the equals(Object) method to compare the string contents of each object. In this case equivalent string contents are considered equal. The StringBuffer class does not override the superclass Object equals(Object) method, which tests whether the argument refers to the same object reference.

Premium Content: Follow this link for subscription information More details available to subscribers:
Why don't two StringBuffers match?

Q: What is a StringTokenizer for?

A: The standard java.util.StringTokenizer class is a special type of Enumeration that represents segments of a string, which may be separated by one or more "delimiters". When you construct a StringTokenizer with a comma delimiter, it will identify each word in a comma separated list for instance.

Premium Content: Follow this link for subscription information More details available to subscribers:
What is a StringTokenizer for?

Regular expressions

Q: How can I check a string has no numbers?

A: The simplest way to check that a String does not contain any numbers is to use the regular expression class Pattern in the java.util.regex package. The method below uses the regular expression [^0-9]+ to check that none of the characters in the input string is a number. The square brackets define a character class. The negation modifier, ^, followed by the number range 0-9 means "not a number". The + quantifier asks the regular expression to match the character class one or more times.

Premium Content: Follow this link for subscription information More details available to subscribers:
How can I check a string has no numbers?

Help request

Use the form below to submit a help request or general enquiry about the Code Style Web site. Read our guidelines on asking the right questions first.

Information: Your email address will not be mis-used. If you include your address you may be sent a personal reply, you will not be added to any mailing list unless you request it. Read the site privacy statement for details.

Add this page to your chosen social bookmarking service

Style warning - please read

Home · CSS · Java · Javascript · HTML · Help · Log