Friday, February 21, 2014

Interview Question about Static in java

1.What is static method?

Static method is a method , it should be declared with keyword static.

2.How will you call static method?

static method should be called by className.static method name.

e.g   A.test();
Here A is a class ad test is a static method.

3.Can I call static method with the help of object?

No. Before creating object static method should be called. I mean, static mehtod is not part of the object.

4.Can I use instance variable inside the static method?

No. JVM will create the object and instance variables after executing static method.So you can not use instance variable inside the static method.

5.What is static block?

static block is a block of statements declared as static.

e.g
static {
System.out.println("You are insdie static block");
}

6.Can I override static method in java?

No.

7.Can I overload static method?

Yes.

public class Test {
    public static void test() {
        System.out.println("Test for static overload I");
    }
    public static void test(int a) {
        System.out.println("Test for static overload II");
    }
    public static void main(String args[])
    {
        Test.test();
        Test.test(2);
    }
}

Output:

Test for static overload I
Test for static overload II

8.I have static block, static method and static variable. what is the order of execution?

static variable, static block, static method.

No comments:

Post a Comment