3
public class Ex
{
  int a;
  public Ex()
  {
      System.out.println("a is "+a);
   }
}

output is:a is 0

where a gets initialized...

i know that default values for int is zero..my question is that where it gets initialied ..through default constructor ?(i heard that default constructor is created when we don't mention any constructor in the class)

1
  • @Qwerky, different title I think. For Googling it matters. The text should probably be edited, though, to reflect differences in the title. Commented Feb 2, 2011 at 12:55

13 Answers 13

6

If you didn't initalize a yourself (it's a primitive value), it gets initialized automatically to it's default value, 0 in this case.

Read section 4.5.5. (Initial Values of Variables) in this document.

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

Comments

5

No, there is no default constructor when you write a specific on. But fields get initialized before any constructor is called. After initialization of fields initializers ({.. some code .. } blocks)are run and finally the constructor is executed.

2 Comments

To be precise, fields initializers and instance initializers are executed not before the constructor, but as a part of its execution, and even not as the first step. For example, if a constructor begins with a super(...) line, then initializers are executed after that line.
An instance variable is created with an initial value. There is no default assignment or hidden initialization code in the java class. Some space on the heap is cleared and allocated for each field and so the initial value is 0 or null for object references.
5

Its default value is 0.

From The Java™ Tutorials - Primitive Data Types - Default Values:

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler.

╔══════════════════════════╦════════════════════════════╗
║        Data Type         ║ Default Value (for fields) ║
╠══════════════════════════╬════════════════════════════╣
║ byte                     ║ 0                          ║
║ short                    ║ 0                          ║
║ int                      ║ 0                          ║
║ long                     ║ 0L                         ║
║ float                    ║ 0.0f                       ║
║ double                   ║ 0.0d                       ║
║ char                     ║ '\u0000'                   ║
║ String (or any object)   ║ null                       ║
║ boolean                  ║ false                      ║
╚══════════════════════════╩════════════════════════════╝

2 Comments

"my question is that where it gets initialied" (emphasis added).
@Readwald ok check update :) and Read More also answers this.
3

The reason why a has an initial value is written in the Java language specification (4.12.5):

Each class variable, instance variable, or array component is initialized with a default value when it is created

a is an instance variable (a non static field) and so it has an initial value. The value itself is specified too:

For type int, the default value is zero, that is, 0.

It may be interesting to know that this is different for local variables (variables declared in a method body):

A local variable must be explicitly given a value before it is used, by either initialization or assignment, in a way that can be verified by the compiler using the rules for definite assignment.

So if you read a local variable that has not been initialized or "set" in your code yet, the compiler will give an error.

Comments

3

Definitely not in the default constructor. According to the JLS, it happens as a part of evaluation of a class instance creation expression (when you do new ClassName...), before any constructor call. From the JLS, Java SE 8 Edition, 15.9.4:

Next, space is allocated for the new class instance. If there is insufficient space to allocate the object, evaluation of the class instance creation expression completes abruptly by throwing an OutOfMemoryError.

The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its default value (§4.12.5).

Next, the actual arguments to the constructor are evaluated, left-to-right. If any of the argument evaluations completes abruptly, any argument expressions to its right are not evaluated, and the class instance creation expression completes abruptly for the same reason.

Next, the selected constructor of the specified class type is invoked. This results in invoking at least one constructor for each superclass of the class type. This process can be directed by explicit constructor invocation statements (§8.8) and is specified in detail in §12.5.

Comments

1

The int has a default value of 0

See this link to find out the different default values depending on the type.(Default Values section)

Comments

1

a isn't being initialized so it's giving a zero value because the default value of an int is 0.

Comments

1

a has a primitive type int. In your code, a is uninitialized with a default value of 0.

Comments

1

To clear your head, if you had not declared a zero-argument constructor and your class had no constructor(s), java creates a default zero-argument constructor for you.

As for your primitive types, once declared, its initialized (if uninitialized) with default values before use.

2 Comments

if you specify a constructor though the compiler will not create a zero-argument constructor.
@dimitrisli, true (fill blanks here)
1

In java instance variables will be initialised from the constructor ( default if you don't have one).

public class TestFile {  
String x = null;  
int y = x.length();  
    public TestFile() {  
        // TODO Auto-generated constructor stub  
    }  
    /**  
     * @param args  
     */  
    public static void main(String[] args) {  

        TestFile tf = new TestFile();  
   }  
}  

you will get a stacktrace

Exception in thread "main" java.lang.NullPointerException  
    at TestFile.<init>(TestFile.java:7)  
    at TestFile.main(TestFile.java:16) 

is called within the constructor.
For static fields, initialisation during class loading

2 Comments

I thought about testing it like this too, but then decided to consult the JLS. It turns out that this is not correct. Explicit field initializers (like in your example) are executed in the constructor, that's true, but default initialization happens even before the arguments to the constructor are evaluated (see my answer), and it happens even if there is an explicit initializer (see the link in this comment).
Didn't know that.. thanks :-) Also thanks to the elite gentleman for formatting the code..i didn't really get the hang of it
0

primitives are initialized before constructor is called

1 Comment

References are initialized to null at the very same moment, so mentioning primitives here is misleading.
0

it occurs when Java allocates memory for a class. It fils all fields with default values;

Comments

0

§ JLS - 8.8.9 Default Constructor

In your code you have supplied constructor if you haven't then .

If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided: If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor takes no parameters and simply invokes the superclass constructor with no arguments

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.