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:
- When declaring the variable:
int count = 10;
String name = "Ivan";
- In the class constructor, if the variable is a field of the object:
public class Person {
private String name;
public Person() {
this.name = "Unknown";
}
}
- Using initializer blocks for class fields:
private int number;
{
number = 5;
}
- 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.