Sunday, May 6, 2018

General Questions

As per java spring concepts, How will you define a bean for static inner class in xml?

<beans>
   <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"/>
</beans>

Which version of Java introduced annotations?

Java 1.5

What is the difference between parameters and arguments?

Parameters refer to variable types to be passed to a method as described in method definition. Arguments on the other hand are variables that are passed to method while making a method call.

What is Marker Interface in Java?


Marker interface in java is an interface which does not have any method. Marker interface is used to inform the JVM that the classes implementing them will have some special behavior. In java we have following four major marker interfaces:
  1. Searilizable interface
  2. Cloneable interface.
  3. Remote interface
  4. Thread Safe interface
What is difference between Association , Aggregation and Composition?
    Association is relation between two separate classes which establishes through their Objects. Association can be one-to-one, one-to-many, many-to-one, many-to-many.

    Aggreation is a special form of Association where:
    • It represents Has-A relationship.
    • It is a unidirectional association i.e. a one way relationship. For example, department can have students but vice versa is not possible and thus unidirectional in nature.
    • In Aggregation, both the entries can survive individually which means ending one entity will not effect the other entity.
    • Without existing container object, if there is a chance of existing the contained object, then objects are weekly associated and this week association is called as aggregation
    Composition is a restricted form of Aggregation in which two entities are highly dependent on each other.
    • It represents part-of relationship.
    • In composition, both the entities are dependent on each other.
    • When there is a composition between two entities, the composed object cannot exist without the other entity.
    • Without existing container object, if there is no chance of existing contained object, then container and contained objects are strongly associated and this strong association is known as composition.
    Demonstrate Identity Hash Map ?

      import java.util.HashMap;   
      import java.util.IdentityHashMap;   
      import java.util.Map;  
      public class IdentityMapDemo   
      {  
        public static void main(String[] args)   
        {   
          Map identityMap = new IdentityHashMap();   
          Map hashMap = new HashMap();   
          identityMap.put("a", 1);   
          identityMap.put(new String("a"), 2);   
          identityMap.put("a", 3);  
          hashMap.put("a", 1);   
          hashMap.put(new String("a"), 2);   
          hashMap.put("a", 3);  
          System.out.println("Identity Map KeySet Size :: " + identityMap.keySet().size());   
          System.out.println("Hash Map KeySet Size :: " + hashMap.keySet().size());   
        }   
      }
    

    Here the output is as follows
    Identity Map KeySet Size :: 2
    Hash Map KeySet Size :: 1

    The Keysize of Identity Map is 2 because here a and new String(“a”) are considered two different Object. The comparison is done using == operator.
    For HashMap the keySize is 1 because K1.equals(K2) returns true for all three Keys and hence it keep on removing the old value and updating it with the new one.
    What is WeakHashMap?

    A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed.

    What is a weak reference , soft reference and phantom reference?


    Soft reference objects are cleared at the discretion of the garbage collector in response to memory demand. Soft references are most often used to implement memory-sensitive caches. All soft references to softly reachable objects are guaranteed to have been cleared before the virtual machine throws an OutOfMemoryError.
    Objects with SoftReference are collected when JVM absolutely needs memory.
    SoftReference looks perfect for implementing caches, so when JVM needs memory it removes object which have only SoftReference pointing towards them.

    Weak reference objects do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings. WeakReference is great for storing meta data e.g. storing ClassLoader reference. If no class is loaded then no point in keeping reference of ClassLoader, a WeakReference makes ClassLoader eligible for Garbage collection as soon as last strong reference removed.


    Phantom reference is third kind of reference type available in java.lang.ref package. Phantom reference is represented by java.lang.ref.PhantomReference class. Object which only has Phantom reference pointing them can be collected whenever Garbage Collector likes it.

    What is the difference between Collection and Collections?

    Collection is a root level interface of the Java Collection Framework. Most of the classes in Java Collection Framework inherit from this interface. ListSet and Queue are main sub interfaces of this interface.

    Collections is an utility class in java.util package. It consists of only static methods which are used to operate on objects of type Collection. For example, it has the method to find the maximum element in a collection, it has the method to sort the collection, it has the method to search for a particular element in a collection.

    What is the difference between serial and parallel garbage collector?

    The serial collector is the simplest one,it’s mainly designed for single-threaded environments (e.g. 32 bit or Windows) and for small heaps. This collector freezes all application threads whenever it’s working, which disqualifies it for all intents and purposes from being used in a server environment.


    Parallel collector is the JVM’s default collector. Much like its name, its biggest advantage is that is uses multiple threads to scan through and compact the heap. The downside to the parallel collector is that it will stop application threads when performing either a minor or full GC collection. The parallel collector is best suited for apps that can tolerate application pauses and are trying to optimize for lower CPU overhead caused by the collector.

    What is the difference between Sync Method and Sync block?

    Synchronized methods enables a simple strategy for preventing the thread interference and memory consistency errors. If a Object is visible to more than one threads, all reads or writes to that Object’s fields are done through the synchronized method.

    If we only need to execute some subsequent lines of code not all lines (instructions) of code within a method, then we should synchronize only block of the code within which required instructions are exists.

    What is JVM?

    JVM is a virtual machine that enables the computer to run the Java Program. JVM acts like a run time engine which calls the main method present in the Java Code. JVM is the specification which must be implemented in the computer system.The Java code is compiled by JVM to be a byte code which is machine independent and close to the native code.

    What is the difference between JDK,JRE and JVM?

    JVM is an acronym for Java Virtual Machine it is an abstract machine which provides run time environment in which Java byte code can be executed.

    JRE stands for Java Runtime Environment.It is the implementation of JVM. JRE is a set of software tools which are used for developing Java Applications.It is used to provide the run-time environment. 

    JDK stands for Java Development Kit.It is a software Development Environment which is used to develop Java Applications and applets.It contains JRE+ development tools.
    What is JIT compiler?

    It is used to improve the performance. JIT compiles parts of the byte code that have similer functionality at the same time, and hence reduces the amount of time needed for compilation.

    Is empty Java File name a valid source file Name?


    Yes Java allows to save our Java file by ".java" only.We need to compile it by "javac .java" and run by "java classname".

    What is a classloader?

    Classloader is a subsystem of JVM which is used to load class files.Whenever we run the java program, it is loaded first by the class loader. Three built in class loaders are
    1. Bootstrap Class Loader : This is the first class loader which is the superclass of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition.
    2. Extension Class Loader : This is the child class loader of Bootstrap and parent class loader of System Class loader.It loads the jar files located inside JAVA_HOME /jre/lib/ext directory.
    3. System/Application Class Loader: This is the child class loader of Extension class loader.It loads the class files from the class path. By default the class path is set to the curent directory.You can change the classpath using "-cp" or "-classpath" switch.
    What are the various access specifiers in Java?

    Public
    The classes, methods or variables which are defined as public, can be accessed by any class or method.

    Protected
    Protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.

    Default
    Default are accessible within the package only.By default all the classes,methods and variables are of default scope.

    Private
    The private class,methods,or variables can be accessed within the class only.

    What is the purpose of static methods and variables?
    1. These variables are shared by all the objects of the class.
    2. The static is a part of the class and not of the object.
    3. These are stored in class area and we do not need to create an object to access such variables.
    What is the output of following?

       public void function1()  
       {  
         System.out.println(10+20+"java implant");  
         System.out.println("java implant"+10+20);  
       }  
    

    Ans:
    30java implant
    java implant1020

    This is because addition operator is executed from left to right so in first case 10,20 is treated as integer but in latter case they are converted as String as String has higher precedence.

    What is the output of following?
      
       public void function2()  
       {  
         System.out.println(10*20+"java implant");  
         System.out.println("java implant"+10*20);  
       }  
    

    Ans:
    200java implant

    java implant200
    (Because multiplication has higher precedence over addition so numbers will be multiplied first)

    What is difference between object oriented programming language and object based programming language?

    Ans:

    1. Object-oriented languages follow all the concepts of oops where as object based language do not follow all the concept of oops like inheritance and polymorphism.

    2. Object-oriented languages do not have the inbuilt objects where as object based languages have inbuilt objects like Javascript has "Window" object.

    3. Examples of object oriented programming are Java,C#,Smalltalk
    Examples of object based languages are Java Script,VB Script etc.

    How many types of constructor are used in Java?

    Ans:

    1. Default Constructor : Default Constructor is the one which does not accept any value.It is used to initialize instance variables with default values.

    2. Parametrized Constructor : It is used to initialize instance variables with given values. These constructors accept arguments.

    Does constructor return any value? If no why?

    Ans:
    Yes, the constructor implicitly returns the current instance of the class.Explicitly you can't return any values.

    Why is constructor not inherited?

    Ans:
    Inheritance allows composition of one object into another object.Now if constructor is also inherited then the object will also be instantiated in the same manner as another object(of parent class) which is not inheritance used for.

    Also if constructors are inherited then where will we initialize the data members of subclass if the parent class is precompiled.

    Can a constructor be made final,static or abstract? Why? Why not?

    Ans:
    No, a constructor can't be made final explicitly since it is implicitly final as it is not inherited.

    Since a constructor is automatically invoked when an object of the class is created so having them as static will bar them from this functionality.

    Since a constructor cannot be implemented by a child class there is no reason of having them abstract.

    What is the output of?


     public class Prog {  
       Prog(int a,int b)  
       {  
         System.out.println("Int Int :");  
         System.out.println("a="+a+"b="+b);  
       }  
       Prog(int a,float b)  
       {  
         System.out.println("Int Float :");  
         System.out.println("a="+a+"b="+b);  
       }  
       public static void main(String args[])   
       {  
         byte a=10;  
         byte b=15;  
         Prog p1=new Prog(a,b);  
       }  
     }  
    
    Ans : Here both the variables will be promoted to int, and the first parameterized constructor with two integer parameters will be called.

    This is because arithmetic operator works with 16 bit variables to make up a 32 bit expression.

    Output of following Java Program?
     class Test  
     {  
       int i;  
     }  
     public class Main {  
       public static void main(String argsp[])  
       {  
         Test test=new Test();  
         System.out.println(test.i);  
       }  
     }  
    

    Ans
    0
    The output of the program is 0 because the variable i is initialized to 0 internally.As we know that a default constructor is invoked implicitly if there is no constructor in the class, the variable i is initialized to 0 since there is no constructor in the class.

    What is the output of the following Java Program?
     public class Test1   
     {  
       int test_a,test_b;  
       Test1(int a,int b)  
       {  
         test_a=a;  
         test_b=b;  
       }  
       public static void main(String args[])  
       {  
         Test1 test=new Test1();  
         System.out.println(test.test_a+" "+test.test_b);  
       }  
     }  

    Ans:
    Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - constructor Test1 in class Test1 cannot be applied to given types;
      required: int,int
      found: no arguments

    As we see there is a compiler error in the program because there is call to the default constructor in the main method which is not present in the class.

    However, there is only one parameterized constructor in the class Test. Therefore no default constructor is invoked by the constructor implicitly.

    What is a static variable and Method?

    A static variable is used to refer to the common property of all objects.Example in a class for area of circles and spheres "PIE" can be a static variable.

    Static Variable gets memory at the time of class loading since it belongs to the class.Static variable makes a program more memory efficient.

    A static method like variable belongs to the class rather than the object.A static method can access and change the value of the static variable.

    What are the restrictions on static methods?

    A static method cannot use non static data member or call the non static method directly.

    This and Super cannot be used in static context as they refer to objects of current and inherited class.

    We cannot override static methods.

    No comments:

    Post a Comment