What is a variable? How we define and initialize a variable?
Answers
Initializing a variable
Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all).
Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value. If the variable has been declared but not initialized, we can use an assignment statement to assign it a value.
Example: The following program contains a semantic error:
public class Java3 {
public static void main(String[] args) {
String line;
System.out.println(line);
System.out.println(line);
}
}
The variable line is not initialized before we request to print it (the error is detected at compile time).
A variable can be initialized at the moment it is declared, through the statement:
type variableName = expression;
In Java, the above statement is equivalent to:
type variableName;
variableName = expression;
Example:
String line = "java".toUpperCase();
is equivalent to
String line;
line = "java".toUpperCase();
.