Saturday 29 August 2015

Java interview questions and answers of Bureau Veritas Consumer Product Services-IT

Bureau Veritas Consumer Product Services-IT
Core Java
Q1. What will be the output of above program ?
packageswain.javainterviewhub.blogspot.in;

public class JavaInterviewHub {

       public static final int A = 5;
       public static final int B;
       static {
              if (A == 5) {
                     B = 10;
              } else {
                     B = 5;
              }
              System.out.println("A=" + JavaInterviewHub.A + ", B="
                           + JavaInterviewHub.B);
       }

       public JavaInterviewHub() {
              System.out.println("C=" + JavaInterviewHub.A + ", D="
                           + JavaInterviewHub.B);
       }

       public static void main(String[] args) {
              new JavaInterviewHub();
       }

}
Please select  the  correct  answer.
A)     A=5,  B=10
C=5,   B=10
B)      C=5, D=10
C)      Exception related to variable B’s initialization
D)     A=5, B=10
Q2. A ClassNotFoundException is thrown when
A)     If a class is referenced with Java’s  “new” operator but the runtime system cannot find the referenced class.
B)      An application tries to load in a class through its string name using “Class.forName()” method.
C)      An application tries to load in a class using static loading.
D)     An application tries to load in a class using dynamic loading.

Q3. Time required in best case for search operation in binary search tree is
A)     O(n)
B)      O(log n)
C)      O(2n)
D)     O(log 2n)




Q4. In the following list which class does not override the equals() and hashCode() methods and inheriting them directly from class Object ?
A)     Java.lang.String
B)      Java.lang.Double
C)      Java.lang.StringBuffer
D)     Java.lang.Character

Q5. Given
packageswain.javainterviewhub.blogspot.in;

public class JavaInterviewHub {

       private static String s = "-";

       public static void main(String[] args) {
              try {
                     throw new Exception();
              } catch (Exception e) {
                     try {
                           try {
                                  throw new Exception();
                           } catch (Exception ex) {
                                  s += "ic ";
                           }
                           throw new Exception();
                     } catch (Exception x) {
                           s += "mc ";
                     } finally {
                           s += "mf ";
                     }

              } finally {
                     s += "of ";
              }
              System.out.println(s);
       }

}

What is the result ?
A)     –ic of
B)      –mf of
C)      –mc mf
D)     –ic mf of
E)      –ic mc mf of
F)      –ic mc of mf
G)     Compilation fails
Q6.  Given
packageswain.javainterviewhub.blogspot.in;

public class Parent {

}
public class Child extends Parent {
      
}
Please select  the correct  answer .(Choose all that apply.)
A) List<Parent> myList1 = newArrayList<Parent>();
B) List<Parent> myList2 = new ArrayList<Child>();
C) List<Child> myList3 = newArrayList<Child>();
D) List<Child> myList4 = newArrayList<Parent>();
Q7. Given
packageswain.javainterviewhub.blogspot.in;

class Chicks{
       synchronized void yack(long id){
              for(int x=1;x<3;x++){
                     System.out.println(id+" ");
                     Thread.yield();
              }
       }
}

public class JavaInterviewHub implements Runnable {

       Chicks c;
      
      
       public static void main(String[] args) {
              newJavaInterviewHub().go();
       }
      
       void go(){
              c=new Chicks();
              new Thread(newJavaInterviewHub()).start();
              new Thread(newJavaInterviewHub()).start();
       }

       @Override
       public void run() {
              c.yack(Thread.currentThread().getId());
       }

}
Which are true ?(Choose all that apply.)
A)Compilation fails
B)The output could be 4 4 2 3
C)The output could be 4 4 2 2
D)The output could be 4 4 4 2
E)The output could be 2 2 4 4
F) An Exception is thrown at runtime
Q8. ___________  can be used to control the order of certain data structures and collection of objects too.
A)     Serial Comparators
B)      Natural Comparators
C)      Comparators
D)     All of above
Q9. Given
packageswain.javainterviewhub.blogspot.in;

class Bar {

}

public class JavaInterviewHub {
       Bar doBar() {
              Bar b = new Bar();/* Line 6 */
              return b;/* Line 7 */
       }

       public static void main(String[] args) {
              JavaInterviewHub t = new JavaInterviewHub();/* Line 11 */
              Bar newBar = t.doBar();/* Line 12 */
              System.out.println("newBar");
              newBar = new Bar();/* Line 14 */
              System.out.println("finishing");/* Line 15 */
       }

}

At what point is the Bar object , created on line 6,eligible for garbage collection ?
A)     After line 12
B)      After Line 14
C)      After line 7, When doBar() completes
D)      After line 15, When main() completes
Q10.  What will be the output of the program ?
packageswain.javainterviewhub.blogspot.in;

public class JavaInterviewHub {

       public static void main(String[] args) {
              JavaInterviewHub t = new JavaInterviewHub();
              t.start();

       }

       void start() {
              long[] a1 = { 3, 4, 5 };
              long[] a2 = fix(a1);
              System.out.println(a1[0] + a1[1] + a1[2] + "");
              System.out.println(a2[0] + a2[1] + a2[2] + "");
       }

       long[] fix(long[] a3) {
              a3[1] = 7;
              return a3;
       }

}
Please select the correct answer.
A)12 15
B)15 15
C)3 4 5 3 7 5
D)3 7 5 3 7 5
Q11. What will the program print when compiled and run ?
packageswain.javainterviewhub.blogspot.in;

import java.util.ArrayList;
import java.util.List;

public class JavaInterviewHub {

       public static void main(String[] args) {
              List<Integer> list=newArrayList<Integer>();
              list.add(2007);
              list.add(2008);
              list.add(2009);
              System.out.println("Before: "+list);
              for(int i:list){
                     intindex=list.indexOf(i);
                     list.set(index, ++i);
              }
              System.out.println("After: "+list);

       }

}
Select the one correct answer.
A)
 Before: [2007, 2008, 2009]
 After: [2008, 2009, 2010]
B)
Before: [2007, 2008, 2009]
After: [2010, 2008, 2009]
C)
Before: [2007, 2008, 2009]
After: [2007, 2008, 2009]
D)
Before: [2007, 2008, 2009]
After: [2008, 2009, 2007]
E)Throws CuncurrentModificationException

Q12. What will be the output of the following program ?

packageswain.javainterviewhub.blogspot.in;

import java.util.TreeSet;

class MyNavigableSetextendsTreeSet<String>{
       public boolean add(Object value){
              return super.add(value);
       }
}

public class TestSetProgram {

       public static void main(String[] args) {
              MyNavigableSet objects=new MyNavigableSet();
              objects.add(new Object());
              System.out.println(objects);

       }

}

Please select the correct answer
A)The program will compile and run fine to print the contents of the set.
B)This program will raise run-time exception
C)This program will raise compile-time error
D)None

Q13. Select all the correct statements regading Enums (Select any 2 options)

A)All enums are subclass of interface java.lang.Enum
B)Enums is simply a data structure and hence it is not compiled to a .class file.
C)Enum enable you to define a new data type .For example ,If you create an Enum ‘Days’ you can declare a variable of type ‘Days’.
D)All instances of Enums are serializable by default. 

Spring
Q14. Given the following Spring configuration file , What is the correct answer:
<bean class=”com.spring.service.MyServiceImpl”>
<property name=”repository” ref=”jpaDao”/>
</bean>
<bean class=”com.spring.repository.JpaDao” />
Please  select the correct  answer
A)     The first declared bean MyServiceImpl is missing an id must be named myService
B)      The Second declared bean JpaDao is missing an id must be named jpaDao
C)      Answer A and B are both rights
D)     Answers A and B are both wrong
Q15. How could you externalize constants from a spring configuration file or a spring annotation into a .properties file ? Select one or more answers.
A)     By using the <util.constant/> tag
B)      By declaring the ConstantPlaceholderConfigurer bean post processor
C)      By using the <context:property-placeholder />  tag
D)     By using the c:namespace
Q16. Select one or many correct  answers about spring bean life cycle.
A) The method annoted with @PostConstruct is called after bean instantiation and before properties setting of the bean
B) The  method @PreDestory of a prototype bean is called when the bean is garbase collected
C) The init() method declared in the init-method attribute of a bean is called before the afterPropertiesSet  callback method of the initializingBean interface
D) The method annoted with @PostConstruct is called before the afterPropertiesSetcallback method of the InitializingBean interface
Q17.  Considering 2 classes AccountServiceImpl and ClientServiceImpl . Any of these 2 classes inherits from each other. What is the result of the pointcut expressions ?
Execution(** .. AccountServiceImpl.update(..))
&& execution (**..ClientServiceImpl.update(…))
A)     Matches public update methods of the 2 classes , Whatever the arguments
B)      Matches any update methods of the 2 classes , whatever the arguments and method visibility
C)      Matches any update methods of the 2 classes , with one more arguments and whatever method visibility
D)     No joint point is defined
Q18. What are the 2 correct statements about AOP proxy ?
A)     AOP proxies are created by spring in order to implement the aspect contracts
B)      AOP proxies are always created with a JDK dynamic proxy
C)      Only classes that implements a least one interface  could be proxied
D)     All methods could be proxied
E)      Proxies are created by a BeanPostProcessor
Q19. What is an after returning advice ? Select a unique answer .
A)     Advice to be executed regardless of the means by which a join point exists
B)      Advice that surrounds a method invocation and can perform custom behavior before and after the method invocation
C)      Advice to be executed before method invocation
D)     Advice to be executed after a join  point completes without throwing an exception
Q20. What is a pointcut ? Select a unique answer .
A)     Code to execute at a join point
B)      An expression to identify joinpoints
C)      An advice and a jointpoint
D)     None of the above
Q21. What are the unique correct  answers about Spring AOP support ?
A)     An advice could proxied a constructor’s class
B)      A point cut could select  methods that have a custom annotation
C)      Static initialization code could be targeted by a point cut
D)     Combination of pointcuts by &&, || and the !operators is not supported
Q22. What could not return a Spring MVC controller ? Select a single answer.
A)     An absolute path to the view
B)      A logical view name
C)      A new JstlView
D)     Void
E)      Null value
Q23. What is the easiest method to write a unit test ?
A)     Void displayAccount(HttpServeltRequestreq,HttpServletResponseresp) throws ServletException,IOException
B)      Void displayAccount(HttpServeltRequestreq,HttpSession Session) throws ServletException,IOException
C)       @RequestMapping(“/displayAccount”)
String displayAccount(@RequestParam(“accountId”) int id,Model model)
D)     @RequestMapping(“/displayAccount”)
String displayAccount(@PathVariable(“accountId”) int id,Model model)
IBATIS
Q24. Choose the correct method for selecting the list of result from database with Ibatis.
A)     queryForList(String id) throws SQLException ;
B)      queryForList(String id,Object parameter) throws SQLException;
C)      queryForList(String id, Object parameter,int max) throws SQLException
D)     queryForList(String id, Object parameter,String key,String value) throws SQLException
Q25. Choose the correct method for selecting the map  of result from database with Ibatis.
A)     queryForList(String id) throws SQLException ;
B)      queryForList(String id,Object parameter) throws SQLException;
C)      queryForList(String id, Object parameter,int max) throws SQLException
D)     queryForList(String id, Object parameter,String key,String value) throws SQLException
J2EE
Q26. What is the difference between using getSession(true) and getSession(false) methods ?
A)     getSession(true)  method will check whether there is already a session exists for the user . If a session exists, it returns that session object. If a session does not already exist  then it creates a new session for the user .
getSession(false) method will check whether there is already a session exists for the user . If a session exists ,It returns that session object . If a session does not already exist then it returns null.
B)      getSession(false)  method will check whether there is already a session exists for the user . If a session exists, it returns that session object. If a session does not already exist  then it creates a new session for the user .
getSession(true) method will check whether there is already a session exists for the user . If a session exists ,It returns that session object . If a session does not already exist then it returns null.
C)        Both A and B
D)     None
Q27. If you set a request attribute in your JSP ,would you be able to access it in your subsequent request within your servelet code ?
A)     No
B)      Yes
C)      May be
D)     None
Q28. Which is not the correct  scope value for <jsp:usebean>
A)     Page
B)      Response
C)      Request
D)     Session
Q29.  Which statement/s is/are  true about the dynamic include ?’
A)     During the translation or compilation phase all the included JSP pages are compiled into a single Servlet.
B)      The dynamically included JSP is compiled into a separate Servlet . It is a separate resource , Which gets to process the request , and the content generated by this resource is included in the JSP response .
C)      No run time performance overhead
D)     Has run time performance overhead
JSF
Q30.Which is the controller servlet in the JSF ?
A)     Javax.faces.webapp.FacesServlet
B)      Javax.faces.FacesServlet
C)      Javax.faces.webapp.FacesServlet
D)     Javax.faces.controller.FacesServlet
Q31.  I have a jsf (v 1.2) application . I want to use properties file for test/message in my application .Same time I also want to make sure it runs property even on older version of jsf .Which is the approprits method to choose ?
A)     Include following in every jsp file <f:loadBundlebasename=”message ” var=”msgs” /> and then you can use  these message properties as below :<h:outputTest value=”#(msgs.text)” />
B)      Include following in the faces-config.xml file :<application><resource-bundle><base-name>message</base-name><var>msgs</var></resource-bundle></application>
C)      Both the above :It works perfectly on older versions
D)     None of the above .jsf versions  does not support it
Q32. What is the Managed-bean definition in JSF.

Programming
Q33. What is RequestDispatcher and how many types of RequestDispatcher  we have ? What is the difference between forwarding a request and redirecting a request ? (Please give an example ).
Q34. Please write a program for given collection of 1 million integers ranging from 1 to 9 ,how would you sort them ?
For Example:[2,1,5,1,2,3,4,3,5,6,7,8,5,6,7,0]
Desired Output:[0,1,1,2,2,2,3,3,4,5,5,5,6,6,7,7,8]
Q35.Calculate factorial using recursive method.
For Example N=7;



ANSWER:

Q1:A) 
 Q2:B)
More details:
The difference from the Java API Specifications is as follows.
Thrown when an application tries to load in a class through its string name using:
·         The forName method in class Class.
·         The findSystemClass method in class ClassLoader.
·         The loadClass method in class ClassLoader.
but no definition for the class with the specified name could be found.
Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.
The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.
So, it appears that the NoClassDefFoundError occurs when the source was successfully compiled, but at runtime, the required class files were not found. This may be something that can happen in the distribution or production of JAR files, where not all the required class files were included.
As for ClassNotFoundException, it appears that it may stem from trying to make reflective calls to classes at runtime, but the classes the program is trying to call is does not exist.
The difference between the two is that one is an Error and the other is an Exception. With NoClassDefFoundError is an Error and it arises from the Java Virtual Machine having problems finding a class it expected to find. A program that was expected to work at compile-time can't run because of class files not being found, or is not the same as was produced or encountered at compile-time. This is a pretty critical error, as the program cannot be initiated by the JVM.
On the other hand, the ClassNotFoundException is an Exception, so it is somewhat expected, and is something that is recoverable. Using reflection is can be error-prone (as there is some expectations that things may not go as expected. There is no compile-time check to see that all the required classes exist, so any problems with finding the desired classes will appear at runtime.

Q3:D)
More details:
For a non-self-balancing tree (possible but unusual for a search tree), worst case is O(n), which is for the degenerate binary tree (a linked list).
In this case, you have to search, on average, half the list before finding your desired element.
Best case is O(log2 n) for a perfectly balanced tree, since you cut the search space in half for every tree level.
Average case is somewhere in between those two and depends entirely on the data :-)
Since you rarely get to control the sequence in which data is inserted into a tree, self-balancing trees are usually preferable since, while they add a small amount of time to each insertion or deletion, they greatly speed up searching. Their worst case is so much better than unbalanced trees.
                 8
         _______/ \_______
        /                 \
       4                  12
    __/ \__             __/ \__
   /       \           /       \
  2         6        10        14
 / \       / \       / \       / \
1   3     5   7     9  11    13  15
In this perfectly balanced tree, you can see that you get 2n-1 nodes for every n levels. That means for 15 nodes, you never have to search more than four nodes to find it (e.g., to find 13, you search 81214 and 13). That's where the log2n figure comes from.
A degenerate unbalanced tree, as already stated, is a linked list. If your data arrived in sequence and you inserted it into an unbalanced binary tree, you'd get:
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -+
                                           |
+------------------------------------------+
|
+-> 10 -> 11 -> 12 -> 13 -> 14 -> 15
To find 13 in that case, you'd need to search 123456789101112and 13, hence O(n).

 Q4:C)
More details:
Because StringBuffer is mutable, and its primary use is for constructing strings. If you want to compare content, call StringBuffer#toString() and compare the returned value.
It is not generally useful to override hashCode() for mutable objects, since modifying such an object that is used as a key in a HashMap could cause the stored value to be "lost."

Q5: E)
Q6:A) and C)
Q7:F)

Console:
 Exception in thread "Thread-0" Exception in thread "Thread-1" java.lang.NullPointerException
        at swain.javainterviewhub.blogspot.in.JavaInterviewHub.run(JavaInterviewHub.java:28)
        at java.lang.Thread.run(Unknown Source)
    java.lang.NullPointerException
        at swain.javainterviewhub.blogspot.in.JavaInterviewHub.run(JavaInterviewHub.java:28)
        at java.lang.Thread.run(Unknown Source)


More details:
ince Chicks.yack() is synchronized, you probably meant for both threads to use the same instance of Chicks, which means you probably meant for both threads to use the same instance of JavaInterviewHub, in which case you probably meant to start both threads with the instance that was created in main().
If that's all true, then you need to use this when creating the threads:
void go(){
    c=new Chicks();
    new Thread(this).start();
    new Thread(this).start();
}


As for the question of when to create an instance of Chicks, and therefore assign a value to c, you have 3 choices:
1.    Leave the code as-is. A bit obscure, but valid.
2.    Do it in a constructor.
3.    Do it when declaring cEasiest.
Option 2: Constructor
private JavaInterviewHub() {
    this.c = new Chicks();
}
Option 3: Declaration
private final Chicks c = new Chicks();
Q8:C)
Q9:A)
Q10:B)
Q11:B)
Q12:C)
Q13:C) and D)
Q14.B)
More detail
Those beans are anonymous because no id is supplied explicitly. Thus Spring container generates a unique id for that bean. It uses the fully qualified class name and appends a number to them. However, if you want to refer to that bean by name, through the use of the ref element you must provide a name (see Naming Beans section of the Spring reference manual). To be correct, the 2 nd bean has to declare a jpaDao id attribute in order to be reference by the repository property of the first bean.
Q15.C)
Q16. C)
Q17.D)
Poincut expression could not satisfied both first and second execution point. Do not confuse the &&
operator and || operator.
Q18.A) and E)
Q19.D)
Q20.B)
Q21.B)
Q22.A)
Q23.C)
Q24.B)
Q25.B)
Q26.A)
Q27.B)
Q28.B)
Q29.B)
Q30. C)
Q31.B)

Q32. Using XML Configuration

<managed-bean>
  <managed-bean-name>helloWorld</managed-bean-name>
  <managed-bean-class>com.tutorialspoint.test.HelloWorld</managed-bean-class>
  <managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<managed-bean>
  <managed-bean-name>message</managed-bean-name>
  <managed-bean-class>com.tutorialspoint.test.Message</managed-bean-class>
  <managed-bean-scope>request</managed-bean-scope>
</managed-bean>
Using Annotation
@ManagedBean(name = "helloWorld", eager = true)
@RequestScoped
public class HelloWorld {
        
   @ManagedProperty(value="#{message}")
   private Message message;
   ...
}
@ManagedBean Annotation
@ManagedBean marks a bean to be a managed bean with the name specified in nameattribute. If the name attribute is not specified, then the managed bean name will default to class name portion of the fully qualified class name. In our case it would be helloWorld.
Another important attribute is eager. If eager="true" then managed bean is created before it is requested for the first time otherwise "lazy" initialization is used in which bean will be created only when it is requested.
Q33.
RequestDispatcher is an interface, implementation of which defines an object which can dispatch request to any resources(such as HTML, Image, JSP, Servlet) on the server.

Methods of RequestDispatcher

RequestDispatcher interface provides two important methods
Methods
Description
voidforward(ServletRequest request, ServletResponse response)
forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server
voidinclude(ServletRequest request, ServletResponse response)
includes the content of a resource (servlet, JSP page, HTML file) in the response

requestDispatcher - forward() method

1.    When we use forward method, request is transfer to other resource within the same server for further processing.
2.    In case of forward, web container handle all process internally and client or browser is not involved.
3.    When forward is called on requestdispatcher object we pass request and response objects so our old request object is present on new resource which is going to process our request.
4.    Visually we are not able to see the forwarded address, it is transparent.
5.    Using forward () method is faster then send redirect.
6.    When we redirect using forward and we want to use same data in new resource we can use request.setAttribute () as we have request object available.

SendRediret

1.    In case of sendRedirect, request is transfer to another resource to different domain or different server for further processing.
2.    When you use sendRedirect, container transfers the request to client or browser so URL given inside the sendRedirect method is visible as a new request to the client.
3.    In case of sendRedirect call, old request and response objects are lost because it’s treated as new request by the browser.
4.    In address bar, we are able to see the new redirected address. It’s not transparent.
5.    sendRedirect is slower because one extra round trip is required, because completely new request is created and old request object is lost. Two browser request required.
6.    But in sendRedirect, if we want to use we have to store the data in session or pass along with the URL.

Which one is good?

Its depends upon the scenario that which method is more useful.
If you want control is transfer to new server or context and it is treated as completely new task then we go for Send Redirect. Generally, forward should be used if the operation can be safely repeated upon a browser reload of the web page will not affect the result

Q34.
public class BucketSort {
    public int[] sort(int[] array, int min, int max) {
        int range = max - min + 1;
        int[] result = new int[range];
        for (int i: array) {
            result[i]++;
        }
        return result;
    }
}

public class BucketSortTest {@
    Test
    public void testBucketSortFor1To9() {
        int[] array = {
            2, 1, 5, 1, 2, 3, 4, 3, 5, 6, 7, 8, 5, 6, 7, 0
        };
        int[] sort = new BucketSort().sort(array, 0, 8);

        for (int i = 0; i & lt; sort.length; i++) {
            for (int j = 0; j & lt; sort[i]; j++) {
                System.out.println(i);
            }
        }
    }
}

Program output : 0,1,1,2,2,3,3,4,5,5,5,6,6,7,7,8

Q35.
Given below is a program which calculates the factorial of 7 using recursion. 

public class Factorial {

   public static void main(String[] args) {
       int n = 7;
       int result = factorial(n);
       System.out.println("The factorial of 7 is " + result);
   }

   public static int factorial(int n) {
       if (n == 0) {
           return 1;
       } else {
           return n * factorial(n - 1);
       }
   }
}

No comments:

Post a Comment