Question:
public class ScopeLifetimeVariables {
public static void main(String[] args) {
int x = 5;
int result = multiplyByTwo(x);
System.out.println(result);
}
public static int multiplyByTwo(int num) {
int temp = num;
num = num * 2;
return num;
}
}
What will be the output of the above Java program?
A) 5 B) 10 C) 15 D) It will result in a compile-time error.
Explain your answer and also discuss the scope and lifetime of the variables used in the program.
Answer:
The output of the above program will be:
10
Explanation:
The program begins by declaring and initializing an integer variable x
with the value 5
. Then, it calls the multiplyByTwo
method passing the value of x
as an argument.
Inside the multiplyByTwo
method, a local variable num
is declared and initialized with the value passed as an argument. In this case, num
will have the value 5
.
A temporary local variable temp
is declared and assigned the value of num
, which is 5
in this case.
The program then multiplies the value of num
by 2 and assigns the updated value to num
. So, num
becomes 10
.
Finally, the method returns the value of num
which is then stored in the result
variable in the main
method.
The value of result
, which is 10
, is then printed using the System.out.println
statement, resulting in the output 10
.
Scope and Lifetime of Variables:
x
declared in the main
method has a scope limited to the main
method, hence it cannot be accessed outside this method.result
also has a scope limited to the main
method, and its lifetime is until the end of the main
method.num
in the multiplyByTwo
method has a scope limited to the multiplyByTwo
method. It's a local variable accessible only within the method. Its lifetime is until the method finishes executing.temp
is also a local variable within the multiplyByTwo
method, with a limited scope and lifetime within the method. It ceases to exist after the method finishes executing.num
created in the multiplyByTwo
method shadows the num
parameter. It is specific to the method and has no impact on other parts of the program.