Java. Initialize variables in class methods. Initialization of fields (data members) of the class. Ways to initialize data members of the class




Initialize variables in class methods. Initialization of fields (data members) of the class. Ways to initialize data members of the class

This topic demonstrates how to initialize the internal members of the class data in the Java programming language.


Contents


Search other websites:

1. The concept of initializing variables in Java methods

Initializing a variable means an explicit (or implicit) setting of a variable value.

In the Java programming language, the variables declared in the method must be initialized before they are used.

If in the body of some class method, try use the declared but not initialized variable, the compiler will generate an error.

For example. In the following code snippet, an attempt is made to use the variable t, which is declared but not initialized

static void SomeMethod()
{
    int t;
    int x;

    x = 6;
    x = x + t + 2; // error: the variable t not initialized
}

In this case, an error message will occurs:

The local variable t may not have been initialized

To correct the situation, you need to assign a value to the variable t before using it.

 2. What are the ways of initializing data members of the class?

In Java, you can initialize a variable if it is a member of the class. There are four ways to initialize members of the class data:

  • initialization by default (implicit initialization);
  • explicit initialization with initial values (constant values);
  • explicit initialization using class methods;
  • initialization using class constructors.



3. Initialization of data fields of the class. What is the initialization by default of data fields of the class? 

If the variable is a data member of the class, this variable is initialized with the default value, when it is declared.

That is, if there is a class in which internal variables are declared (class fields)

class SomeClass
{
    int d;
    double x;

    // ...
}

 these variables (d, x) will be initialized with the default value. In the above code, the default variable will be assigned the following values

d = 0.0
x = 0

 It does not matter which access identifier is used for the variable (private, protected, public) in the class.

4. What default values are assigned to the class fields for different types?

When you declare a variable in a class, this variable is set to the default values. The following are the default values that are assigned to variables of different types

int       => 0
boolean   => false
double    => 0.0
float     => 0.0
char      => ' ' - zero-character
long      => 0
byte      => 0

A character variable of type char is assigned a null character, which is displayed as a space character.

5. What value initializes a reference variable of a class object?

If the class declares a reference variable to an object of a certain class, then by default, the value of this reference is null.

The following code fragment demonstrates this.

// some class
public class InnerClass
{
    // ...
}

// class in which an object of the InnerClass class is declared
public class MyClass
{
    // ...

    public static InnerClass obj; // obj = null; - by default

    // ...
}

In the above example, the variable obj is a reference to the InnerClass class. In other words, obj is an object of the InnerClass class. Because, the memory for obj is not already allocated, the default value of obj = null.

6. Explicit initialization. How is realized an explicit initialization by initial values of data members of class?

Explicit initialization means setting the initial (necessary) value of the variable when it is declared in the class.

For example. The MyClass class implements the initialization of variables of different types with initial values.

public class CTrain01
{
    // explicit initialization of initial values of variables
    int d = 25; // explicit initialization of a variable d of type int with a value 25
    float y = 3.885f;
    public double x = -129.48;
    boolean b = true;
    char c = 'Z';
    long l = 0xF3309FA;

    // ...
}

7. How is realized an explicit initialization of data members of a class that are variable-references to a class

If a data member of the class has a reference variable to some class (a class object), then it is initialized in the standard way with the new operator:

class InnerClass
{
    // ...
}

class MyClass
{
    // ...

    // explicit initialization of variable obj in class MyClass
    InnerClass obj = new InnerClass();

    // ...
}

In the MyClass class, the obj reference variable must be initialized with the ‘new’ operator before it can be used. If you try to use an uninitialized variable, which is a reference to the class, an exception will occur.

8. Explicit initialization by calling methods. How is the value of a class data member initialized by a method call?

Members of the class data can be initialized by calling some method.

For example. Let the class CRadius be given. In the CRadius class, data members len, area, volume are initialized by calling the Length(), Area(), Volume() methods. These methods calculate, respectively, the circumference, the area of the circle, and the volume of the sphere of radius r, which is the input parameter of the methods.

public class CRadius
{
    // hidden variables
    private double Pi = 3.1415;
    private double radius=1;

    // public variables
    public double len = Length(radius); // Initializing the len variable with the Length() method
    public double area = Area(radius); // initializing the area variable with the Area() method
    public double volume = Volume(radius); // initializing the volume variable

    // calculation methods
    double Length(double r)     { return 2*Pi*r; }
    double Area(double r)   { return Pi*r*r; }
    double Volume(double r) { return 4.0/3.0*Pi*r*r*r; }

    public static void main(String[] args)
    {
        // demonstration of initialization using CRadius class methods
        CRadius r1 = new CRadius(); // there is an explicit initialization of the data members of the object r1
        double l, a, v;

        l = r1.len; // l = 6.283
        a = r1.area; // a = 3.1415
        v = r1.volume; // v = 4.1886666666
    }
}





9. What is the order of initialization when declaring variables? What is the value of the initialization order when declaring variables? Examples

In a class, variables are initialized first. Initialization of variables occurs even before the class constructor is called. The order of initialization of variables is determined by the order of their declaration in the class (see Example 1). After the variables are initialized, the constructor is called. In this case, declaration and initialization of variables can be implemented anywhere in the class (see example 2).

As can be seen from the program code in section 8, the variables are declared in a strictly defined sequence, in which the value of the initializing variables and methods (to the right of the assignment operation) was determined at the time of initialization.

Example 1. Let the class CInitOrderClass be specified, in which the value of the next data member is initialized by the value of the previous member of the data or method.

// the class demonstrates the correct initialization order
public class CInitOrderClass
{
    int t1 = 5;
    int t2 = SomeMethod(); // t2 = 100;
    int t3 = t2; // t3 = 100
    int t4 = t1 + t3; // t4 = 5 + 100 = 105
    int t5 = SomeMethod() + t4; // t5 = 205

    // method that is used when initializing
    int SomeMethod()
    {
        return 100;
    }

    public static void main(String[] args)
    {
        // use of a CInitOrderClass object
        CInitOrderClass obj = new CInitOrderClass();
        int d;

        d = obj.t1; // d = 5
        d = obj.t2; // d = 100
        d = obj.t3; // d = 100
        d = obj.t4; // d = 105
        d = obj.t5; // d = 205
    }
}

If you change the order of declaration and initialization in the class, an error may occur. For example, if the declaration of variable t4 is placed at the very top of the declarations of members of the class data:

public class CInitOrderClass
{
    int t4 = t1 + t3; // t4 = ??? - here an error, variables t1, t3 have not yet been declared
    int t1 = 5;
    int t2 = SomeMethod(); // t2 = 100;
    int t3 = t2; // t3 = 100
    int t5 = SomeMethod() + t4; // t5 = 205

    // ...
}

then there will be a compilation error

Cannot reference a field before it is defined

This is logical, since the variable declaration is viewed from top to bottom (from the beginning to the end). At the time the variable t4 is declared, the variables t1 and t3 that take part in the initialization are not yet declared. This is the cause of the error.

This does not apply to the method of the SomeMethod() class, which can be used when initializing anywhere in the class.

Example 2. This example demonstrates a rule in which any internal class variable (class data member) is initialized first, even before calling the constructor.

Let the class COrderInit be given, in which the three variables a, b, c are initialized using the InitMethod() method and using the COrderInit() constructor.

// the class demonstrates the initialization order
public class COrderInit
{
    int a = InitMethod("a = "); // Initializing the variable a using the method

    // initializing variables with a constructor
    COrderInit()
    {
        a = b = c = 0;
        System.out.println("Constructor COrderInit().");
    }

    int c = InitMethod("c = "); // initializing variable c

    // method of initializing variables
    int InitMethod(String s)
    {
        System.out.println(s + "InitMethod().");
        return 100;
    }
    
    int b = InitMethod("b = "); // initialization of varible b

    public static void main(String[] args)
    {
        COrderInit obj = new COrderInit();
    }
}

As you can see from the above code, the class contains the main() function, in which an object of the COrderInit class is created. The method of the InitMethod() class gets the string s as the input parameter. This line displays an initialization string with the name of the corresponding variable. As a result of executing this code, the following result will be output:

a = InitMethod().
c = InitMethod().
b = InitMethod().
Constructor COrderInit().

The result shows that the initialization of the variables a, c, b occurs first. The order of initialization of variables is determined by the order of their declaration in the class. After that, the constructor is called.

10. How is the initialization done using the constructor?

The initialization of data members of a class using the constructor is described in more detail in the topic:

11. How is it possible to initialize the members of the class data using the initialization section { }? Example

Members of class can be initialized in one section, as shown in the example.

public class CDataInit
{
    int a, b, c, d;

    // Initialization using the initialization section {}
    {
        a = 1;
        b = 2;
        c = 3;
        d = 4;
    }

    public static void main(String[] args)
    {
        CDataInit obj = new CDataInit();
        int t;

        t = obj.a; // t = 1
        t = obj.b; // t = 2
        t = obj.c; // t = 3
        t = obj.d; // t = 4
    }
}

12. What is done first: the initialization section or the constructor?

The initialization section is executed first and then the class constructor.


Related topics