Tuesday, 9 August 2016

Java basics interview questions

  1. What are JVM, JRE and JDK?

    JVM

    JVM meaning Java Virtual Machine is an abstract layer between a Java program and the platform that Java Program is running on.
    JVM is platform dependent and different implementations of JVMs are available for specific platforms.

    JRE

    JRE meaning Java Runtime Environment provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language.

    JDK

    JDK meaning Java Development Kit is a superset of the JRE, and contains everything that is in the JRE, plus development tools such as the compilers and debuggers necessary for developing applets and applications.

    Read more about JVM, JRE and JDK here

  2. What is bytecode in Java or Why java is called platform independent?

    Java programs are both compiled and interpreted which means -
    When we do javac javaprogram, the java source code is compiled into a .class file which is actually a bytecode. The generated bytecode is portable and it's format is same across platforms.
    After compilation, the interpreter reads the generated byte code & transforms it according to the native platform.
    The compiled bytecode doesn't run on CPU directly, JVM sits in between and interpret the bytecode into readable machine language for the CPU. So Java program is platform independent but JVM is platform dependent and different implementations of JVMs are available for specific platforms.


  3. Java is pass by value or pass by reference?

    Java is pass by value for both primitive types as well as for objects.

    Read more about Java pass by value or pass by reference here

  4. What is package in Java?

    A package is a namespace that organizes a set of related classes and interfaces. Packages also help in  preventing naming conflicts.
    Packages also provide visibility control mechanism. You can define classes and class members inside a package that are not visible to the classes in other packages.

    Read more about Package in Java here

  5. What are access modifiers in Java?

    Access level modifiers are used to control the visibility of the class or the members of the class i.e. fields and methods.
    Types of Access Modifiers

    • private - private modifier specifies that the member can only be accessed in its own class.
    • default (or package-private) - If no specifier is used (which is known as default access) member is visible only within its own package.
    • protected - protected modifier specifies that the member can only be accessed within its own package and by a subclass of its class in another package.
    • public - public modifier specifies that member is visible to all classes everywhere.

    Read more about Access Modifiers here

  6. What all access modifiers can be used with a class?

    At the class level only two of the modifiers can be used, public or default.
    If a class is declared with the modifier public, that class is visible to all classes everywhere.
    If a class has no modifier (the default), it is visible only within its own package.

    Read more about Access Modifiers here

  7. What all access modifiers can be used with class fields?

    All the four types of access modifiers - public, protected, default, private can be used with variables declared in the class.

    • If a field is declared as public then it is visible to all classes in the same package or other packages.
    • If a fields is declared with no access specifier (default) then it can be accessed by any class in the same package.
    • If a field is defined as protected then it is accessible to any class in the same package or to any subclass (of the class where field is declared) in different package.
    • If a field is defined private then that field can only be accessed in its own class.


  8. What all access modifiers can be used with class methods?

    All the four types of access modifiers - public, protected, default, private can be used with methods of the class and access modifier for the methods work the same way as for the fields.


  9. What all access modifiers can be used with constructors?

    All the four types of access modifiers - public, protected, default, private can be used with constructors of the class.

    • In case constructor of the class is private then the object of that class can be created by that class only.
    • In case constructor is marked as protected then a subclass in different package can access the protected constructor.
    • If a constructor is declared with no access specifier (default) then it can be accessed by any class in the same package.
    • If a constructor is declared as public then it is visible to all classes in the same package or other packages.


  10. What is automatic numeric promotion in Java?

    In Java numeric promotion happens in case of primitive types when those primitives are used in an expression.
    As exp.

    byte a = 100;
    byte b = 50;
    int i = a * b;
    
    In the above code a * b will exceed the range of its byte operand (range of byte is -128 to 127). In these types of situations Java will automatically promote the byte, short or char to int when evaluating an expression.

    Read more about automatic numeric promotion here

  11. What is constructor?

    In Java there is a special method provided to initialize objects when they are created. This special method which is used for automatic initialization is called Constructor.
    Constructor has the same name as the class in which it is created and defined just like a method, that is, constructor's syntax is similar to a method

    Read more about constructor here.

  12. What is default constructor in Java?

    When a constructor is not explicitly defined for a class, then Java creates a default no-arg constructor for a class that is called default constructor.

    Read more about constructor here.

  13. What is Parameterized Constructor in Java?

    If we want our object's fields to be initialized with specific values, we can do it by adding parameters to the constructor.

    Read more about constructor here.

  14. What is constructor chaining in Java?

    In case when we have a hierarchy of classes (inheritance) the constructors of the classes are invoked in an order. That order is known as constructor chaining.
    For Exp - If class A is super-class and there is Class B which is subclass of A. In that case if a new instance of class B is created, order in which constructors of Class A and Class B are executed is from super-class to subclass.

    Read more about constructor chaining here.

  15. What is constructor overloading in Java?

    Like method overloading there is also an option to have multiple constructors within the same class where the constructors differ in number and/or types of parameters, that process is known as Constructor overloading.

    Read more about constructor overloading here.

  16. Are constructors from the super class inherited in the sub-class?

    No constructors are not inherited in Java.


  17. What is this in java?

    this in java is a reference to the current object on which the method or constructor was invoked. this can be used inside any method or constructor to refer to the current object.

    Read more about this here

  18. What is super in java?

    The super keyword in java is essentially a reference variable that can be used to refer to its immediate parent class.
    Usage of super -

    • Invoke the constructor of the super class.
    • Accessing the variables and methods of parent class.

    Read more about super here

  19. What is interface in Java?

    Interfaces help in achieving full abstraction in Java, as using interface, you can specify what a class should do, but how class does it is not specified.
    Interfaces look syntactically similar to classes, but they differ in many ways -

    • Interfaces don't have instance variables.
    • In interfaces methods are declared with out any body. They end with a semicolon.
    • Interface can't be instantiated.
    • Interfaces don't have constructors.
    • An interface is implemented by a class not extended.
    • An interface can extend multiple interfaces.

    Read more about interfaces here.

  20. Can an Interface be final?

    No, interface can't be final. The whole idea of having an interface is to inherit it and implement it. Having it as final means it can't be subclassed.

    Read more about interfaces here.

  21. Is it possible to declare an interface method static?

    Not before Java 8, from Java 8 it is possible to have interface static methods.

    Read more about interface here and interface static method here.

  22. What are interface default/defender methods?

    With the release of Java 8, it is now possible to add default method in interfaces. With the addition of default method to an interface, addition of new method, to even an interface will not break the pre-existing code.
    An interface default method is defined the same way a method will be defined in a class. One difference is that in interface default method is preceded by the keyword default
    As Exp.

    public interface MyInterface {
     int method1();
     // default method, providing default implementation
     default String displayGreeting(){
      return "Hello from MyInterface";
     }
    }
    

    Read more about interface default method here.

  23. Can an Interface implement another Interface?

    No, an interface can't implement another interface. Though, interface can extend another interface.

    Read more about extending interface here.

  24. Can an Interface extend another Interface?

    Yes,interface can extend another interface.

    Read more about extending interface here.

  25. Is it possible to have final method in an interface?

    No, whole idea of interface is to have abstract methods for which implementation is provided by the implementing classes. Making a method as final in interface will mean it can't be overridden which will mean implementing class can't provide an implementation for that mthod.

    Read more about interfaces here.

  26. Is it possible to define a class inside an interface?

    Yes.An interface can have an inner class. That class will be accessed by using interfaceName.ClassName.


  27. What is a nested interface?

    An interface or a class can have another interface. Such an interface is known as nested interface or a member interface.When a nested interface is used outside, it must be used as a fully qualified name i.e. must be qualified by the name of the class or interface of which it is a member.

    Read more about nested interface here.

  28. What is a marker interface?

    A marker interface is an interface that has no method declarations or fields in it. It is used as a tag to let the compiler know it needs to add some special behavior to the class implementing marker interface. That is why marker interface is also known as tag interface.

    Read more about marker interfaces here.

  29. What is an abstract class?

    An abstract class is a class that is declared using the abstract keyword. An abstract class may contain methods without any implementation, called abstract methods.

    Read more about abstract class here.

  30. Is it possible to have abstract method in a class that is not abstract?

    No. If there is even a single abstract method in a class that class has to be declared as abstract.

    Read more about abstract class here.

  31. Is it possible to instantiate an abstract class?

    No. An abstract class can not be instantiated on its own, but abstract class can be used to create object references.

    Read more about abstract class here.

  32. Is it possible to have an abstract class without any abstract method?

    Yes. Even if there are no abstract methods in a class that class can still be declared as abstract. That abstract class still can not be instantiated.

    Read more about abstract class here.

  33. Can you use abstract and final both with a method?

    No. The whole idea of having a abstract method in a class is that it would be implemented by the inheriting class. Whereas making a method final means it can't be overridden thus can't be provided implementation in inheriting class. So using both of them is not possible.

    Read more about abstract class here and about final here

  34. What are the differences between abstract class and interface?

    Abstract Class Interface
    Methods Abstract class can have both abstract and non-abstract methods. Interface can have abstract methods only.
    Note: From Java 8 interfaces can have default methods and static methods.
    Access Modifiers Abstract class methods can have public, protected, private and default modifier apart from abstarct methods. In interface methods are by default public abstract only.
    Variables Abstract class fields can be non-static or non-final. In interface all the fields are by default public, static, final.
    Implementation Abstract class may have some methods with implementation and some methods as abstract. In interface all the methods are by default abstract, where only method signature is provided. Note: From Java 8 interfaces can have default methods and static methods.
    Constructor Abstract class have a constructor, it may be user supplied or default in case no constructor is written by a user. Interface can't have a constructor.
    Multiple Inheritance Abstract class can extend at most one class and implement one or more interfaces. Interface can only extend one or more interfaces.
    Abstraction Abstract class can provide both partial or full abstraction. Interface provides full abstraction as no implementation is provided for any of the method.
    Extends/Implements Abstract class are extended by the sub-classes. Sub-classes need to provide implementation for all the abstract methods of the extended abstract class or be declared as abstract itself. Interface is implemented by a class and the implementing class needs to provide implementation for all the methods declared in an interface. If a class does not implement all the methods of interface then that class must be declared as abstract.
    Easy to evolve Abstract class was considered easy to evolve as abstract classes could add new methods and provide default implementation to those methods. Interface was not considered easy to evolve as, in the case of adding new method to an interface, all the implementing classes had to be changed to provide implementation for the new method. With Java 8 even interfaces can have default methods so that issue has been addresses.


  35. What is Static variable in Java?

    A variable declared as static is associated with the class rather than with any object. When objects of its class are created, copy of static variable is not created per object. All objects of the class share the same static variable.

    Read more about static keyword here.

  36. What is static method in Java?

    A static method is associated with the class rather than objects of the class. Static method can be called directly with the class name ClassName.static_method() rather than with the object of the class.

    Read more about static method here.

  37. What is static block in Java?

    A static block in a class is executed only once, when the class is first loaded, even before the main method.

    Example of static block

    public class StaticDemo {
    // static blank final variable
     static final int i;
     static int b;
    static {
      System.out.println("in static block");
      i = 5;
      b = i * 5;
      System.out.println("Values " + i + " " +  b);
     }
    }
    
    Read more about static block here.

  38. Can we have static variable inside a method?

    No. Since static variables belong to a class where as variables declared inside a method are local variables and belong to that method. So variables inside a method can be declared as final, but not static, public, protected or private.

    Read more about static keyword here.

  39. Why can't we access non-static variable from static method?
    OR
    Why non-static variable can not be accessed from main method in Java?

    Static methods or fields can be accessed without even creating an instance of the class, we just need to qualify the static member with the class name and access it. But non-static members need instance of the class to be created to come into existence. That is the reason why non-static field or method can not be called from the static context.

    Read more about Static reference to the non-static method or field error here.

  40. Can we overload static method?

    Static methods can be overloaded just as 'instance methods'. So it is possible to have two or more static methods having the same name, but the parameters are different in types or number.

    Read more about static overloading here.

  41. Can we override static method?

    Static methods can not be overridden in Java. Though it is possible to have a static method with same signature in sub-class but in that case sub-class method hides the super class method rather than overriding it.

    Read more about static method overriding here.

  42. Why main method is static in Java?

    When a class is loaded JVM needs an entry point (main method). JVM needs to access that main method with out creating an instance of the class, that is why main method is static.
    If it is not declared as static then instance of the main class has to be created which may cause ambiguity.

    public class A {
     private int i;
     A(int i){
      this.i = i;
     }
     public static void main(String args[]){
     }
    }
    

    Here in the class there is a constructor with one argument i. Now in order to create an object of the class what should be passed as i? To avoid these types of ambiguities it doesn't make sense for the JVM to have to create an object of the class before the entry point (main method) is called. That's why main method is static.

    Read more about Why main method is static here.

  43. What is static import in Java?

    In order to access any static member (static field or method) of the class, it is necessary to qualify references with the class they came from.
    As exp. - ClassName.static_method()

    With static import feature of Java 5, members defined in a class as public static can be used without qualifying it with the class name, in any Java class which does a static import. This shortens the syntax required to use a static member.

    Read more about static import in Java here.

  44. What is final in Java?

    final keyword in java has its usage in preventing the user from modifying a field, method or class.

    • final field - A variable declared as final prevents the content of that variable being modified.
    • final method - A method declared as final prevents the user from overriding that method.
    • final class - A class declared as final can not be extended thus prevents inheritance.

    Read more about final keyword here.

  45. What is a final blank variable?

    A final variable can be initialized only once but it can be done in two ways.

    • Value is assigned when the variable is declared.
    • Value is assigned with in a constructor.
    A final variable that has not been assigned a value while declaring a variable is called blank final variable, in that case it forces the constructor to initialize it.

    Read more about final keyword here.

  46. What if a list is declared as final, is it possible to add or remove values from that list?

    When an object reference variable is declared as final, object fields can still be changed but the reference can't be changed.
    So yes it is possible to add or remove values from the list even if the list is declared as final.

    But we can't change the reference of that list.
    As Exp.

    final List tempList = new Arraylist();
    tempList.add("1"); // permitted
    tempList = new ArrayList()// This will result in an error as we are trying to change the reference
    

  47. What is a final method?

    A method can be declared as final in order to avoid method overriding. Method declared as final in super class cannot be overridden in subclass.

    Read more about final method here.

  48. What is a final class?

    A class declared as final can't be extended thus avoiding inheritance altogether.
    If creator of the class is sure that the class has all the required functionality and should be used as it is with out extending it then it should be declared as final.

    Read more about final class here.

  49. What is covariant return type?

    Before Java 5, when you override a superclass method in a subclass the method signature had to be exactly same, i.e., the name, argument types and return type of the overriding method in the sub-class had to be exactly same as that of the super-class method.

    This is relaxed a bit in Java 5 in case of return type. The sub-class method's return type may be different from super-class method's return type but the return type of the subclass should be a subtype of return type of super class method. Which means, if method in the super-class has return type R1 and the overriding method in the subclass has return type R2 then R2 must be the subtype of R1. That is known as covariant return type.

    Read more about covariant return type here.

  50. What is strictfp in Java?

    strictfp is a keyword in Java that restricts floating-point calculations to ensure portability. Prior to JVM 1.2, floating-point calculations were strict; which meant, all intermediate floating-point results were represented as IEEE single or double precisions only. As a consequence, errors of calculation (round-off errors), overflows and underflows would occur with greater frequency than in architectures which did intermediate calculations in greater precision.

    Since JVM 1.2, intermediate computations are not limited to the standard 32 bit and 64 bit precisions. On platforms that can handle other representations e.g. 80-bit double extended on x86 or x86-64 platforms, those representations can be used, helping to prevent round-off errors and overflows, thereby increasing precision.

    Read more about strictfp in Java here.

  51. What is serialization and deserialization in Java?

    Object serialization is the mechanism of converting object into byte stream. Where as the reverse process of constituting the object from those bytes is known as deserialization.

    Read more about serialization in Java here.

  52. What are the benefits of serialization?

    Once an object is converted to a byte stream those bytes can be -

    • Transmitted from one JVM to another where the object can be reconstituted using those bytes and used in further processing.
    • Stored on a disk/DB for further use.
    Read more about serialization in Java here.

  53. When a serialized object is transmitted across the network where different operating system is used will it work?

    Yes serialization offers that portability. When a serialized object is transmitted across the network the serialization mechanism will take into account the differences in operating systems. Thus an object converted into byte streams in Windows OS can be transmitted across the network and deserialized into an object in the Unix operating system.

    Read more about serialization in Java here.

  54. What is Serializable interface in Java?

    Serializable interface is a marker interface and does not have any field or method. It is part of java.io package.
    Any class whose object has to be serialized should implement Serializable interface.

    Read more about marker interface here.

  55. Suppose I have a Person class in which Address class object is referred. Person class implements Serializable interface but Address class doesn't. Will you be able to serialize a Person object in that case?

    No, in this case you will get exception (java.io.NotSerializableException) when you try to serialize the Person class object.
    All the classes which are to be serialized should be implementing Serializable interface. Since in this case Address class whose object is used in Person class doesn't implement Serializable interface an exception will be thrown.


  56. What is ObjectOutputStream class?

    An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. This class provides writeObject method which is used to write an object to the stream.

    Read more about ObjectOutputStream class here.

  57. What is ObjectInputStream class?

    An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. This class provides readObject method which is used to read an object from the stream.

    Read more about ObjectInputStream class here.

  58. What if you provide your own writeObject() and readObject() methods?

    If you want to have some control over the process of serialization and deserialization rather than using the default serialization mechanism which for us, as end user, is automatic then you can add your own implementation of writeObject() and readObject() methods.

    If you add methods writeObject() and readObject(), these methods will be called automatically when the object is serialized and deserialized respectively and provide the serialization mechanism rather than using the default mechanism.


  59. What is transient keyword in Java?

    If you want to exclude any object field from getting serialized you can use transient keyword along with that field. Note that you cannot use transient keyword with methods or local variables it can only be used with member variables.

    Read more about transient here.

  60. What is Externalizable interface in Java?

    Externalizable interface extends the Serializable interface and adds two methods writeExternal() and readExternal(). When you use Externalizable for your serialization, you will implement Externalizable interface and implement writeExternal() and readExternal() methods. These two methods will be called while serializing and deserializing respectively.

    Read more about Externalizable interface here.

  61. How is the class object serialized if it implements Externalizable interface?

    An object which is to be serialized is tested for the Externalizable interface. If the object supports Externalizable, the writeExternal method is called. If the object does not support Externalizable and does implement Serializable, the object is saved using ObjectOutputStream.

    When an Externalizable object is reconstructed, an instance is created using the public no-arg constructor, then the readExternal method called. Serializable objects are restored by reading them from an ObjectInputStream.

    Read more about Externalizable interface here.

  62. What are the conditions when class implements Externalizable interface?

    A default no-arg constructor has to be there in the class while using externalizable as object is created using no-arg constructor while deserializing and then the object is initialized using the logic in readExternal() method.

    Order that is used in writeExternal() method for writing the fields should be maintained in readExternal() method.

    Read more about Externalizable interface here.

  63. What is serialVersionUID?

    The serialVersionUID helps in versioning in a Serializable class. serialVersionUID is declared as a private static final long field in the serializable class.
    Suppose you have some class which is serialized and it changes before it is deserialized. If serialVersionUID was generated for the class when serializing it then the generated serialVersionUID while deserializing will differ as the class has changed.

    Read more about serialVersionUID and how it helps with version control here.

  64. How is serialVersionUID generated?

    The stream-unique identifier is a 64-bit hash of the class name, interface class names, methods, and fields. If you are using IDE like eclipse that will give you an option to add generated serialVersionUID or to add default serialVersionUID.
    If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class.

    Read more about serialVersionUID and how it helps with version control here.

  65. What is Serialization Proxy pattern?

    Its a way of designing your class where proxy pattern defines its serialization mechanism. Rather than serializing the original class you provide functionality to serialize the proxy class instead. For the class which has to be serialized a proxy class is also created which is then serialized instead of the original class.
    In serialization Proxy pattern writeReplace() method and readResolve() methods are used for serialization.

    Read more about Serialization Proxy pattern here.

  66. What is writeReplace() method?

    Serializable classes that use an alternative object (proxy object) when writing an object to the stream should implement writeReplace() method with the exact signature:

    ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException;
    
    This writeReplace() method is invoked by serialization if the method exists and this method is defined within the original class whose object is serialized.

    Read more about Serialization Proxy pattern here.

  67. What is readResolve() method?

    Using serialization proxy pattern you serialize the proxy class instead of the original class. At the time of deserializing it should create the original class object. Thus the classes that need to provide a replacement object when the serialized object is read from the stream should implement readResolve() method with the exact signature.

    ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;
    

    Read more about Serialization Proxy pattern here.

  68. How does Serialization Proxy pattern work?

    Rather than serializing the original class you provide functionality using the writeReplace() method to serialize the proxy class instead. writeReplace() method is implemented in the original class.

    At the time of deserialization proxy object is deserialized and then the readResolve() method is called. That’s where you will have to provide the functionality to create the original class object regular way. readResolve() method is implemented in the proxy class.

    Read more about Serialization Proxy pattern here.

  69. What is cloning process?

    If you want to quickly create an object using the existing object in such a way that you get a new instance (where the reference between the objects is not shared) with the same content for the fields in the new object as in existing object. Then you can clone the existing object to create an exact copy.


  70. How is cloning of the object done in Java?

    In Java you can use clone() method to create an exact copy of the existing object.
    clone() method is defined as protected in the Object class which you must override as public in any derived classes that you want to clone.
    Signature of clone method in Object class - protected native Object clone() throws CloneNotSupportedException;

    Read more about Object cloning in Java here.

  71. What is Cloneable interface?

    Your class, whose object you want to clone, must implement Cloneable interface which is part of java.lang package. Not implementing Cloneable interface will result in CloneNotSupportedException exception being thrown when clone method is called.

    Read more about Object cloning in Java here.

  72. What all methods are there in Cloneable interface?

    Cloneable interface is a marker interface and defines no members of its own.

    Read more about marker interface here.

  73. What are the steps in cloning process?

    There are two required steps if you want to clone any object.

    • You need to call clone() method of the Object class or provide your own implementation by overriding the clone() method in your class.
    • Your class, whose object you want to clone, must implement Cloneable interface.

    Read more about Object cloning in Java here.

  74. What are the advantages of cloning?

    If you have an object, creation of which using the usual way is costly; as example if you have to call DB in order to get data to create and initialize your object. In that scenario rather than hitting DB every time to create your object you can cache it, clone it when object is needed and update it in DB only when needed.


  75. What is Shallow copy?

    If the class whose object you want to clone has reference to other class objects then those reference are shared.
    When you clone an object all the values for the fields are copied to the cloned object. Since Java is pass by value, if the field value is a reference to an object (a memory address) it copies that reference to the field of the cloned object. In that case referenced field is shared between both objects and any change made to the referenced field will be reflected in the other object too.
    This process of cloning when the field values are copied to the new object is known as shallow copy.

    Read more about Shallow copy here.

  76. What is deep copy?

    If you don’t want references of object being copied during the cloning process then option is deep copy. When a deep copy is done objects referenced by the cloned object are distinct from those referenced by original object, and independent.
    Deep copies are more expensive, as you need to create additional objects, and can be substantially more complicated, due to references possibly forming a complicated graph.

    Read more about deep copy here.

Related Topics

  1. Java OOP interview questions
  2. Java String interview questions
  3. Java Exception Handling interview questions
  4. Java Multi-threading interview questions
  5. Java Collections interview questions
  6. Java Concurrency interview questions

5 comments:

  1. wow really nice. It will be helpful for the people those who are ready to crack the interview and please also for remind what they have learned throughout concept.

    SEO Training in Chennai

    ReplyDelete
  2. Thanks for this blog. All screenshots can explain the full blogs easily. This is very easy to understand. Using this screen shots know the details becomes easy.
    Web Designing Training in Chennai

    ReplyDelete
  3. This blog explains the details about changing the ways of doing that business. That is understand well and doing some different process. Provides he best output of others. Thanks for this blog.

    iOS App Development Company


    ReplyDelete

  4. I wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.

    Android App Development Company

    ReplyDelete
  5. it is really amazing...thanks for sharing....provide more useful information...
    Mobile app development company

    ReplyDelete