Sobes.tech
Junior — Middle

How can you set the initial value of a variable in your code?

sobes.tech AI

Answer from AI

In Java, the initial value of a variable can be set in several ways:

  1. When declaring the variable:
int count = 10;
String name = "Ivan";
  1. In the class constructor, if the variable is a field of the object:
public class Person {
    private String name;

    public Person() {
        this.name = "Unknown";
    }
}
  1. Using initializer blocks for class fields:
private int number;
{
    number = 5;
}
  1. For local variables, you must assign a value before use; otherwise, the compiler will give an error.

Thus, the initial value of a variable is the value it receives upon creation to avoid an undefined state.