Sunday 16 August 2015

Java tricky interview questions

These are some tricky questions usually found in java questionnaire or interviews. Check the answers at the end. These are very easy to answer if you have the liberty to try on a computer.
Questions:
  1. The code in finally block will never get executed in the following program? True/False
 try {
        if (choice) {
             while (true)
        } else {
            system .exit(1):
        }
}finally {
    codetocleanup();
}
 
  1. Write an nearest equivalent of size operator in C. Hint: Use Runtime class.
  2. Which one is faster in java ?
    1. for(int i = 100000; i > 0; i--) {}
    2. for(int i = 1; i < 100001; i++) {}
  3. Which one is faster in java ?
    1. Math.max(a,b);
    2. (a>b)?a:b
  4. Is Array operations are faster or of Vector.
  5. What will be the value of Point p after methods in a and b if the value before method call is (700,800).
  6. static void changePoint ( Point p) {
                    p.x = 100; p.y=200;
                }
  7. static void changePoint(Point p) {
                    p=new Point(100,200);
                }
  8. MyClass.java and empty file is valid source file. True/False?
  9. Which one of these statements are valid?
    1. Char     \u0061r  a  =’a’;
    2. Char      \u0062      =  ’b’;
    3. Char               c       =’\u0063’;

    1. 1    b. 2      c.3     d. ALL     e. NONE
  10. Which one of these primitive types are unsigned?
    1. int
    2. long
    3. char
    4. double
    5. float
  11. Java supports both multi dimension and nested arrays. True/False
  12. public main(int number) { } is a valid method. True/False?
  13. public static final main(String[] args) {} is a valid method. True/False?
  14. A class without a method can be run by  JVM if its ancestor class has main. True/False?
  15. GC is  a high  priority thread. True/False?
  16. Can circular reference prevent an object to be GCed?
  17. If there is an exception in finalize method, will the object be garbage collected?
  18. An object is resurrected by making other object refer to the dying object in finalize method. Will this object be ever garbage collected?
  19. Can finalize method be overloaded?
  20. Does the finalize method in subclass invoke finalize method in super class?
  21. Which one throws arithmetic exception:
    1. int i = 100/0;
    2. float f = 100.00/0.0
  22. Which one is not correct
    1. x = = Float.NaN
    2. Float.isNan(x);
    3. Myobject .equals(float.NaN);
  23. What will be output from the following statements:
    1. System.out.println(1+2+”3”);
    2. System.out.println (“1”+2+3);
  24. Is the following statement correct:
    char ch = 'd';
    if(ch < 32.00){ }
     
  25. Determine the output:
    1. byte b=10;
      b=b+10;
      System.out.println("The value of b is " + b);
    2. byte b=10;
      b+=10;
      System.out.println("The value of b is " + b);
    3. char c = 3;
      int a = 65;
      char d = a;
      System.out.println("The value of d is " + d);
    4. float f = 1.3; 
      System.out.println("The value of f is " + f);
    5. float f = 1.3f; 
      System.out.println("The value of f is " + f);
    6. float f = 6/2;
      System.out.println("The value of f is " + f);
    7.  float f = 6.0/2.0;
      System.out.println("The value of f is " + f);
    8. byte b;
      final int a = 10;
      b=a;
      System.out.println("The value of b is " + b);
    9. byte b;
      final int a = 10;
      final int x = a;
      b = x;  
      System.out.println("The value of b is " + b);
    10. int y;
      final int z = y;
      b = z;  
      System.out.println("The value of b is " + b);
    11. public class precedence{
          public static void main(String[] args) {
                  int i = 0;
                  i=i++;
                  i=i++;
                  i=i++;
                  i=i++;
                  System.out.println("The value of i is " + i);
                  int   arr []= new int [5];
                  int index= 0;
                  arr [index]= index = 3;
                  System.out.println("The value of first element is " + arr[0]);
                  System.out.println("The value of fourth element is " + arr[3]);
          }
      }
    12. if(-0.0==0.0){
          System.out.println("-0.0==0.0");
      } else {
          System.out.println("-0.0!=0.0");
      }
  26. If you  have reference variable of parent class type and you assign a child class object to that  variable and invoke static method. Which method will be invoked? Parent/Child.
  27. Local variables can  not be  declared static or final or transient .True/False?
  28. Final variables declared without initialization can be initialized in static initializer ( static final var) or in constructor( final var). True/False?
  29. What is the use of transient variable? Can a transiant variable be static?
  30. What is the use of volatile variable?
  31. Random access file extends from File. True/False?
  32. Map implements collection. True/False?
  33. Dictionary is an interface or class?
  34. Can we declare derived class first and then base class in java?
  35. Can constructor throw exception?
  36. Array whether local or class  levels are always initialized. True/False?
  37. Can we cast two derived class for each other, both having same parent class. Yes/No
  38. Can inner class have static members? Yes/No
  39. Does File class have any method to read or write content in a file? Yes/No
  40. Which ones are classes and which ones are interfaces?
    1. InputStream, OutputStream
    2. DataInputStream, DataOutputStream
  41. What is the rule regarding overriding methods throwing exceptions?
  42. Member variables are resolved compiletime or runtime?
  43. Can we override variables?
    class S1{
            public string S= “ S1”;
            public string gets() {
                returns S;
            }
    }
    class S2 extend S1 {
            public string S = “ S2”;
            public string gets() {
                return s;
            }
    }
    public class shadow{
            public static void main(String S[]) {
                     S1 S1 = new S1();
                     S2 S2= new S2();
                     System.out.println("Print S1 " + s1.s); 
                     System.out.println("Print S1 " + S2.s);
                     S1=S2;
                     System.out.println("Print S1 now " + S1.S) ;
                     System.out.println( "Print S1.gets() now " + S1.gets());
            }
    }
  44. If an overridden method calls super class method which access class member variable, which variable will be used base class or super class.
    class S1 {
            string S= “ S1”;
            public string gets (){
                return S;
            }
            void display () {
                System.out.println("Display in S1 " + S);
            }
    }
    class S2 extends S1{
            string S= “ S2”;
            void display(){
                super.display();
                System.out.println("Display in S2 " +S);
            }
    }
    public class shadow 2   {
            string s =” base”;
            public static void main(String s[]) {
                    S2 s2=new S2();
                    S2.display ();
                    S1 s1=new S1();
                    System.out.println("Print S1 " + S1.gets());
                    System.out.println("Print S2 " + S2.S2.gets());
            }
    }
  45. Can we have static method in interface?
  46. Can an interface have variables? Can these variables be transient?
  47. Can an interface be final?
  48. Can a class implement two interfaces which has got methods with same name and signatures?
  49. Can a class implement two interfaces with same variable names.
  50. Nested classes can extend only the enclosing class and can not implement any interface? True/False
  51. What are the different types of inner classes. (Read answer).
Answers:
  1. True   
  2. Static Runtime runtime=Runtime.getRuntime();
    long start,end;
    Object obj;
    runtime.gc();
    start=runtime.freememory();
    obj=new object();
    end= Runtime.freememory();
    System.out.println(“sixe of obj”+ (start-end)+ “ bytes”);
    [Note: Since GC can't be enforced in java the result is not always predictable.]
  3. a
  4. b
  5. Array
  6. a. (100,200) b. (700,800)  [Note: Primitive are passed by value in method parameter and objects are passed by value of the reference. In a method if the object values are changed , it will reflect, but if we try to change the reference itself  its original reference /object will not change, as only copy of the reference is changed.
  7. True
  8. d. ALL
  9. c. char (All numeric data types are signed .char is the only  unsigned integer type.)
  10. False. Java doesn't support multi dimension arrays. It supports only nested arrays.
  11. True
  12. True
  13. True
  14. False. GC is a low priority thread.
  15. No
  16. Exception in finalize method doesn't prevent GC.
  17. Resurrection can happen in finalize method which will prevent GC to reclaim the object memory. However this could be done only once. Next time GC will not invoke finalize method before garbage collection.
  18. Yes but only the following version is called by garbage collector:
        protected void finalize() throws Throwable { };
  19. Finalize is not implicitly chained. A finalize method in sub-class  should call finalize in super class explicitly as its last action for  proper functioning . Compilers does not enforce this check.
  20. b float f = 100.00/0.0. Float division by zero returns NAN (not a number) instead of exception.
  21. a
  22. a: 33     b:123
  23. Correct.
  24. a. Compilation error as b=b+10 evaluates to int.
    1. The value of b is 20
    2. Compilation error
    3. Compilation error
    4. The value of f is 1.3
    5. The value of f is 3.0
    6. Compilation error as 6.0/2.0 evaluates to double.
    7. The value of b is 10
    8. The value of b is 10
    9. Compilation error as the value of z is not determined.
    10. The value of i is 0
      The value of first element is 3
      The value of fourth element is 0
    11. -0.0==0.0
  25. Parent
  26. True
  27. True but at most once.
  28. Transient variables are not stored as  objects persistence state .Not serialized for security. Transient variables may not be final  or static . Compilers does not  give any errors as static variables  are anyway not serialized.
  29. Volatile can be applied only  to variables. Not for static or  final. Declaring a variable volatile  indicates that it might  be modified  asynchronously, so that thread will get  correct  value. Used in multi processor environment.
  30. False, Random access file descends from object  and implements data input and data output.
  31. Map doesn't implement collection.
  32. Dictionary is a class not an interface.
  33. Yes.
  34. Yes. Constructor can throw exception.
  35. True
  36. No
  37. No
  38. No
  39. a. Abstract Class    b. Interface
  40. Overriding method can not throw more generic exception than base method.
  41. Compile Time
  42. Yes but variables when overridden shadows the super class variable.
                     Print S1 S1
                     Print S1 S2
                     Print S1 now S1
                     Print S1.gets() now S2
  43. Methods access  variables only in the context  of the class they belong to. If subclass calls super class method, it will access super class variable.
        Display in S1 S1
        Display in S2 S2
        Print S1 S1
        Print S2 S1
  44. All methods in an inter face  are implicitly  public, abstract and never static.
  45. All variables  in an interface  are implicitly static , public and final. They cannot be transient or volatile. A class can shadow the interface  variable with its variable while implementing.
  46. Interface cannot be declared final as they are implicitly abstract.
  47. Yes.
  48. If both the interface have same variable  and the variable is not declared  in implementing class , the compiler will throw ´field ambiguous “ error.
  49. False. Nested class can extend any  class or implement any interface.
  50. An inner class is part of the implementation of its enclosing class (or classes). As such, it has access to the private members of any enclosing class. Top-level nested classes are declared with static keyword. Top level inner classes can be accessed / instantiated without an instance of the outer class. Can access only static members of outer class. Can’t access instance variables or methods of the enclosing class. Non static inner classes which are declared without static keyword can not exist without enclosing class. Can access all the features (even private) of the enclosing outer class. Local classes are defined inside a block (could be a method, a constructor, a local block, a static initializer or an instance initializer). Cannot be specified with static modifier. A class can not have non static inner interface. All inner class except anonymous can be abstract or final.

No comments:

Post a Comment