Open In App

Output of Java Programs | Set 48 (Static keyword)

Last Updated : 10 Oct, 2017
Comments
Improve
Suggest changes
Like Article
Like
Report
Prerequisite : Static keyword in Java Question 1. what is the output of this question? JAVA
class Test1 {
public
    static void main(String[] args)
    {
        int x = 20;
        System.out.println(x);
    }
    static
    {
        int x = 10;
        System.out.print(x + " ");
    }
}
Option A) 10 20 B) 20 10 C) 10 10 D) 20 20
Output: A
Explanation : Static block is executed before main method. If we declare a Static block in java class it is executed when class loads. Question 2. what is the output of this question? JAVA
class Test1 {
    int x = 10;
public
    static void main(String[] args)
    {
        System.out.println(x);
    }
    static
    {
        System.out.print(x + " ");
    }
}
Option A) 10 10 B) Error C) Exception D) none
Output: B
Explanation : If we are trying to print the instance variable inside the static block or static method without creating class instance then it will give the error : non-static variable x cannot be referenced from a static context. Question 3. what is the output of this question? JAVA
class Test1 {
    int x = 10;
public
    static void main(String[] args)
    {
        Test1 t1 = new Test1();
        System.out.println(t1.x);
    }
    static
    {
        int x = 20;
        System.out.print(x + " ");
    }
}
Option A) 10 20 B) 20 10 C) 10 10 D) Error
Output: B
Explanation : We can print the instance variable inside the static method after creating the class reference. Question 4. what is the output of this question? JAVA
class Test1 {
    int x = 10;
public
    static void main(String[] args)
    {
        System.out.println(Test1.x);
    }
    static
    {
        int x = 20;
        System.out.print(x + " ");
    }
}
Option A)10 10 B) 20 20 C) 20 10 D) Error
Output: D
Explanation : We can not access the instance variable with class name. otherwise it will give the error : non-static variable x cannot be referenced from a static context Question 5. what is the output of this question? JAVA
class Test1 {
    static int x = 10;
public
    static void main(String[] args)
    {
        Test1 t1 = new Test1();
        Test1 t2 = new Test1();

        t1.x = 20;
        System.out.print(t1.x + " ");
        System.out.println(t2.x);
    }
}
Option A) 10 10 B) 20 20 C) 10 20 D) 20 10
Output: B
Explanation : static variable is class level variable. if we do update in any reference then automatically all pointing reference value are changed.

Next Article
Practice Tags :

Similar Reads