Saturday, February 5, 2011

Core Java-Sample questions-Part 4

16.

package tpg;

public class Tester {

    public static void main(String[] args) {
        Tester t = new Tester();
        t.display();
    }

    public void display() {
        int i = 1;
        while(boolean b=true){
            System.out.println("railfan");
        }
    }
}

Ans: Compilation Error
Explanation: There shouldn’t be any declaration in WHILE condition. The program would have compiled if variable ‘b’ was declared outside the WHILE condition and then used within the condition.

17.
package tpg;

public class Tester {
    int x=1;
    public static void main(String[] args) {
        Tester t = new Tester();
        System.out.println("Value of x: "+x);
    }
}

Ans: Compilation Error
Explanation: Non-static variable ‘x’ cannot be referenced from static context. Static declarations belong to class! It exists even before you create an instance. But instance variable x becomes alive only when you create an instance. So an instance variable like ‘x’ in our example cannot be referenced from static context.


18.

package tpg;

public class Tester {
    static int x=1;
    public void main(String []args){
       x=2;
      System.out.println(x);
    }
}

Ans: The program compiles fine. But it doesn’t runs. The main method should be declared as static.


19.
package tpg;

public class Tester{
    public static void main(String []args){
        Tester t=new Tester();
        t.display();
    }
    void display(){
        int x=1;
        for(int x=0;x<10;x++){
            System.out.println(x);
        }
    }
}

Ans: Compilation error.
Explanation: In the method display(), variable ‘x’ is declared twice. Such declarations are not allowed in Java.


20.

package tpg;

public class Tester {

    public static void main(String[] args) {
        Tester t = new Tester();
        t.display();
    }

    void display() {

        for (int x = 0; x < 10; x++) {          
        }
        System.out.println(x);
    }
}

Ans: Compilation Error
Explanation: Variable ‘x’ is out of scope. Any variable declared within for loop should be accessed within a for loop only. The variable ‘x’ scope is limited to for loop.

No comments:

Post a Comment