When I don't include the commented line开发者_如何学C, prevLineBuffer contains "null." When i do include the commented line it still works, but prints an empty string. Does Java statically allocate space for the declared string and then dynamically allocate space for an additional string in the commented line? Both appear to work...
public class Indexer {
String input;
StringBuilder prevLineBuffer;
Indexer(String inputFileName) throws RuntimeException{
input = inputFileName;
//prevLineBuffer = new StringBuilder();
System.out.print(prevLineBuffer);
}//constructor
}//class
You need to print the result of .toString()
, and .append()
something to it, in order to give it something to print. For example:
prevLineBuffer = new StringBuilder();
prevLineBuffer.append(inputFileName);
System.out.print(prevLineBuffer.toString());
To answer the second half of your question...
From the String docs:
A pool of strings, initially empty, is maintained privately by the class String. [...] When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
From the StringBuilder docs:
In general, if sb refers to an instance of a StringBuilder, then sb.append(x) has the same effect as sb.insert(sb.length(), x). Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger. -
In short, printing a null reference of anything to a PrintStream (which is what System.out is) will append "null". This is because the print() and println() methods explicitly test for null, using something like: txt=(obj==null ? "null" : obj.toString());
When you create the StringBuilder instead of leaving it null, what is printed is StringBuilder's toString(), which if you have added nothing is an empty string, or... nothing.
Java does not statically allocate space for objects. The line
StringBuilder prevLineBuffer;
declares a reference to a StringBuilder. The StringBuilder itself does not exist before you invoke the constructor. Thus you get a NullPointerException - the prevLineBuffer reference is null.
The reason why your prevLineBuffer is empty is simply that you never append any content to it - see also the other replies.
精彩评论