What will be the output for the below code?
public class Test{
int i=8;
int j=9;
public static void main(String[] args){
add();
}
public static void add(){
int k = i+j;
System.out.println(k);
}
}
public class Test{
int i=8;
int j=9;
public static void main(String[] args){
add();
}
public static void add(){
int k = i+j;
System.out.println(k);
}
}
A. 17
B. 0
C. Compilation fails with an error at line 5
D. Compilation fails with an error at line 8
E. None of these
Answer: Option D
Solution(By Examveda Team)
i and j are instance variable and attempting to access an instance variable from a static method. So Compilation fails.
Join The Discussion
Comments ( 2 )
Related Questions on Data Types and Variables
What is the maximum value that can be stored in a byte variable in Java?
A. 127
B. 255
C. 32767
D. 64
What is the default value of an int variable in Java if it's not explicitly initialized?
A. 0
B. 1
C. -1
D. Null
Which of the following is not a valid identifier for a Java variable?
A. my_var
B. _myVar
C. 3rdVar
D. $var
Adding int k=i+j;
why can adding int k = i+j;