Monday 20 May 2013

Core Java Basic Interview Questions Part-1 !



Interview Questions


1. Question: - What is the difference between a static variable, an instance variable and a local variable?

     Answer: - Static Variables V/S Instance Variables V/S Local Variables
  • Class variables are known as static variables. There is only one occurrence of a class variable per JVM per class loader. It means that only one copy of the variables shared with the all instances of the class. When a class is loaded the static variables gets initialized. Instance variables across different objects can have different values. As we know that Instance and Static variables are associated with the objects and the reason they live in the Heap.

  •  An instance variable refers to an instance of a class. Non-Static variables are known as Instance variables and there is one occurrence of an instance variable in each class instance/object.  It means each instance of the class has a separate copy or we can say that every object has its own copy of the instance variables. It is also known as a member variable or a field. Static/Class variables across different objects can have only one value. Instance variables can be used by all the available methods of a class unless the methods are marked with "static" modifier. Instance variables scope depends on their enclosing objects and it can’t live independently. These variables are declared in a class but outside a constructor, method or any code block. When space is assigned for an object in the heap then a slot for every instance variable is created. These variables have default values.

  •  Local Variables: - As Stack variables live on the stack so they are also known as stack variables. Local variables have a narrower scope than others like instance variables or class variables. The lifetime of a local variable is determined by execution path. Initialization of Stack variables or Local variables is always done by the developer.

2. Question: - What is the use of private constructor?

    Answer: - If we want to prevent from sub classing and if we don’t want other classes to instantiate the object. The instantiation is done by a public static factory method within the same class.

Use of private constructor:-

  • It can be used in the factory method design pattern. i.e. java.util.Collections class

  • It can also be used to follow a singleton design pattern.

  • It can be used in utility classes i.e. StringUtils.

3. Question: - What is the use of static methods?

Answer: - Static methods are useful for Creating Singleton classes, factory methods and utility classes. The best example of utility classes is java.util.Collections and java.lang.Math classes.

4. Question:- What is Static and Dynamic Class Loading?

Answer:-


Static V/S Dynamic Class loading

Static Class Loading: Creation of objects and instance using new keyword is known as static class loading. It means static class loading is done through the new operator. In Static Class Loading,  retrieval of class definition and instantiation of the object is completed during compilation time.

Dynamic Class Loading: Class.forName () method  is used to load classes in case of Dynamic Class Loading. Dynamic class loading is used when the name of the class is not known at compile time. Dynamic loading of a class is a technique for programmatically invoking the functions of a class loader at run time using available below methods
                       
                        Class.forName(String)
                        ClassLoader.findSystemClass(String)
                        ClassLoader.loadClass(String)

Dynamic class loading is achieved through reflection.This is done with the help of the following methods:-
                         
                        getClass();
                        getName();
                        getDeclaredFields();



Example of Static Class Loading:-

package com.gaurav.dynamicclassloading;


public class StaticLoadingDemoTest {
            public String readValue(String value){
                        return "readValue() Method called and the parameter value is : "+value;
            }
            public static void main(String args[]){
                        StaticLoadingDemoTest sldt = new StaticLoadingDemoTest();
                        System.out.println(sldt.readValue("GAURAV"));
            }
}



Example of Dynamic Class Loading:-


package com.gaurav.dynamicclassloading;


class TestClassForDynamicLoading {

            public String display(String strValue) {
                        System.out
                                                .println("Inside display method and the parameter value is : "
                                                                        + strValue);
                        return TestClassForDynamicLoading.class.getName();
            }
}

public class DynamicLoadingDemoTest {
            @SuppressWarnings("rawtypes")
            public static void main(String[] args) throws InstantiationException, IllegalAccessException {

                        ClassLoader classLoader = DynamicLoadingDemoTest.class.getClassLoader();
                       
                        try {
                                    Class loadedClass = classLoader
                                                            .loadClass("com.gaurav.dynamicclassloading.TestClassForDynamicLoading");
                                    System.out.println("Getting the simple name of the loadedClass  = "
                                                            + loadedClass.getSimpleName());
                                    System.out
                                                            .println("Getting the fully qualified name of the loadedClass  = "
                                                                                    + loadedClass.getName());
                                    System.out
                                                            .println("Getting the fully qualified name of the loadedClass Using getCanonicalName()  = "
                                                                                    + loadedClass.getCanonicalName());
                                   
                                   
                                    System.out.println("********************************************************");
                                    String className = "com.gaurav.dynamicclassloading.TestClassForDynamicLoading";
                                    Class loadedClass1 = Class.forName(className);
                                    System.out.println("Getting the simple name of the loadedClass  = "
                                                            + loadedClass1.getSimpleName());
                                    System.out
                                                            .println("Getting the fully qualified name of the loadedClass  = "
                                                                                    + loadedClass1.getName());
                                   
                                    TestClassForDynamicLoading tcdl = (TestClassForDynamicLoading) Class.forName(className).newInstance();
                                    tcdl.display("KUMAR GAURAV");
                                   
                                    Class classLoad = DynamicLoadingDemoTest.class;
                                    System.out.println("Name of the loaded class -"+classLoad.getName());
                                   
                        } catch (ClassNotFoundException e) {
                                    e.printStackTrace();
                        }
            }
}

 5. Question:-What is the difference between NoClassDefFoundError and ClassNotFoundException?

 Answer:- Difference between NoClassDefFoundError and ClassNotFoundException

1) ClassNotFoundException This Exception is thrown when our application will try to load a class through the passed string name by using below methods and requested class is not available at Runtime. ClassNotFoundException is thrown when that required class is not present in the location where classloader is searching.
Below are the methods which is generally generating the ClassNotFoundException:-
             
            findSystemClass() method of ClassLoader class.
loadClass() method of ClassLoader class.
forName() method of Class class.


NoClassDefFoundError will be thrown when a class has been compiled with a specific class available in a jar in the class path but then that class is no longer available during run time(missing that jar in the class path during execution). Missing JAR files are the most common reason for this error. Below are the reasons for getting that error :-
             
            Specified class is not in the classpath
Specified class is not visible to the classloader.
Specified class does not exist.

2) ClassNotFoundException is a checked Exception derived directly from java.lang.Exception class means when we write our code like "Class.forName("oracle.driver.Driver")",then we should must provide try-catch block or we should use throws keyword otherwise code will throw compilation error where as NoClassDefFoundError is an Error derived from LinkageError.


Example to generate ClassNotFoundException:-

ClassNotFoundExceptionTest.java

package com.gaurav.dynamicclassloading;

class TestClassForClassNotFoundException {

            public String displayValues(String strValue) {
                        System.out
                                                .println("Inside display method and the parameter value is : "
                                                                        + strValue);
                        return TestClassForClassNotFoundException.class.getName();
            }
}

public class ClassNotFoundExceptionTest {
            @SuppressWarnings({ "rawtypes", "unused" })
            public static void main(String args[]) {

                        ClassLoader classLoader = ClassNotFoundExceptionTest.class
                                                .getClassLoader();

                        try {
                                    Class loadedClass = classLoader
                                                            .loadClass("TestClassForClassNotFoundException");

                        } catch (ClassNotFoundException e) {
                                    e.printStackTrace();
                        }
            }
}

Result:-

java.lang.ClassNotFoundException: TestClassForClassNotFoundException
            at java.net.URLClassLoader$1.run(Unknown Source)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.net.URLClassLoader.findClass(Unknown Source)
            at java.lang.ClassLoader.loadClass(Unknown Source)
            at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
            at java.lang.ClassLoader.loadClass(Unknown Source)
            at com.gaurav.dynamicclassloading.ClassNotFoundExceptionTest.main(ClassNotFoundExceptionTest.java:22)

Example for Generating NoClassDefFoundError:-


Steps for how to get NoClassDefFoundError :
  •      Develop the below program.
  •      Compile it and execute. It will execute. It will work fine and we will get output.
  •      Set the jdk path upto bin directory in the current location.
  •      Now Delete the inner class NoClassDefFoundErrorTest$InnerClass.
  •      Run the program again. We will find NoClassDefFoundError. Below I have attached the screenshot.
public class NoClassDefFoundErrorTest {
           
            class InnerClass{
                        public void getGreeting(){
                                    System.out.println("Welcome in India");
                        }
            }
            public static void main(String args[]){
                        System.out.println("Inside main()");
                        NoClassDefFoundErrorTest nc = new NoClassDefFoundErrorTest();
                        NoClassDefFoundErrorTest.InnerClass ic = nc.new InnerClass();
                        ic.getGreeting();
            }
}
  
Result:-


No comments:

Post a Comment