[JAVA] When is the default value automatically entered without explicit initialization?

If you do not explicitly initialize, whether the initial value is automatically entered or the indefinite value is still entered, a summary of the differences depending on the language and declaration location.

Java#

Instance variable

The default value is automatically entered in the instance variable.

public class Sample{
    int x;    //Instance variables

    void show(){
        int tmp;    //Local variables
        System.out.println("x = " + x);
    }
}
Variable type Default value
int , short , byte , long 0
float , double 0.0
char '\u0000'
boolean false
Object reference null

Even in the case of an array, all elements have default values.

Local variable

Local variables are not automatically initialized. If you do not explicitly initialize it yourself, you will get a compile error.

However, even if it is a local variable, only the ** array is automatically initialized **.

Reference site http://www.booran.com/menu/java/format.html

C/C++#

Global variable

Global variables are initialized with default values.

#include <stdio.h>

int g_hoge;    //Global variables

int main(){
    int a;    //Local variables

    return 0;
}
Variable type Default value
int , short , long 0
float , double 0.0
char '\0'
bool false
Object reference NULL

Even in the case of an array, all elements have default values.

Local variable

Local variables are not automatically initialized.

Unlike Java, arrays of local variables are not initialized either.

For variables with static, even local variables are initialized.

Reference site http://edu.clipper.co.jp/pg-2-33.html

I'm not sure about variables of classes and structures because their behavior changes depending on the declaration location and how to create an instance.

Although it will initialize itself, it is better to explicitly initialize it yourself in programs that others see.

Recommended Posts

When is the default value automatically entered without explicit initialization?
Null value is entered when assigning to an array
[Swift] Get the timing when the value of textField is changed
How to output the value when there is an array in the array
[Rails] How to solve the problem that the default image is overwritten when editing without uploading the image [Active Storage]
[Java small story] Monitor when a value is added to the List
When the bean class name is duplicated
Initialize Ruby array with 0 like Java, that is, set the default value to 0