J2EEOnline J2EE  


Java Questions 41 - 50  «Prev  Next»

Java Array Declarations(Interview Questions)

  1. Can the following be declared with arrays in Java?
    int [][] globalArray = new int [3][];
    


    Answer:
    Yes. As a counter example the following line of code is incorrect and will result in a compiler error.
    int [][] array1 = new int[][];
    

    A minimum of 1 dimension is required when declaring arrays in Java.

  2. Write a Java constructor that accepts 2 array arguments.

    Answer:
    public class ArrayDemo {
     private int[] num1 = new int[3];
     private int[] num2 = new int[3];
     public ArrayDemo() { };
     public ArrayDemo(int[] array1, int[] array2) {
      this.num1 = array1;
      this.num2 = array2;
     }
     public static void main(String[] args) {
      ArrayDemo ad1 = new ArrayDemo(new int[] {1,2,3} ,new int[] {1,2,3} );
     }
    }
    

  3. Can a constructor take a) arrays b) objects as parameters?

    Answer:
    Yes

  4. What are arguments when calling a method?

    Answer:
    Arguments are the elements you specify between the parentheses when you are invoking a method. The parameters are the elements in the methods signature.

  5. What is static import?

    Answer: static import enables access to static members of a class without need to qualify it by the class name.

  6. How can you think of each of the elements in the primeArray?
    int [][] primeArray = {{1,3,5}, { 7,11,13}, { 17, 19, 23}};
    


    Answer:
    Each of the 3 elements in the primeArray is a reference variable to an int array.

  7. How do you create an anonymous array in Java.

    Answer:
    class AnonymousArray{
     static void print(int a[]) {
      for(int i=0;i<a.length;++i)
       System.out.print(a[i]+" ");
     }
     
     static void print(int a[][]) {
      for(int i=0;i<a.length;++i){
       for(int j=0;j<a[i].length;++j)
        System.out.print(a[i][j]+" ");
       System.out.println("");
      }
     }
     

     public static void main(String...s){
      //1d anonymous array 
      print(new int[]{11,23,31,43});
      System.out.println("\n Anonymous Array");
      //2d anonymous array 
      print(new int[][]{{2,3},{5,7},{11,13}});  
     }
    }
    

  8. How can you create an anonymous array for an array of int?

    Answer:
    int[] testScores;
    testScores = new int[] {4,7,2};
    

  9. Which primitive datatypes can an array of int hold?

    Answer:
    a) byte b) char c) short.

  10. What types of data can be assigned to an array?

    Answer:
    Any object that passes the "IS-A" test for the declared array type can be assigned to an element of that array.