Put your text ad here
WestNIC provides reliable web hosting services
Free software downloads and drivers download resources
25% off cpanel web hosting and reseller hosting deals. Promo: codestyle25off
This FAQ is part of the Code Style Help and FAQ section. Join our premium content service for full access all FAQs, or choose the single FAQ by email option for premium answers.
String class declared final?
== operator doesn't match strings correctly!
+ operator overloaded?
+ operator is not overloaded in Java!
String and StringBuffer?
StringBuffer instead of a String?
StringBuffers match?
StringBuffers?
StringBuffer?
StringTokenizer for?
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 omitted
Get full access to all FAQs, subscribe now for $40
Why is the String class declared final?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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");
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
== 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 omitted
Get full access to all FAQs, subscribe now for $40
The == operator doesn't match strings correctly!
Actions: Follow-up, clarify or correct this answer. Submit a new question.
+ operator is not overloaded in Java!
A: The plus operator for Java strings is a limited exceptional case that is practically the same as operator overloading. Its a fine distinction but using + to append object contents is not a general case in Java, it only applies to String objects. An equivalent append operation may be meaningful and useful for data storage types but does not have a general application and is not implemented in Java.
// Compiler error: "operator + cannot be applied to java.util.Vector"
// Vector vector = new Vector() + new Vector();
… premium content omitted
Get full access to all FAQs, subscribe now for $40
How can you say the + operator is not overloaded in Java!
Actions: Follow-up, clarify or correct this answer. Submit a new question.
+ 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.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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 omitted
Get full access to all FAQs, subscribe now for $40
How can I reverse the characters in a string?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
String and StringBuffer?
A: The main difference is that in Java Strings are immutable objects, which makes them quite inefficient for concatenating substantial amounts of text, especially in extensive loops. For each String concatenation statement the Java runtime system must instantiate at least one additional String object and then dispose of it. StringBuffer is designed exactly to overcome this problem, to build string content in an editable internal buffer without generating lots of additional objects. StringBuffer has many convenience methods to append all Java primitive types, character arrays and objects, and to check and manipulate characters in the buffer.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
StringBuffer instead of a String?
A: In most cases you should use a StringBuffer rather than string concatenation. Java String objects are immutable; whenever you concatenate two String instances you actually create a third String object for the result. This implicit String object creation can slow down your program, increase the number of objects in the runtime system and the garbage collection required to dispose of the temporary strings.
On a small scale, string concatenation is unlikely to have a significant performance impact, but if you are building strings in a for or while loop, or over many statement lines it is better to use a StringBuffer, or StringBuilder in single threaded applications.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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 omitted
Get full access to all FAQs, subscribe now for $40
Why don't two StringBuffers match?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
StringBuffers?
A: The key difference between a String and a StringBuffer in terms of memory allocation is that String objects are immutable; once the string contents are set they cannot be changed, so the virtual machine can optimise memory use on this basis. The content of StringBuffers can be expanded beyond their initial buffer size, so the memory allocation needs to be variable and must be managed by the Java runtime system. The StringBuffer class automatically adjusts its buffer size to fit the string content it is given, but you should instantiate the class with an explicit buffer size large enough to avoid the performance overhead associated with such resizes.
StringBuffer buffer = new StringBuffer(1024);
Java programmers should not be concerned with detailed level memory management for String operations, which will be handled and optimised by the runtime system. The key things are to choose String or StringBuffer types appropriate to the task and set an adequate buffer size.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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 omitted
Get full access to all FAQs, subscribe now for $40
How can I pad a StringBuffer?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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 omitted
Get full access to all FAQs, subscribe now for $40
What is a StringTokenizer for?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: The simplest way to extract single words from a string like a full name is to use a StringTokenizer, which is a special type of Enumerator. The String method charAt(int) can then be used to get the first character of each word, as below.
… premium content omitted
Get full access to all FAQs, subscribe now for $40
How can I get a person's initials from their full name?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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 omitted
Get full access to all FAQs, subscribe now for $40
How can I check a string has no numbers?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
| Front-end FAQs | Back-end FAQs | Learning Java |
|---|---|---|
About us: site help, text ads, sponsored links and premium content FAQs.