java 字符串缓冲区声明
当我不包含注释行时,prevLineBuffer 包含“null”。当我包含注释行时,它仍然有效,但打印一个空字符串。 Java 是否为声明的字符串静态分配空间,然后为注释行中的附加字符串动态分配空间?两者似乎都有效...
public class Indexer {
String input;
StringBuilder prevLineBuffer;
Indexer(String inputFileName) throws RuntimeException{
input = inputFileName;
//prevLineBuffer = new StringBuilder();
System.out.print(prevLineBuffer);
}//constructor
}//class
When I don't include the commented line, 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要打印
.toString()
的结果,并为其添加.append()
内容,以便为其提供打印内容。例如:要回答问题的后半部分...
来自 字符串文档:
来自 StringBuilder 文档:
You need to print the result of
.toString()
, and.append()
something to it, in order to give it something to print. For example:To answer the second half of your question...
From the String docs:
From the StringBuilder docs:
简而言之,将任何内容的空引用打印到 PrintStream(这就是 System.out)都会附加“null”。这是因为 print() 和 println() 方法显式测试 null,使用类似以下内容:
txt=(obj==null ? "null" : obj.toString());
当您创建StringBuilder 而不是将其保留为 null,打印的是 StringBuilder 的 toString(),如果您没有添加任何内容,则它是一个空字符串,或者...什么都没有。
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 不为对象静态分配空间。该行
声明了对 StringBuilder 的引用。在调用构造函数之前,StringBuilder 本身并不存在。因此,您会得到一个 NullPointerException - prevLineBuffer 引用为 null。
您的 prevLineBuffer 为空的原因很简单,就是您从未向其中添加任何内容 - 另请参阅其他回复。
Java does not statically allocate space for objects. The line
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.