7

"It is important to point out that the content field of the template is by default set to null (as Java does with all noninitialized object fields upon creation)."

It is from book "JavaSpaces Principles Patterns and Practice"

Here is code:

public class Message implements Entry {
  public String content;
  public Message() {
  }
}

I wonder if this is true, because I watched somewhere on internet that this is not true?

5
  • Write it up, compile it, run it, use an IDE, debug it. Commented Aug 10, 2011 at 22:57
  • Perhaps you should link to the article that claims this is not true so that we can help explain what it really meant. Commented Aug 10, 2011 at 22:58
  • @Adam I am not sure of this internet address, maybe I am wrong, I don't remember. Commented Aug 10, 2011 at 23:02
  • 1
    @Marcelo, you are right, I tried to println uninitialized String and it prints null. But it was confusing me that int default value is 0. kylc explained this below. Commented Aug 10, 2011 at 23:06
  • Yes, kylc's answer clearing up that primitive types behave differently is spot on. Commented Aug 10, 2011 at 23:11

2 Answers 2

9

Yes, this is true, but it may not mean quite what you think it means. All object fields will be initialized to null if no value is specified, but primitive types have other default values. For instance, int fields default to 0, floats to 0.0, and booleans to false.

More information on these defaults here: http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html.

Sign up to request clarification or add additional context in comments.

3 Comments

just to complete: (one of) the reason for this is that a primitive type can not be null
@kylc: Can I explicitly initialize the int member variable value to something like 2, float member variable to 4.4? Likewise initialize String and boolean variables? Is it possible?
@kylc: I realize that it can be can be done using a constructor, but can it done while declaring itself? Just curious..
5

It is probably true, but if you really want to be sure that content starts as null, then set it explicitly. (Doing this also makes it more clear that your code intends content to be null initially.)

public String content = null;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.