Java Interview Questions Set 7
Categories: Java 8(JDK1.8)
What is the output of the following Java program?
class Test
{
int test_a, test_b;
Test(int a, int b)
{
test_a = a;
test_b = b;
}
public static void main (String args[])
{
Test test = new Test();
System.out.println(test.test_a+" "+test.test_b);
}
}
What is the static variable?
The static variable is used to refer to the common property of all objects (that is not unique for each object), e.g., The company name of employees, college name of students, etc. Static variable gets memory only once in the class area at the time of class loading. Using a static variable makes your program more memory efficient (it saves memory). Static variable belongs to the class rather than the object.
What is the static method?
1) A static method belongs to the class rather than the object.
2) There is no need to create the object to call the static methods.
3) A static method can access and change the value of the static variable.
What are the restrictions that are applied to the Java static methods?
Two main restrictions are applied to the static methods.
a) The static method can not use non-static data member or call the non-static method directly.
b) this and super cannot be used in static context as they are non-static.
Why is the main method static?
Because the object is not required to call the static method. If we make the main method non-static, JVM will have to create its object first and then call main() method which will lead to the extra memory allocation.