Friday, January 28, 2011

Core Java-Sample questions-Part 2

6.

public class Tester {
       void display(){
              String name="Wipro";
              System.out.println("Length "+name.length);
       }
       public static void main(String []args){
              Tester t=new Tester();
              t.display();
       }
}

Ans: Compilation error
Explanation: In the line System.out.println("Length "+name.length), instead of length, length() method should be used. Length() is a method in String class while length is an attribute to find array length.

7.
package practice;

public class Tester {
       void display(){
              int[] arr[]=new int[5];
       }
       public static void main(String []args){
              Tester t=new Tester();
              t.display();
       }
}
Ans: Compilation error
Explanation: In the line int[] arr[]=new int[5], a 2-D array is declared but size allocated is wrong.


8.
public class Tester {
       void display(){
              int[] arr[]=new int[5][5];
       }
       public static void main(String []args){
              Tester t=new Tester();
              t.display();
       }
}

Ans: No error.
Explanation: int[] arr[]=new int[5][5] is also a way of declaring 2-D array.

9.

package practice;

public class Tester {
       void display(){
              int[5][5] arr=new int[][];
       }
       public static void main(String []args){
              Tester t=new Tester();
              t.display();
       }
}
Ans: Compilation error.
Explanation: Array size cannot be initialized during declaration.

10.
package practice;

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

Ans: No error.
Explanation: It is perfectly legal to mention the size of first dimension and leave the other dimension empty.

No comments:

Post a Comment